Bug Summary

File:clang/lib/Sema/SemaExpr.cpp
Warning:line 9982, column 26
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 -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-26-234817-15343-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/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/ADT/STLExtras.h"
50#include "llvm/ADT/StringExtras.h"
51#include "llvm/Support/ConvertUTF.h"
52#include "llvm/Support/SaveAndRestore.h"
53
54using namespace clang;
55using namespace sema;
56using llvm::RoundingMode;
57
58/// Determine whether the use of this declaration is valid, without
59/// emitting diagnostics.
60bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
61 // See if this is an auto-typed variable whose initializer we are parsing.
62 if (ParsingInitForAutoVars.count(D))
63 return false;
64
65 // See if this is a deleted function.
66 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
67 if (FD->isDeleted())
68 return false;
69
70 // If the function has a deduced return type, and we can't deduce it,
71 // then we can't use it either.
72 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
73 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
74 return false;
75
76 // See if this is an aligned allocation/deallocation function that is
77 // unavailable.
78 if (TreatUnavailableAsInvalid &&
79 isUnavailableAlignedAllocationFunction(*FD))
80 return false;
81 }
82
83 // See if this function is unavailable.
84 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
85 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
86 return false;
87
88 if (isa<UnresolvedUsingIfExistsDecl>(D))
89 return false;
90
91 return true;
92}
93
94static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
95 // Warn if this is used but marked unused.
96 if (const auto *A = D->getAttr<UnusedAttr>()) {
97 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
98 // should diagnose them.
99 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
100 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
101 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
102 if (DC && !DC->hasAttr<UnusedAttr>())
103 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
104 }
105 }
106}
107
108/// Emit a note explaining that this function is deleted.
109void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
110 assert(Decl && Decl->isDeleted())(static_cast <bool> (Decl && Decl->isDeleted
()) ? void (0) : __assert_fail ("Decl && Decl->isDeleted()"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 110, __extension__ __PRETTY_FUNCTION__))
;
111
112 if (Decl->isDefaulted()) {
113 // If the method was explicitly defaulted, point at that declaration.
114 if (!Decl->isImplicit())
115 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
116
117 // Try to diagnose why this special member function was implicitly
118 // deleted. This might fail, if that reason no longer applies.
119 DiagnoseDeletedDefaultedFunction(Decl);
120 return;
121 }
122
123 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
124 if (Ctor && Ctor->isInheritingConstructor())
125 return NoteDeletedInheritingConstructor(Ctor);
126
127 Diag(Decl->getLocation(), diag::note_availability_specified_here)
128 << Decl << 1;
129}
130
131/// Determine whether a FunctionDecl was ever declared with an
132/// explicit storage class.
133static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
134 for (auto I : D->redecls()) {
135 if (I->getStorageClass() != SC_None)
136 return true;
137 }
138 return false;
139}
140
141/// Check whether we're in an extern inline function and referring to a
142/// variable or function with internal linkage (C11 6.7.4p3).
143///
144/// This is only a warning because we used to silently accept this code, but
145/// in many cases it will not behave correctly. This is not enabled in C++ mode
146/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
147/// and so while there may still be user mistakes, most of the time we can't
148/// prove that there are errors.
149static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
150 const NamedDecl *D,
151 SourceLocation Loc) {
152 // This is disabled under C++; there are too many ways for this to fire in
153 // contexts where the warning is a false positive, or where it is technically
154 // correct but benign.
155 if (S.getLangOpts().CPlusPlus)
156 return;
157
158 // Check if this is an inlined function or method.
159 FunctionDecl *Current = S.getCurFunctionDecl();
160 if (!Current)
161 return;
162 if (!Current->isInlined())
163 return;
164 if (!Current->isExternallyVisible())
165 return;
166
167 // Check if the decl has internal linkage.
168 if (D->getFormalLinkage() != InternalLinkage)
169 return;
170
171 // Downgrade from ExtWarn to Extension if
172 // (1) the supposedly external inline function is in the main file,
173 // and probably won't be included anywhere else.
174 // (2) the thing we're referencing is a pure function.
175 // (3) the thing we're referencing is another inline function.
176 // This last can give us false negatives, but it's better than warning on
177 // wrappers for simple C library functions.
178 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
179 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
180 if (!DowngradeWarning && UsedFn)
181 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
182
183 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
184 : diag::ext_internal_in_extern_inline)
185 << /*IsVar=*/!UsedFn << D;
186
187 S.MaybeSuggestAddingStaticToDecl(Current);
188
189 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
190 << D;
191}
192
193void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
194 const FunctionDecl *First = Cur->getFirstDecl();
195
196 // Suggest "static" on the function, if possible.
197 if (!hasAnyExplicitStorageClass(First)) {
198 SourceLocation DeclBegin = First->getSourceRange().getBegin();
199 Diag(DeclBegin, diag::note_convert_inline_to_static)
200 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
201 }
202}
203
204/// Determine whether the use of this declaration is valid, and
205/// emit any corresponding diagnostics.
206///
207/// This routine diagnoses various problems with referencing
208/// declarations that can occur when using a declaration. For example,
209/// it might warn if a deprecated or unavailable declaration is being
210/// used, or produce an error (and return true) if a C++0x deleted
211/// function is being used.
212///
213/// \returns true if there was an error (this declaration cannot be
214/// referenced), false otherwise.
215///
216bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
217 const ObjCInterfaceDecl *UnknownObjCClass,
218 bool ObjCPropertyAccess,
219 bool AvoidPartialAvailabilityChecks,
220 ObjCInterfaceDecl *ClassReceiver) {
221 SourceLocation Loc = Locs.front();
222 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
223 // If there were any diagnostics suppressed by template argument deduction,
224 // emit them now.
225 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
226 if (Pos != SuppressedDiagnostics.end()) {
227 for (const PartialDiagnosticAt &Suppressed : Pos->second)
228 Diag(Suppressed.first, Suppressed.second);
229
230 // Clear out the list of suppressed diagnostics, so that we don't emit
231 // them again for this specialization. However, we don't obsolete this
232 // entry from the table, because we want to avoid ever emitting these
233 // diagnostics again.
234 Pos->second.clear();
235 }
236
237 // C++ [basic.start.main]p3:
238 // The function 'main' shall not be used within a program.
239 if (cast<FunctionDecl>(D)->isMain())
240 Diag(Loc, diag::ext_main_used);
241
242 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
243 }
244
245 // See if this is an auto-typed variable whose initializer we are parsing.
246 if (ParsingInitForAutoVars.count(D)) {
247 if (isa<BindingDecl>(D)) {
248 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
249 << D->getDeclName();
250 } else {
251 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
252 << D->getDeclName() << cast<VarDecl>(D)->getType();
253 }
254 return true;
255 }
256
257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
258 // See if this is a deleted function.
259 if (FD->isDeleted()) {
260 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
261 if (Ctor && Ctor->isInheritingConstructor())
262 Diag(Loc, diag::err_deleted_inherited_ctor_use)
263 << Ctor->getParent()
264 << Ctor->getInheritedConstructor().getConstructor()->getParent();
265 else
266 Diag(Loc, diag::err_deleted_function_use);
267 NoteDeletedFunction(FD);
268 return true;
269 }
270
271 // [expr.prim.id]p4
272 // A program that refers explicitly or implicitly to a function with a
273 // trailing requires-clause whose constraint-expression is not satisfied,
274 // other than to declare it, is ill-formed. [...]
275 //
276 // See if this is a function with constraints that need to be satisfied.
277 // Check this before deducing the return type, as it might instantiate the
278 // definition.
279 if (FD->getTrailingRequiresClause()) {
280 ConstraintSatisfaction Satisfaction;
281 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
282 // A diagnostic will have already been generated (non-constant
283 // constraint expression, for example)
284 return true;
285 if (!Satisfaction.IsSatisfied) {
286 Diag(Loc,
287 diag::err_reference_to_function_with_unsatisfied_constraints)
288 << D;
289 DiagnoseUnsatisfiedConstraint(Satisfaction);
290 return true;
291 }
292 }
293
294 // If the function has a deduced return type, and we can't deduce it,
295 // then we can't use it either.
296 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
297 DeduceReturnType(FD, Loc))
298 return true;
299
300 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
301 return true;
302
303 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
304 return true;
305 }
306
307 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
308 // Lambdas are only default-constructible or assignable in C++2a onwards.
309 if (MD->getParent()->isLambda() &&
310 ((isa<CXXConstructorDecl>(MD) &&
311 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
312 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
313 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
314 << !isa<CXXConstructorDecl>(MD);
315 }
316 }
317
318 auto getReferencedObjCProp = [](const NamedDecl *D) ->
319 const ObjCPropertyDecl * {
320 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
321 return MD->findPropertyDecl();
322 return nullptr;
323 };
324 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
325 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
326 return true;
327 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
328 return true;
329 }
330
331 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
332 // Only the variables omp_in and omp_out are allowed in the combiner.
333 // Only the variables omp_priv and omp_orig are allowed in the
334 // initializer-clause.
335 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
336 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
337 isa<VarDecl>(D)) {
338 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
339 << getCurFunction()->HasOMPDeclareReductionCombiner;
340 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
341 return true;
342 }
343
344 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
345 // List-items in map clauses on this construct may only refer to the declared
346 // variable var and entities that could be referenced by a procedure defined
347 // at the same location
348 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
349 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
350 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
351 << getOpenMPDeclareMapperVarName();
352 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
353 return true;
354 }
355
356 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
357 Diag(Loc, diag::err_use_of_empty_using_if_exists);
358 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
359 return true;
360 }
361
362 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
363 AvoidPartialAvailabilityChecks, ClassReceiver);
364
365 DiagnoseUnusedOfDecl(*this, D, Loc);
366
367 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
368
369 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
370 if (auto *VD = dyn_cast<ValueDecl>(D))
371 checkDeviceDecl(VD, Loc);
372
373 if (!Context.getTargetInfo().isTLSSupported())
374 if (const auto *VD = dyn_cast<VarDecl>(D))
375 if (VD->getTLSKind() != VarDecl::TLS_None)
376 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
377 }
378
379 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
380 !isUnevaluatedContext()) {
381 // C++ [expr.prim.req.nested] p3
382 // A local parameter shall only appear as an unevaluated operand
383 // (Clause 8) within the constraint-expression.
384 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
385 << D;
386 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
387 return true;
388 }
389
390 return false;
391}
392
393/// DiagnoseSentinelCalls - This routine checks whether a call or
394/// message-send is to a declaration with the sentinel attribute, and
395/// if so, it checks that the requirements of the sentinel are
396/// satisfied.
397void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
398 ArrayRef<Expr *> Args) {
399 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
400 if (!attr)
401 return;
402
403 // The number of formal parameters of the declaration.
404 unsigned numFormalParams;
405
406 // The kind of declaration. This is also an index into a %select in
407 // the diagnostic.
408 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
409
410 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
411 numFormalParams = MD->param_size();
412 calleeType = CT_Method;
413 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
414 numFormalParams = FD->param_size();
415 calleeType = CT_Function;
416 } else if (isa<VarDecl>(D)) {
417 QualType type = cast<ValueDecl>(D)->getType();
418 const FunctionType *fn = nullptr;
419 if (const PointerType *ptr = type->getAs<PointerType>()) {
420 fn = ptr->getPointeeType()->getAs<FunctionType>();
421 if (!fn) return;
422 calleeType = CT_Function;
423 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
424 fn = ptr->getPointeeType()->castAs<FunctionType>();
425 calleeType = CT_Block;
426 } else {
427 return;
428 }
429
430 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
431 numFormalParams = proto->getNumParams();
432 } else {
433 numFormalParams = 0;
434 }
435 } else {
436 return;
437 }
438
439 // "nullPos" is the number of formal parameters at the end which
440 // effectively count as part of the variadic arguments. This is
441 // useful if you would prefer to not have *any* formal parameters,
442 // but the language forces you to have at least one.
443 unsigned nullPos = attr->getNullPos();
444 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(static_cast <bool> ((nullPos == 0 || nullPos == 1) &&
"invalid null position on sentinel") ? void (0) : __assert_fail
("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 444, __extension__ __PRETTY_FUNCTION__))
;
445 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
446
447 // The number of arguments which should follow the sentinel.
448 unsigned numArgsAfterSentinel = attr->getSentinel();
449
450 // If there aren't enough arguments for all the formal parameters,
451 // the sentinel, and the args after the sentinel, complain.
452 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
453 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
454 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
455 return;
456 }
457
458 // Otherwise, find the sentinel expression.
459 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
460 if (!sentinelExpr) return;
461 if (sentinelExpr->isValueDependent()) return;
462 if (Context.isSentinelNullExpr(sentinelExpr)) return;
463
464 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
465 // or 'NULL' if those are actually defined in the context. Only use
466 // 'nil' for ObjC methods, where it's much more likely that the
467 // variadic arguments form a list of object pointers.
468 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
469 std::string NullValue;
470 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
471 NullValue = "nil";
472 else if (getLangOpts().CPlusPlus11)
473 NullValue = "nullptr";
474 else if (PP.isMacroDefined("NULL"))
475 NullValue = "NULL";
476 else
477 NullValue = "(void*) 0";
478
479 if (MissingNilLoc.isInvalid())
480 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
481 else
482 Diag(MissingNilLoc, diag::warn_missing_sentinel)
483 << int(calleeType)
484 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
485 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
486}
487
488SourceRange Sema::getExprRange(Expr *E) const {
489 return E ? E->getSourceRange() : SourceRange();
490}
491
492//===----------------------------------------------------------------------===//
493// Standard Promotions and Conversions
494//===----------------------------------------------------------------------===//
495
496/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
497ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
498 // Handle any placeholder expressions which made it here.
499 if (E->getType()->isPlaceholderType()) {
500 ExprResult result = CheckPlaceholderExpr(E);
501 if (result.isInvalid()) return ExprError();
502 E = result.get();
503 }
504
505 QualType Ty = E->getType();
506 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"
) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 506, __extension__ __PRETTY_FUNCTION__))
;
507
508 if (Ty->isFunctionType()) {
509 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
510 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
511 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
512 return ExprError();
513
514 E = ImpCastExprToType(E, Context.getPointerType(Ty),
515 CK_FunctionToPointerDecay).get();
516 } else if (Ty->isArrayType()) {
517 // In C90 mode, arrays only promote to pointers if the array expression is
518 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
519 // type 'array of type' is converted to an expression that has type 'pointer
520 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
521 // that has type 'array of type' ...". The relevant change is "an lvalue"
522 // (C90) to "an expression" (C99).
523 //
524 // C++ 4.2p1:
525 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
526 // T" can be converted to an rvalue of type "pointer to T".
527 //
528 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
529 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
530 CK_ArrayToPointerDecay);
531 if (Res.isInvalid())
532 return ExprError();
533 E = Res.get();
534 }
535 }
536 return E;
537}
538
539static void CheckForNullPointerDereference(Sema &S, Expr *E) {
540 // Check to see if we are dereferencing a null pointer. If so,
541 // and if not volatile-qualified, this is undefined behavior that the
542 // optimizer will delete, so warn about it. People sometimes try to use this
543 // to get a deterministic trap and are surprised by clang's behavior. This
544 // only handles the pattern "*null", which is a very syntactic check.
545 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
546 if (UO && UO->getOpcode() == UO_Deref &&
547 UO->getSubExpr()->getType()->isPointerType()) {
548 const LangAS AS =
549 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
550 if ((!isTargetAddressSpace(AS) ||
551 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
552 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
553 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
554 !UO->getType().isVolatileQualified()) {
555 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
556 S.PDiag(diag::warn_indirection_through_null)
557 << UO->getSubExpr()->getSourceRange());
558 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
559 S.PDiag(diag::note_indirection_through_null));
560 }
561 }
562}
563
564static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
565 SourceLocation AssignLoc,
566 const Expr* RHS) {
567 const ObjCIvarDecl *IV = OIRE->getDecl();
568 if (!IV)
569 return;
570
571 DeclarationName MemberName = IV->getDeclName();
572 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
573 if (!Member || !Member->isStr("isa"))
574 return;
575
576 const Expr *Base = OIRE->getBase();
577 QualType BaseType = Base->getType();
578 if (OIRE->isArrow())
579 BaseType = BaseType->getPointeeType();
580 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
581 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
582 ObjCInterfaceDecl *ClassDeclared = nullptr;
583 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
584 if (!ClassDeclared->getSuperClass()
585 && (*ClassDeclared->ivar_begin()) == IV) {
586 if (RHS) {
587 NamedDecl *ObjectSetClass =
588 S.LookupSingleName(S.TUScope,
589 &S.Context.Idents.get("object_setClass"),
590 SourceLocation(), S.LookupOrdinaryName);
591 if (ObjectSetClass) {
592 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
595 "object_setClass(")
596 << FixItHint::CreateReplacement(
597 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
598 << FixItHint::CreateInsertion(RHSLocEnd, ")");
599 }
600 else
601 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
602 } else {
603 NamedDecl *ObjectGetClass =
604 S.LookupSingleName(S.TUScope,
605 &S.Context.Idents.get("object_getClass"),
606 SourceLocation(), S.LookupOrdinaryName);
607 if (ObjectGetClass)
608 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
609 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
610 "object_getClass(")
611 << FixItHint::CreateReplacement(
612 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
613 else
614 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
615 }
616 S.Diag(IV->getLocation(), diag::note_ivar_decl);
617 }
618 }
619}
620
621ExprResult Sema::DefaultLvalueConversion(Expr *E) {
622 // Handle any placeholder expressions which made it here.
623 if (E->getType()->isPlaceholderType()) {
624 ExprResult result = CheckPlaceholderExpr(E);
625 if (result.isInvalid()) return ExprError();
626 E = result.get();
627 }
628
629 // C++ [conv.lval]p1:
630 // A glvalue of a non-function, non-array type T can be
631 // converted to a prvalue.
632 if (!E->isGLValue()) return E;
633
634 QualType T = E->getType();
635 assert(!T.isNull() && "r-value conversion on typeless expression?")(static_cast <bool> (!T.isNull() && "r-value conversion on typeless expression?"
) ? void (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 635, __extension__ __PRETTY_FUNCTION__))
;
636
637 // lvalue-to-rvalue conversion cannot be applied to function or array types.
638 if (T->isFunctionType() || T->isArrayType())
639 return E;
640
641 // We don't want to throw lvalue-to-rvalue casts on top of
642 // expressions of certain types in C++.
643 if (getLangOpts().CPlusPlus &&
644 (E->getType() == Context.OverloadTy ||
645 T->isDependentType() ||
646 T->isRecordType()))
647 return E;
648
649 // The C standard is actually really unclear on this point, and
650 // DR106 tells us what the result should be but not why. It's
651 // generally best to say that void types just doesn't undergo
652 // lvalue-to-rvalue at all. Note that expressions of unqualified
653 // 'void' type are never l-values, but qualified void can be.
654 if (T->isVoidType())
655 return E;
656
657 // OpenCL usually rejects direct accesses to values of 'half' type.
658 if (getLangOpts().OpenCL &&
659 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
660 T->isHalfType()) {
661 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
662 << 0 << T;
663 return ExprError();
664 }
665
666 CheckForNullPointerDereference(*this, E);
667 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
668 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
669 &Context.Idents.get("object_getClass"),
670 SourceLocation(), LookupOrdinaryName);
671 if (ObjectGetClass)
672 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
673 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
674 << FixItHint::CreateReplacement(
675 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
676 else
677 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
678 }
679 else if (const ObjCIvarRefExpr *OIRE =
680 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
681 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
682
683 // C++ [conv.lval]p1:
684 // [...] If T is a non-class type, the type of the prvalue is the
685 // cv-unqualified version of T. Otherwise, the type of the
686 // rvalue is T.
687 //
688 // C99 6.3.2.1p2:
689 // If the lvalue has qualified type, the value has the unqualified
690 // version of the type of the lvalue; otherwise, the value has the
691 // type of the lvalue.
692 if (T.hasQualifiers())
693 T = T.getUnqualifiedType();
694
695 // Under the MS ABI, lock down the inheritance model now.
696 if (T->isMemberPointerType() &&
697 Context.getTargetInfo().getCXXABI().isMicrosoft())
698 (void)isCompleteType(E->getExprLoc(), T);
699
700 ExprResult Res = CheckLValueToRValueConversionOperand(E);
701 if (Res.isInvalid())
702 return Res;
703 E = Res.get();
704
705 // Loading a __weak object implicitly retains the value, so we need a cleanup to
706 // balance that.
707 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
708 Cleanup.setExprNeedsCleanups(true);
709
710 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
711 Cleanup.setExprNeedsCleanups(true);
712
713 // C++ [conv.lval]p3:
714 // If T is cv std::nullptr_t, the result is a null pointer constant.
715 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
716 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
717 CurFPFeatureOverrides());
718
719 // C11 6.3.2.1p2:
720 // ... if the lvalue has atomic type, the value has the non-atomic version
721 // of the type of the lvalue ...
722 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
723 T = Atomic->getValueType().getUnqualifiedType();
724 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
725 nullptr, VK_PRValue, FPOptionsOverride());
726 }
727
728 return Res;
729}
730
731ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
732 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
733 if (Res.isInvalid())
734 return ExprError();
735 Res = DefaultLvalueConversion(Res.get());
736 if (Res.isInvalid())
737 return ExprError();
738 return Res;
739}
740
741/// CallExprUnaryConversions - a special case of an unary conversion
742/// performed on a function designator of a call expression.
743ExprResult Sema::CallExprUnaryConversions(Expr *E) {
744 QualType Ty = E->getType();
745 ExprResult Res = E;
746 // Only do implicit cast for a function type, but not for a pointer
747 // to function type.
748 if (Ty->isFunctionType()) {
749 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
750 CK_FunctionToPointerDecay);
751 if (Res.isInvalid())
752 return ExprError();
753 }
754 Res = DefaultLvalueConversion(Res.get());
755 if (Res.isInvalid())
756 return ExprError();
757 return Res.get();
758}
759
760/// UsualUnaryConversions - Performs various conversions that are common to most
761/// operators (C99 6.3). The conversions of array and function types are
762/// sometimes suppressed. For example, the array->pointer conversion doesn't
763/// apply if the array is an argument to the sizeof or address (&) operators.
764/// In these instances, this routine should *not* be called.
765ExprResult Sema::UsualUnaryConversions(Expr *E) {
766 // First, convert to an r-value.
767 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
768 if (Res.isInvalid())
769 return ExprError();
770 E = Res.get();
771
772 QualType Ty = E->getType();
773 assert(!Ty.isNull() && "UsualUnaryConversions - missing type")(static_cast <bool> (!Ty.isNull() && "UsualUnaryConversions - missing type"
) ? void (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 773, __extension__ __PRETTY_FUNCTION__))
;
774
775 // Half FP have to be promoted to float unless it is natively supported
776 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
777 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
778
779 // Try to perform integral promotions if the object has a theoretically
780 // promotable type.
781 if (Ty->isIntegralOrUnscopedEnumerationType()) {
782 // C99 6.3.1.1p2:
783 //
784 // The following may be used in an expression wherever an int or
785 // unsigned int may be used:
786 // - an object or expression with an integer type whose integer
787 // conversion rank is less than or equal to the rank of int
788 // and unsigned int.
789 // - A bit-field of type _Bool, int, signed int, or unsigned int.
790 //
791 // If an int can represent all values of the original type, the
792 // value is converted to an int; otherwise, it is converted to an
793 // unsigned int. These are called the integer promotions. All
794 // other types are unchanged by the integer promotions.
795
796 QualType PTy = Context.isPromotableBitField(E);
797 if (!PTy.isNull()) {
798 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
799 return E;
800 }
801 if (Ty->isPromotableIntegerType()) {
802 QualType PT = Context.getPromotedIntegerType(Ty);
803 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
804 return E;
805 }
806 }
807 return E;
808}
809
810/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
811/// do not have a prototype. Arguments that have type float or __fp16
812/// are promoted to double. All other argument types are converted by
813/// UsualUnaryConversions().
814ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
815 QualType Ty = E->getType();
816 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultArgumentPromotion - missing type"
) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 816, __extension__ __PRETTY_FUNCTION__))
;
817
818 ExprResult Res = UsualUnaryConversions(E);
819 if (Res.isInvalid())
820 return ExprError();
821 E = Res.get();
822
823 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
824 // promote to double.
825 // Note that default argument promotion applies only to float (and
826 // half/fp16); it does not apply to _Float16.
827 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
828 if (BTy && (BTy->getKind() == BuiltinType::Half ||
829 BTy->getKind() == BuiltinType::Float)) {
830 if (getLangOpts().OpenCL &&
831 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
832 if (BTy->getKind() == BuiltinType::Half) {
833 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
834 }
835 } else {
836 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
837 }
838 }
839 if (BTy &&
840 getLangOpts().getExtendIntArgs() ==
841 LangOptions::ExtendArgsKind::ExtendTo64 &&
842 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
843 Context.getTypeSizeInChars(BTy) <
844 Context.getTypeSizeInChars(Context.LongLongTy)) {
845 E = (Ty->isUnsignedIntegerType())
846 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
847 .get()
848 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
849 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&(static_cast <bool> (8 == Context.getTypeSizeInChars(Context
.LongLongTy).getQuantity() && "Unexpected typesize for LongLongTy"
) ? void (0) : __assert_fail ("8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && \"Unexpected typesize for LongLongTy\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 850, __extension__ __PRETTY_FUNCTION__))
850 "Unexpected typesize for LongLongTy")(static_cast <bool> (8 == Context.getTypeSizeInChars(Context
.LongLongTy).getQuantity() && "Unexpected typesize for LongLongTy"
) ? void (0) : __assert_fail ("8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && \"Unexpected typesize for LongLongTy\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 850, __extension__ __PRETTY_FUNCTION__))
;
851 }
852
853 // C++ performs lvalue-to-rvalue conversion as a default argument
854 // promotion, even on class types, but note:
855 // C++11 [conv.lval]p2:
856 // When an lvalue-to-rvalue conversion occurs in an unevaluated
857 // operand or a subexpression thereof the value contained in the
858 // referenced object is not accessed. Otherwise, if the glvalue
859 // has a class type, the conversion copy-initializes a temporary
860 // of type T from the glvalue and the result of the conversion
861 // is a prvalue for the temporary.
862 // FIXME: add some way to gate this entire thing for correctness in
863 // potentially potentially evaluated contexts.
864 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
865 ExprResult Temp = PerformCopyInitialization(
866 InitializedEntity::InitializeTemporary(E->getType()),
867 E->getExprLoc(), E);
868 if (Temp.isInvalid())
869 return ExprError();
870 E = Temp.get();
871 }
872
873 return E;
874}
875
876/// Determine the degree of POD-ness for an expression.
877/// Incomplete types are considered POD, since this check can be performed
878/// when we're in an unevaluated context.
879Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
880 if (Ty->isIncompleteType()) {
881 // C++11 [expr.call]p7:
882 // After these conversions, if the argument does not have arithmetic,
883 // enumeration, pointer, pointer to member, or class type, the program
884 // is ill-formed.
885 //
886 // Since we've already performed array-to-pointer and function-to-pointer
887 // decay, the only such type in C++ is cv void. This also handles
888 // initializer lists as variadic arguments.
889 if (Ty->isVoidType())
890 return VAK_Invalid;
891
892 if (Ty->isObjCObjectType())
893 return VAK_Invalid;
894 return VAK_Valid;
895 }
896
897 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
898 return VAK_Invalid;
899
900 if (Ty.isCXX98PODType(Context))
901 return VAK_Valid;
902
903 // C++11 [expr.call]p7:
904 // Passing a potentially-evaluated argument of class type (Clause 9)
905 // having a non-trivial copy constructor, a non-trivial move constructor,
906 // or a non-trivial destructor, with no corresponding parameter,
907 // is conditionally-supported with implementation-defined semantics.
908 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
909 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
910 if (!Record->hasNonTrivialCopyConstructor() &&
911 !Record->hasNonTrivialMoveConstructor() &&
912 !Record->hasNonTrivialDestructor())
913 return VAK_ValidInCXX11;
914
915 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
916 return VAK_Valid;
917
918 if (Ty->isObjCObjectType())
919 return VAK_Invalid;
920
921 if (getLangOpts().MSVCCompat)
922 return VAK_MSVCUndefined;
923
924 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
925 // permitted to reject them. We should consider doing so.
926 return VAK_Undefined;
927}
928
929void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
930 // Don't allow one to pass an Objective-C interface to a vararg.
931 const QualType &Ty = E->getType();
932 VarArgKind VAK = isValidVarArgType(Ty);
933
934 // Complain about passing non-POD types through varargs.
935 switch (VAK) {
936 case VAK_ValidInCXX11:
937 DiagRuntimeBehavior(
938 E->getBeginLoc(), nullptr,
939 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
940 LLVM_FALLTHROUGH[[gnu::fallthrough]];
941 case VAK_Valid:
942 if (Ty->isRecordType()) {
943 // This is unlikely to be what the user intended. If the class has a
944 // 'c_str' member function, the user probably meant to call that.
945 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
946 PDiag(diag::warn_pass_class_arg_to_vararg)
947 << Ty << CT << hasCStrMethod(E) << ".c_str()");
948 }
949 break;
950
951 case VAK_Undefined:
952 case VAK_MSVCUndefined:
953 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
954 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
955 << getLangOpts().CPlusPlus11 << Ty << CT);
956 break;
957
958 case VAK_Invalid:
959 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
960 Diag(E->getBeginLoc(),
961 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
962 << Ty << CT;
963 else if (Ty->isObjCObjectType())
964 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
965 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
966 << Ty << CT);
967 else
968 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
969 << isa<InitListExpr>(E) << Ty << CT;
970 break;
971 }
972}
973
974/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
975/// will create a trap if the resulting type is not a POD type.
976ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
977 FunctionDecl *FDecl) {
978 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
979 // Strip the unbridged-cast placeholder expression off, if applicable.
980 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
981 (CT == VariadicMethod ||
982 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
983 E = stripARCUnbridgedCast(E);
984
985 // Otherwise, do normal placeholder checking.
986 } else {
987 ExprResult ExprRes = CheckPlaceholderExpr(E);
988 if (ExprRes.isInvalid())
989 return ExprError();
990 E = ExprRes.get();
991 }
992 }
993
994 ExprResult ExprRes = DefaultArgumentPromotion(E);
995 if (ExprRes.isInvalid())
996 return ExprError();
997
998 // Copy blocks to the heap.
999 if (ExprRes.get()->getType()->isBlockPointerType())
1000 maybeExtendBlockObject(ExprRes);
1001
1002 E = ExprRes.get();
1003
1004 // Diagnostics regarding non-POD argument types are
1005 // emitted along with format string checking in Sema::CheckFunctionCall().
1006 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1007 // Turn this into a trap.
1008 CXXScopeSpec SS;
1009 SourceLocation TemplateKWLoc;
1010 UnqualifiedId Name;
1011 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1012 E->getBeginLoc());
1013 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1014 /*HasTrailingLParen=*/true,
1015 /*IsAddressOfOperand=*/false);
1016 if (TrapFn.isInvalid())
1017 return ExprError();
1018
1019 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1020 None, E->getEndLoc());
1021 if (Call.isInvalid())
1022 return ExprError();
1023
1024 ExprResult Comma =
1025 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1026 if (Comma.isInvalid())
1027 return ExprError();
1028 return Comma.get();
1029 }
1030
1031 if (!getLangOpts().CPlusPlus &&
1032 RequireCompleteType(E->getExprLoc(), E->getType(),
1033 diag::err_call_incomplete_argument))
1034 return ExprError();
1035
1036 return E;
1037}
1038
1039/// Converts an integer to complex float type. Helper function of
1040/// UsualArithmeticConversions()
1041///
1042/// \return false if the integer expression is an integer type and is
1043/// successfully converted to the complex type.
1044static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1045 ExprResult &ComplexExpr,
1046 QualType IntTy,
1047 QualType ComplexTy,
1048 bool SkipCast) {
1049 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1050 if (SkipCast) return false;
1051 if (IntTy->isIntegerType()) {
1052 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1053 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1054 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1055 CK_FloatingRealToComplex);
1056 } else {
1057 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1057, __extension__ __PRETTY_FUNCTION__))
;
1058 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1059 CK_IntegralComplexToFloatingComplex);
1060 }
1061 return false;
1062}
1063
1064/// Handle arithmetic conversion with complex types. Helper function of
1065/// UsualArithmeticConversions()
1066static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1067 ExprResult &RHS, QualType LHSType,
1068 QualType RHSType,
1069 bool IsCompAssign) {
1070 // if we have an integer operand, the result is the complex type.
1071 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1072 /*skipCast*/false))
1073 return LHSType;
1074 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1075 /*skipCast*/IsCompAssign))
1076 return RHSType;
1077
1078 // This handles complex/complex, complex/float, or float/complex.
1079 // When both operands are complex, the shorter operand is converted to the
1080 // type of the longer, and that is the type of the result. This corresponds
1081 // to what is done when combining two real floating-point operands.
1082 // The fun begins when size promotion occur across type domains.
1083 // From H&S 6.3.4: When one operand is complex and the other is a real
1084 // floating-point type, the less precise type is converted, within it's
1085 // real or complex domain, to the precision of the other type. For example,
1086 // when combining a "long double" with a "double _Complex", the
1087 // "double _Complex" is promoted to "long double _Complex".
1088
1089 // Compute the rank of the two types, regardless of whether they are complex.
1090 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1091
1092 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1093 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1094 QualType LHSElementType =
1095 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1096 QualType RHSElementType =
1097 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1098
1099 QualType ResultType = S.Context.getComplexType(LHSElementType);
1100 if (Order < 0) {
1101 // Promote the precision of the LHS if not an assignment.
1102 ResultType = S.Context.getComplexType(RHSElementType);
1103 if (!IsCompAssign) {
1104 if (LHSComplexType)
1105 LHS =
1106 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1107 else
1108 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1109 }
1110 } else if (Order > 0) {
1111 // Promote the precision of the RHS.
1112 if (RHSComplexType)
1113 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1114 else
1115 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1116 }
1117 return ResultType;
1118}
1119
1120/// Handle arithmetic conversion from integer to float. Helper function
1121/// of UsualArithmeticConversions()
1122static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1123 ExprResult &IntExpr,
1124 QualType FloatTy, QualType IntTy,
1125 bool ConvertFloat, bool ConvertInt) {
1126 if (IntTy->isIntegerType()) {
1127 if (ConvertInt)
1128 // Convert intExpr to the lhs floating point type.
1129 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1130 CK_IntegralToFloating);
1131 return FloatTy;
1132 }
1133
1134 // Convert both sides to the appropriate complex float.
1135 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1135, __extension__ __PRETTY_FUNCTION__))
;
1136 QualType result = S.Context.getComplexType(FloatTy);
1137
1138 // _Complex int -> _Complex float
1139 if (ConvertInt)
1140 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1141 CK_IntegralComplexToFloatingComplex);
1142
1143 // float -> _Complex float
1144 if (ConvertFloat)
1145 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1146 CK_FloatingRealToComplex);
1147
1148 return result;
1149}
1150
1151/// Handle arithmethic conversion with floating point types. Helper
1152/// function of UsualArithmeticConversions()
1153static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1154 ExprResult &RHS, QualType LHSType,
1155 QualType RHSType, bool IsCompAssign) {
1156 bool LHSFloat = LHSType->isRealFloatingType();
1157 bool RHSFloat = RHSType->isRealFloatingType();
1158
1159 // N1169 4.1.4: If one of the operands has a floating type and the other
1160 // operand has a fixed-point type, the fixed-point operand
1161 // is converted to the floating type [...]
1162 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1163 if (LHSFloat)
1164 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1165 else if (!IsCompAssign)
1166 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1167 return LHSFloat ? LHSType : RHSType;
1168 }
1169
1170 // If we have two real floating types, convert the smaller operand
1171 // to the bigger result.
1172 if (LHSFloat && RHSFloat) {
1173 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1174 if (order > 0) {
1175 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1176 return LHSType;
1177 }
1178
1179 assert(order < 0 && "illegal float comparison")(static_cast <bool> (order < 0 && "illegal float comparison"
) ? void (0) : __assert_fail ("order < 0 && \"illegal float comparison\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1179, __extension__ __PRETTY_FUNCTION__))
;
1180 if (!IsCompAssign)
1181 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1182 return RHSType;
1183 }
1184
1185 if (LHSFloat) {
1186 // Half FP has to be promoted to float unless it is natively supported
1187 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1188 LHSType = S.Context.FloatTy;
1189
1190 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1191 /*ConvertFloat=*/!IsCompAssign,
1192 /*ConvertInt=*/ true);
1193 }
1194 assert(RHSFloat)(static_cast <bool> (RHSFloat) ? void (0) : __assert_fail
("RHSFloat", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1194, __extension__ __PRETTY_FUNCTION__))
;
1195 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1196 /*ConvertFloat=*/ true,
1197 /*ConvertInt=*/!IsCompAssign);
1198}
1199
1200/// Diagnose attempts to convert between __float128, __ibm128 and
1201/// long double if there is no support for such conversion.
1202/// Helper function of UsualArithmeticConversions().
1203static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1204 QualType RHSType) {
1205 // No issue if either is not a floating point type.
1206 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1207 return false;
1208
1209 // No issue if both have the same 128-bit float semantics.
1210 auto *LHSComplex = LHSType->getAs<ComplexType>();
1211 auto *RHSComplex = RHSType->getAs<ComplexType>();
1212
1213 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1214 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1215
1216 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1217 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1218
1219 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1220 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1221 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1222 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1223 return false;
1224
1225 return true;
1226}
1227
1228typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1229
1230namespace {
1231/// These helper callbacks are placed in an anonymous namespace to
1232/// permit their use as function template parameters.
1233ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1234 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1235}
1236
1237ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1238 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1239 CK_IntegralComplexCast);
1240}
1241}
1242
1243/// Handle integer arithmetic conversions. Helper function of
1244/// UsualArithmeticConversions()
1245template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1246static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1247 ExprResult &RHS, QualType LHSType,
1248 QualType RHSType, bool IsCompAssign) {
1249 // The rules for this case are in C99 6.3.1.8
1250 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1251 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1252 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1253 if (LHSSigned == RHSSigned) {
1254 // Same signedness; use the higher-ranked type
1255 if (order >= 0) {
1256 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1257 return LHSType;
1258 } else if (!IsCompAssign)
1259 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1260 return RHSType;
1261 } else if (order != (LHSSigned ? 1 : -1)) {
1262 // The unsigned type has greater than or equal rank to the
1263 // signed type, so use the unsigned type
1264 if (RHSSigned) {
1265 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1266 return LHSType;
1267 } else if (!IsCompAssign)
1268 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1269 return RHSType;
1270 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1271 // The two types are different widths; if we are here, that
1272 // means the signed type is larger than the unsigned type, so
1273 // use the signed type.
1274 if (LHSSigned) {
1275 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1276 return LHSType;
1277 } else if (!IsCompAssign)
1278 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1279 return RHSType;
1280 } else {
1281 // The signed type is higher-ranked than the unsigned type,
1282 // but isn't actually any bigger (like unsigned int and long
1283 // on most 32-bit systems). Use the unsigned type corresponding
1284 // to the signed type.
1285 QualType result =
1286 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1287 RHS = (*doRHSCast)(S, RHS.get(), result);
1288 if (!IsCompAssign)
1289 LHS = (*doLHSCast)(S, LHS.get(), result);
1290 return result;
1291 }
1292}
1293
1294/// Handle conversions with GCC complex int extension. Helper function
1295/// of UsualArithmeticConversions()
1296static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1297 ExprResult &RHS, QualType LHSType,
1298 QualType RHSType,
1299 bool IsCompAssign) {
1300 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1301 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1302
1303 if (LHSComplexInt && RHSComplexInt) {
1304 QualType LHSEltType = LHSComplexInt->getElementType();
1305 QualType RHSEltType = RHSComplexInt->getElementType();
1306 QualType ScalarType =
1307 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1308 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1309
1310 return S.Context.getComplexType(ScalarType);
1311 }
1312
1313 if (LHSComplexInt) {
1314 QualType LHSEltType = LHSComplexInt->getElementType();
1315 QualType ScalarType =
1316 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1317 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1318 QualType ComplexType = S.Context.getComplexType(ScalarType);
1319 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1320 CK_IntegralRealToComplex);
1321
1322 return ComplexType;
1323 }
1324
1325 assert(RHSComplexInt)(static_cast <bool> (RHSComplexInt) ? void (0) : __assert_fail
("RHSComplexInt", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1325, __extension__ __PRETTY_FUNCTION__))
;
1326
1327 QualType RHSEltType = RHSComplexInt->getElementType();
1328 QualType ScalarType =
1329 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1330 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1331 QualType ComplexType = S.Context.getComplexType(ScalarType);
1332
1333 if (!IsCompAssign)
1334 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1335 CK_IntegralRealToComplex);
1336 return ComplexType;
1337}
1338
1339/// Return the rank of a given fixed point or integer type. The value itself
1340/// doesn't matter, but the values must be increasing with proper increasing
1341/// rank as described in N1169 4.1.1.
1342static unsigned GetFixedPointRank(QualType Ty) {
1343 const auto *BTy = Ty->getAs<BuiltinType>();
1344 assert(BTy && "Expected a builtin type.")(static_cast <bool> (BTy && "Expected a builtin type."
) ? void (0) : __assert_fail ("BTy && \"Expected a builtin type.\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1344, __extension__ __PRETTY_FUNCTION__))
;
1345
1346 switch (BTy->getKind()) {
1347 case BuiltinType::ShortFract:
1348 case BuiltinType::UShortFract:
1349 case BuiltinType::SatShortFract:
1350 case BuiltinType::SatUShortFract:
1351 return 1;
1352 case BuiltinType::Fract:
1353 case BuiltinType::UFract:
1354 case BuiltinType::SatFract:
1355 case BuiltinType::SatUFract:
1356 return 2;
1357 case BuiltinType::LongFract:
1358 case BuiltinType::ULongFract:
1359 case BuiltinType::SatLongFract:
1360 case BuiltinType::SatULongFract:
1361 return 3;
1362 case BuiltinType::ShortAccum:
1363 case BuiltinType::UShortAccum:
1364 case BuiltinType::SatShortAccum:
1365 case BuiltinType::SatUShortAccum:
1366 return 4;
1367 case BuiltinType::Accum:
1368 case BuiltinType::UAccum:
1369 case BuiltinType::SatAccum:
1370 case BuiltinType::SatUAccum:
1371 return 5;
1372 case BuiltinType::LongAccum:
1373 case BuiltinType::ULongAccum:
1374 case BuiltinType::SatLongAccum:
1375 case BuiltinType::SatULongAccum:
1376 return 6;
1377 default:
1378 if (BTy->isInteger())
1379 return 0;
1380 llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1380)
;
1381 }
1382}
1383
1384/// handleFixedPointConversion - Fixed point operations between fixed
1385/// point types and integers or other fixed point types do not fall under
1386/// usual arithmetic conversion since these conversions could result in loss
1387/// of precsision (N1169 4.1.4). These operations should be calculated with
1388/// the full precision of their result type (N1169 4.1.6.2.1).
1389static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1390 QualType RHSTy) {
1391 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(static_cast <bool> ((LHSTy->isFixedPointType() || RHSTy
->isFixedPointType()) && "Expected at least one of the operands to be a fixed point type"
) ? 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-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1392, __extension__ __PRETTY_FUNCTION__))
1392 "Expected at least one of the operands to be a fixed point type")(static_cast <bool> ((LHSTy->isFixedPointType() || RHSTy
->isFixedPointType()) && "Expected at least one of the operands to be a fixed point type"
) ? 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-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1392, __extension__ __PRETTY_FUNCTION__))
;
1393 assert((LHSTy->isFixedPointOrIntegerType() ||(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType
() || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? 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-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1396, __extension__ __PRETTY_FUNCTION__))
1394 RHSTy->isFixedPointOrIntegerType()) &&(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType
() || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? 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-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1396, __extension__ __PRETTY_FUNCTION__))
1395 "Special fixed point arithmetic operation conversions are only "(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType
() || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? 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-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1396, __extension__ __PRETTY_FUNCTION__))
1396 "applied to ints or other fixed point types")(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType
() || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? 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-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1396, __extension__ __PRETTY_FUNCTION__))
;
1397
1398 // If one operand has signed fixed-point type and the other operand has
1399 // unsigned fixed-point type, then the unsigned fixed-point operand is
1400 // converted to its corresponding signed fixed-point type and the resulting
1401 // type is the type of the converted operand.
1402 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1403 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1404 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1405 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1406
1407 // The result type is the type with the highest rank, whereby a fixed-point
1408 // conversion rank is always greater than an integer conversion rank; if the
1409 // type of either of the operands is a saturating fixedpoint type, the result
1410 // type shall be the saturating fixed-point type corresponding to the type
1411 // with the highest rank; the resulting value is converted (taking into
1412 // account rounding and overflow) to the precision of the resulting type.
1413 // Same ranks between signed and unsigned types are resolved earlier, so both
1414 // types are either signed or both unsigned at this point.
1415 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1416 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1417
1418 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1419
1420 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1421 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1422
1423 return ResultTy;
1424}
1425
1426/// Check that the usual arithmetic conversions can be performed on this pair of
1427/// expressions that might be of enumeration type.
1428static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1429 SourceLocation Loc,
1430 Sema::ArithConvKind ACK) {
1431 // C++2a [expr.arith.conv]p1:
1432 // If one operand is of enumeration type and the other operand is of a
1433 // different enumeration type or a floating-point type, this behavior is
1434 // deprecated ([depr.arith.conv.enum]).
1435 //
1436 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1437 // Eventually we will presumably reject these cases (in C++23 onwards?).
1438 QualType L = LHS->getType(), R = RHS->getType();
1439 bool LEnum = L->isUnscopedEnumerationType(),
1440 REnum = R->isUnscopedEnumerationType();
1441 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1442 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1443 (REnum && L->isFloatingType())) {
1444 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1445 ? diag::warn_arith_conv_enum_float_cxx20
1446 : diag::warn_arith_conv_enum_float)
1447 << LHS->getSourceRange() << RHS->getSourceRange()
1448 << (int)ACK << LEnum << L << R;
1449 } else if (!IsCompAssign && LEnum && REnum &&
1450 !S.Context.hasSameUnqualifiedType(L, R)) {
1451 unsigned DiagID;
1452 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1453 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1454 // If either enumeration type is unnamed, it's less likely that the
1455 // user cares about this, but this situation is still deprecated in
1456 // C++2a. Use a different warning group.
1457 DiagID = S.getLangOpts().CPlusPlus20
1458 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1459 : diag::warn_arith_conv_mixed_anon_enum_types;
1460 } else if (ACK == Sema::ACK_Conditional) {
1461 // Conditional expressions are separated out because they have
1462 // historically had a different warning flag.
1463 DiagID = S.getLangOpts().CPlusPlus20
1464 ? diag::warn_conditional_mixed_enum_types_cxx20
1465 : diag::warn_conditional_mixed_enum_types;
1466 } else if (ACK == Sema::ACK_Comparison) {
1467 // Comparison expressions are separated out because they have
1468 // historically had a different warning flag.
1469 DiagID = S.getLangOpts().CPlusPlus20
1470 ? diag::warn_comparison_mixed_enum_types_cxx20
1471 : diag::warn_comparison_mixed_enum_types;
1472 } else {
1473 DiagID = S.getLangOpts().CPlusPlus20
1474 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1475 : diag::warn_arith_conv_mixed_enum_types;
1476 }
1477 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1478 << (int)ACK << L << R;
1479 }
1480}
1481
1482/// UsualArithmeticConversions - Performs various conversions that are common to
1483/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1484/// routine returns the first non-arithmetic type found. The client is
1485/// responsible for emitting appropriate error diagnostics.
1486QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1487 SourceLocation Loc,
1488 ArithConvKind ACK) {
1489 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1490
1491 if (ACK != ACK_CompAssign) {
1492 LHS = UsualUnaryConversions(LHS.get());
1493 if (LHS.isInvalid())
1494 return QualType();
1495 }
1496
1497 RHS = UsualUnaryConversions(RHS.get());
1498 if (RHS.isInvalid())
1499 return QualType();
1500
1501 // For conversion purposes, we ignore any qualifiers.
1502 // For example, "const float" and "float" are equivalent.
1503 QualType LHSType =
1504 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1505 QualType RHSType =
1506 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1507
1508 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1509 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1510 LHSType = AtomicLHS->getValueType();
1511
1512 // If both types are identical, no conversion is needed.
1513 if (LHSType == RHSType)
1514 return LHSType;
1515
1516 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1517 // The caller can deal with this (e.g. pointer + int).
1518 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1519 return QualType();
1520
1521 // Apply unary and bitfield promotions to the LHS's type.
1522 QualType LHSUnpromotedType = LHSType;
1523 if (LHSType->isPromotableIntegerType())
1524 LHSType = Context.getPromotedIntegerType(LHSType);
1525 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1526 if (!LHSBitfieldPromoteTy.isNull())
1527 LHSType = LHSBitfieldPromoteTy;
1528 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1529 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1530
1531 // If both types are identical, no conversion is needed.
1532 if (LHSType == RHSType)
1533 return LHSType;
1534
1535 // At this point, we have two different arithmetic types.
1536
1537 // Diagnose attempts to convert between __ibm128, __float128 and long double
1538 // where such conversions currently can't be handled.
1539 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1540 return QualType();
1541
1542 // Handle complex types first (C99 6.3.1.8p1).
1543 if (LHSType->isComplexType() || RHSType->isComplexType())
1544 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1545 ACK == ACK_CompAssign);
1546
1547 // Now handle "real" floating types (i.e. float, double, long double).
1548 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1549 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1550 ACK == ACK_CompAssign);
1551
1552 // Handle GCC complex int extension.
1553 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1554 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1555 ACK == ACK_CompAssign);
1556
1557 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1558 return handleFixedPointConversion(*this, LHSType, RHSType);
1559
1560 // Finally, we have two differing integer types.
1561 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1562 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1563}
1564
1565//===----------------------------------------------------------------------===//
1566// Semantic Analysis for various Expression Types
1567//===----------------------------------------------------------------------===//
1568
1569
1570ExprResult
1571Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1572 SourceLocation DefaultLoc,
1573 SourceLocation RParenLoc,
1574 Expr *ControllingExpr,
1575 ArrayRef<ParsedType> ArgTypes,
1576 ArrayRef<Expr *> ArgExprs) {
1577 unsigned NumAssocs = ArgTypes.size();
1578 assert(NumAssocs == ArgExprs.size())(static_cast <bool> (NumAssocs == ArgExprs.size()) ? void
(0) : __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1578, __extension__ __PRETTY_FUNCTION__))
;
1579
1580 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1581 for (unsigned i = 0; i < NumAssocs; ++i) {
1582 if (ArgTypes[i])
1583 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1584 else
1585 Types[i] = nullptr;
1586 }
1587
1588 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1589 ControllingExpr,
1590 llvm::makeArrayRef(Types, NumAssocs),
1591 ArgExprs);
1592 delete [] Types;
1593 return ER;
1594}
1595
1596ExprResult
1597Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1598 SourceLocation DefaultLoc,
1599 SourceLocation RParenLoc,
1600 Expr *ControllingExpr,
1601 ArrayRef<TypeSourceInfo *> Types,
1602 ArrayRef<Expr *> Exprs) {
1603 unsigned NumAssocs = Types.size();
1604 assert(NumAssocs == Exprs.size())(static_cast <bool> (NumAssocs == Exprs.size()) ? void (
0) : __assert_fail ("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1604, __extension__ __PRETTY_FUNCTION__))
;
1605
1606 // Decay and strip qualifiers for the controlling expression type, and handle
1607 // placeholder type replacement. See committee discussion from WG14 DR423.
1608 {
1609 EnterExpressionEvaluationContext Unevaluated(
1610 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1611 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1612 if (R.isInvalid())
1613 return ExprError();
1614 ControllingExpr = R.get();
1615 }
1616
1617 // The controlling expression is an unevaluated operand, so side effects are
1618 // likely unintended.
1619 if (!inTemplateInstantiation() &&
1620 ControllingExpr->HasSideEffects(Context, false))
1621 Diag(ControllingExpr->getExprLoc(),
1622 diag::warn_side_effects_unevaluated_context);
1623
1624 bool TypeErrorFound = false,
1625 IsResultDependent = ControllingExpr->isTypeDependent(),
1626 ContainsUnexpandedParameterPack
1627 = ControllingExpr->containsUnexpandedParameterPack();
1628
1629 for (unsigned i = 0; i < NumAssocs; ++i) {
1630 if (Exprs[i]->containsUnexpandedParameterPack())
1631 ContainsUnexpandedParameterPack = true;
1632
1633 if (Types[i]) {
1634 if (Types[i]->getType()->containsUnexpandedParameterPack())
1635 ContainsUnexpandedParameterPack = true;
1636
1637 if (Types[i]->getType()->isDependentType()) {
1638 IsResultDependent = true;
1639 } else {
1640 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1641 // complete object type other than a variably modified type."
1642 unsigned D = 0;
1643 if (Types[i]->getType()->isIncompleteType())
1644 D = diag::err_assoc_type_incomplete;
1645 else if (!Types[i]->getType()->isObjectType())
1646 D = diag::err_assoc_type_nonobject;
1647 else if (Types[i]->getType()->isVariablyModifiedType())
1648 D = diag::err_assoc_type_variably_modified;
1649
1650 if (D != 0) {
1651 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1652 << Types[i]->getTypeLoc().getSourceRange()
1653 << Types[i]->getType();
1654 TypeErrorFound = true;
1655 }
1656
1657 // C11 6.5.1.1p2 "No two generic associations in the same generic
1658 // selection shall specify compatible types."
1659 for (unsigned j = i+1; j < NumAssocs; ++j)
1660 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1661 Context.typesAreCompatible(Types[i]->getType(),
1662 Types[j]->getType())) {
1663 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1664 diag::err_assoc_compatible_types)
1665 << Types[j]->getTypeLoc().getSourceRange()
1666 << Types[j]->getType()
1667 << Types[i]->getType();
1668 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1669 diag::note_compat_assoc)
1670 << Types[i]->getTypeLoc().getSourceRange()
1671 << Types[i]->getType();
1672 TypeErrorFound = true;
1673 }
1674 }
1675 }
1676 }
1677 if (TypeErrorFound)
1678 return ExprError();
1679
1680 // If we determined that the generic selection is result-dependent, don't
1681 // try to compute the result expression.
1682 if (IsResultDependent)
1683 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1684 Exprs, DefaultLoc, RParenLoc,
1685 ContainsUnexpandedParameterPack);
1686
1687 SmallVector<unsigned, 1> CompatIndices;
1688 unsigned DefaultIndex = -1U;
1689 for (unsigned i = 0; i < NumAssocs; ++i) {
1690 if (!Types[i])
1691 DefaultIndex = i;
1692 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1693 Types[i]->getType()))
1694 CompatIndices.push_back(i);
1695 }
1696
1697 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1698 // type compatible with at most one of the types named in its generic
1699 // association list."
1700 if (CompatIndices.size() > 1) {
1701 // We strip parens here because the controlling expression is typically
1702 // parenthesized in macro definitions.
1703 ControllingExpr = ControllingExpr->IgnoreParens();
1704 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1705 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1706 << (unsigned)CompatIndices.size();
1707 for (unsigned I : CompatIndices) {
1708 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1709 diag::note_compat_assoc)
1710 << Types[I]->getTypeLoc().getSourceRange()
1711 << Types[I]->getType();
1712 }
1713 return ExprError();
1714 }
1715
1716 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1717 // its controlling expression shall have type compatible with exactly one of
1718 // the types named in its generic association list."
1719 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1720 // We strip parens here because the controlling expression is typically
1721 // parenthesized in macro definitions.
1722 ControllingExpr = ControllingExpr->IgnoreParens();
1723 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1724 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1725 return ExprError();
1726 }
1727
1728 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1729 // type name that is compatible with the type of the controlling expression,
1730 // then the result expression of the generic selection is the expression
1731 // in that generic association. Otherwise, the result expression of the
1732 // generic selection is the expression in the default generic association."
1733 unsigned ResultIndex =
1734 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1735
1736 return GenericSelectionExpr::Create(
1737 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1738 ContainsUnexpandedParameterPack, ResultIndex);
1739}
1740
1741/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1742/// location of the token and the offset of the ud-suffix within it.
1743static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1744 unsigned Offset) {
1745 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1746 S.getLangOpts());
1747}
1748
1749/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1750/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1751static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1752 IdentifierInfo *UDSuffix,
1753 SourceLocation UDSuffixLoc,
1754 ArrayRef<Expr*> Args,
1755 SourceLocation LitEndLoc) {
1756 assert(Args.size() <= 2 && "too many arguments for literal operator")(static_cast <bool> (Args.size() <= 2 && "too many arguments for literal operator"
) ? void (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1756, __extension__ __PRETTY_FUNCTION__))
;
1757
1758 QualType ArgTy[2];
1759 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1760 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1761 if (ArgTy[ArgIdx]->isArrayType())
1762 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1763 }
1764
1765 DeclarationName OpName =
1766 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1767 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1768 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1769
1770 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1771 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1772 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1773 /*AllowStringTemplatePack*/ false,
1774 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1775 return ExprError();
1776
1777 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1778}
1779
1780/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1781/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1782/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1783/// multiple tokens. However, the common case is that StringToks points to one
1784/// string.
1785///
1786ExprResult
1787Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1788 assert(!StringToks.empty() && "Must have at least one string!")(static_cast <bool> (!StringToks.empty() && "Must have at least one string!"
) ? void (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1788, __extension__ __PRETTY_FUNCTION__))
;
1789
1790 StringLiteralParser Literal(StringToks, PP);
1791 if (Literal.hadError)
1792 return ExprError();
1793
1794 SmallVector<SourceLocation, 4> StringTokLocs;
1795 for (const Token &Tok : StringToks)
1796 StringTokLocs.push_back(Tok.getLocation());
1797
1798 QualType CharTy = Context.CharTy;
1799 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1800 if (Literal.isWide()) {
1801 CharTy = Context.getWideCharType();
1802 Kind = StringLiteral::Wide;
1803 } else if (Literal.isUTF8()) {
1804 if (getLangOpts().Char8)
1805 CharTy = Context.Char8Ty;
1806 Kind = StringLiteral::UTF8;
1807 } else if (Literal.isUTF16()) {
1808 CharTy = Context.Char16Ty;
1809 Kind = StringLiteral::UTF16;
1810 } else if (Literal.isUTF32()) {
1811 CharTy = Context.Char32Ty;
1812 Kind = StringLiteral::UTF32;
1813 } else if (Literal.isPascal()) {
1814 CharTy = Context.UnsignedCharTy;
1815 }
1816
1817 // Warn on initializing an array of char from a u8 string literal; this
1818 // becomes ill-formed in C++2a.
1819 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1820 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1821 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1822
1823 // Create removals for all 'u8' prefixes in the string literal(s). This
1824 // ensures C++2a compatibility (but may change the program behavior when
1825 // built by non-Clang compilers for which the execution character set is
1826 // not always UTF-8).
1827 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1828 SourceLocation RemovalDiagLoc;
1829 for (const Token &Tok : StringToks) {
1830 if (Tok.getKind() == tok::utf8_string_literal) {
1831 if (RemovalDiagLoc.isInvalid())
1832 RemovalDiagLoc = Tok.getLocation();
1833 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1834 Tok.getLocation(),
1835 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1836 getSourceManager(), getLangOpts())));
1837 }
1838 }
1839 Diag(RemovalDiagLoc, RemovalDiag);
1840 }
1841
1842 QualType StrTy =
1843 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1844
1845 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1846 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1847 Kind, Literal.Pascal, StrTy,
1848 &StringTokLocs[0],
1849 StringTokLocs.size());
1850 if (Literal.getUDSuffix().empty())
1851 return Lit;
1852
1853 // We're building a user-defined literal.
1854 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1855 SourceLocation UDSuffixLoc =
1856 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1857 Literal.getUDSuffixOffset());
1858
1859 // Make sure we're allowed user-defined literals here.
1860 if (!UDLScope)
1861 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1862
1863 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1864 // operator "" X (str, len)
1865 QualType SizeType = Context.getSizeType();
1866
1867 DeclarationName OpName =
1868 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1869 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1870 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1871
1872 QualType ArgTy[] = {
1873 Context.getArrayDecayedType(StrTy), SizeType
1874 };
1875
1876 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1877 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1878 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1879 /*AllowStringTemplatePack*/ true,
1880 /*DiagnoseMissing*/ true, Lit)) {
1881
1882 case LOLR_Cooked: {
1883 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1884 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1885 StringTokLocs[0]);
1886 Expr *Args[] = { Lit, LenArg };
1887
1888 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1889 }
1890
1891 case LOLR_Template: {
1892 TemplateArgumentListInfo ExplicitArgs;
1893 TemplateArgument Arg(Lit);
1894 TemplateArgumentLocInfo ArgInfo(Lit);
1895 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1896 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1897 &ExplicitArgs);
1898 }
1899
1900 case LOLR_StringTemplatePack: {
1901 TemplateArgumentListInfo ExplicitArgs;
1902
1903 unsigned CharBits = Context.getIntWidth(CharTy);
1904 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1905 llvm::APSInt Value(CharBits, CharIsUnsigned);
1906
1907 TemplateArgument TypeArg(CharTy);
1908 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1909 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1910
1911 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1912 Value = Lit->getCodeUnit(I);
1913 TemplateArgument Arg(Context, Value, CharTy);
1914 TemplateArgumentLocInfo ArgInfo;
1915 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1916 }
1917 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1918 &ExplicitArgs);
1919 }
1920 case LOLR_Raw:
1921 case LOLR_ErrorNoDiagnostic:
1922 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1922)
;
1923 case LOLR_Error:
1924 return ExprError();
1925 }
1926 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1926)
;
1927}
1928
1929DeclRefExpr *
1930Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1931 SourceLocation Loc,
1932 const CXXScopeSpec *SS) {
1933 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1934 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1935}
1936
1937DeclRefExpr *
1938Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1939 const DeclarationNameInfo &NameInfo,
1940 const CXXScopeSpec *SS, NamedDecl *FoundD,
1941 SourceLocation TemplateKWLoc,
1942 const TemplateArgumentListInfo *TemplateArgs) {
1943 NestedNameSpecifierLoc NNS =
1944 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1945 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1946 TemplateArgs);
1947}
1948
1949// CUDA/HIP: Check whether a captured reference variable is referencing a
1950// host variable in a device or host device lambda.
1951static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1952 VarDecl *VD) {
1953 if (!S.getLangOpts().CUDA || !VD->hasInit())
1954 return false;
1955 assert(VD->getType()->isReferenceType())(static_cast <bool> (VD->getType()->isReferenceType
()) ? void (0) : __assert_fail ("VD->getType()->isReferenceType()"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 1955, __extension__ __PRETTY_FUNCTION__))
;
1956
1957 // Check whether the reference variable is referencing a host variable.
1958 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1959 if (!DRE)
1960 return false;
1961 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1962 if (!Referee || !Referee->hasGlobalStorage() ||
1963 Referee->hasAttr<CUDADeviceAttr>())
1964 return false;
1965
1966 // Check whether the current function is a device or host device lambda.
1967 // Check whether the reference variable is a capture by getDeclContext()
1968 // since refersToEnclosingVariableOrCapture() is not ready at this point.
1969 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
1970 if (MD && MD->getParent()->isLambda() &&
1971 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
1972 VD->getDeclContext() != MD)
1973 return true;
1974
1975 return false;
1976}
1977
1978NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1979 // A declaration named in an unevaluated operand never constitutes an odr-use.
1980 if (isUnevaluatedContext())
1981 return NOUR_Unevaluated;
1982
1983 // C++2a [basic.def.odr]p4:
1984 // A variable x whose name appears as a potentially-evaluated expression e
1985 // is odr-used by e unless [...] x is a reference that is usable in
1986 // constant expressions.
1987 // CUDA/HIP:
1988 // If a reference variable referencing a host variable is captured in a
1989 // device or host device lambda, the value of the referee must be copied
1990 // to the capture and the reference variable must be treated as odr-use
1991 // since the value of the referee is not known at compile time and must
1992 // be loaded from the captured.
1993 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1994 if (VD->getType()->isReferenceType() &&
1995 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1996 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
1997 VD->isUsableInConstantExpressions(Context))
1998 return NOUR_Constant;
1999 }
2000
2001 // All remaining non-variable cases constitute an odr-use. For variables, we
2002 // need to wait and see how the expression is used.
2003 return NOUR_None;
2004}
2005
2006/// BuildDeclRefExpr - Build an expression that references a
2007/// declaration that does not require a closure capture.
2008DeclRefExpr *
2009Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2010 const DeclarationNameInfo &NameInfo,
2011 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2012 SourceLocation TemplateKWLoc,
2013 const TemplateArgumentListInfo *TemplateArgs) {
2014 bool RefersToCapturedVariable =
2015 isa<VarDecl>(D) &&
2016 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2017
2018 DeclRefExpr *E = DeclRefExpr::Create(
2019 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2020 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2021 MarkDeclRefReferenced(E);
2022
2023 // C++ [except.spec]p17:
2024 // An exception-specification is considered to be needed when:
2025 // - in an expression, the function is the unique lookup result or
2026 // the selected member of a set of overloaded functions.
2027 //
2028 // We delay doing this until after we've built the function reference and
2029 // marked it as used so that:
2030 // a) if the function is defaulted, we get errors from defining it before /
2031 // instead of errors from computing its exception specification, and
2032 // b) if the function is a defaulted comparison, we can use the body we
2033 // build when defining it as input to the exception specification
2034 // computation rather than computing a new body.
2035 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2036 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2037 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2038 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2039 }
2040 }
2041
2042 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2043 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2044 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2045 getCurFunction()->recordUseOfWeak(E);
2046
2047 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2048 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2049 FD = IFD->getAnonField();
2050 if (FD) {
2051 UnusedPrivateFields.remove(FD);
2052 // Just in case we're building an illegal pointer-to-member.
2053 if (FD->isBitField())
2054 E->setObjectKind(OK_BitField);
2055 }
2056
2057 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2058 // designates a bit-field.
2059 if (auto *BD = dyn_cast<BindingDecl>(D))
2060 if (auto *BE = BD->getBinding())
2061 E->setObjectKind(BE->getObjectKind());
2062
2063 return E;
2064}
2065
2066/// Decomposes the given name into a DeclarationNameInfo, its location, and
2067/// possibly a list of template arguments.
2068///
2069/// If this produces template arguments, it is permitted to call
2070/// DecomposeTemplateName.
2071///
2072/// This actually loses a lot of source location information for
2073/// non-standard name kinds; we should consider preserving that in
2074/// some way.
2075void
2076Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2077 TemplateArgumentListInfo &Buffer,
2078 DeclarationNameInfo &NameInfo,
2079 const TemplateArgumentListInfo *&TemplateArgs) {
2080 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2081 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2082 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2083
2084 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2085 Id.TemplateId->NumArgs);
2086 translateTemplateArguments(TemplateArgsPtr, Buffer);
2087
2088 TemplateName TName = Id.TemplateId->Template.get();
2089 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2090 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2091 TemplateArgs = &Buffer;
2092 } else {
2093 NameInfo = GetNameFromUnqualifiedId(Id);
2094 TemplateArgs = nullptr;
2095 }
2096}
2097
2098static void emitEmptyLookupTypoDiagnostic(
2099 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2100 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2101 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2102 DeclContext *Ctx =
2103 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2104 if (!TC) {
2105 // Emit a special diagnostic for failed member lookups.
2106 // FIXME: computing the declaration context might fail here (?)
2107 if (Ctx)
2108 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2109 << SS.getRange();
2110 else
2111 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2112 return;
2113 }
2114
2115 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2116 bool DroppedSpecifier =
2117 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2118 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2119 ? diag::note_implicit_param_decl
2120 : diag::note_previous_decl;
2121 if (!Ctx)
2122 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2123 SemaRef.PDiag(NoteID));
2124 else
2125 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2126 << Typo << Ctx << DroppedSpecifier
2127 << SS.getRange(),
2128 SemaRef.PDiag(NoteID));
2129}
2130
2131/// Diagnose a lookup that found results in an enclosing class during error
2132/// recovery. This usually indicates that the results were found in a dependent
2133/// base class that could not be searched as part of a template definition.
2134/// Always issues a diagnostic (though this may be only a warning in MS
2135/// compatibility mode).
2136///
2137/// Return \c true if the error is unrecoverable, or \c false if the caller
2138/// should attempt to recover using these lookup results.
2139bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2140 // During a default argument instantiation the CurContext points
2141 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2142 // function parameter list, hence add an explicit check.
2143 bool isDefaultArgument =
2144 !CodeSynthesisContexts.empty() &&
2145 CodeSynthesisContexts.back().Kind ==
2146 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2147 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2148 bool isInstance = CurMethod && CurMethod->isInstance() &&
2149 R.getNamingClass() == CurMethod->getParent() &&
2150 !isDefaultArgument;
2151
2152 // There are two ways we can find a class-scope declaration during template
2153 // instantiation that we did not find in the template definition: if it is a
2154 // member of a dependent base class, or if it is declared after the point of
2155 // use in the same class. Distinguish these by comparing the class in which
2156 // the member was found to the naming class of the lookup.
2157 unsigned DiagID = diag::err_found_in_dependent_base;
2158 unsigned NoteID = diag::note_member_declared_at;
2159 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2160 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2161 : diag::err_found_later_in_class;
2162 } else if (getLangOpts().MSVCCompat) {
2163 DiagID = diag::ext_found_in_dependent_base;
2164 NoteID = diag::note_dependent_member_use;
2165 }
2166
2167 if (isInstance) {
2168 // Give a code modification hint to insert 'this->'.
2169 Diag(R.getNameLoc(), DiagID)
2170 << R.getLookupName()
2171 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2172 CheckCXXThisCapture(R.getNameLoc());
2173 } else {
2174 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2175 // they're not shadowed).
2176 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2177 }
2178
2179 for (NamedDecl *D : R)
2180 Diag(D->getLocation(), NoteID);
2181
2182 // Return true if we are inside a default argument instantiation
2183 // and the found name refers to an instance member function, otherwise
2184 // the caller will try to create an implicit member call and this is wrong
2185 // for default arguments.
2186 //
2187 // FIXME: Is this special case necessary? We could allow the caller to
2188 // diagnose this.
2189 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2190 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2191 return true;
2192 }
2193
2194 // Tell the callee to try to recover.
2195 return false;
2196}
2197
2198/// Diagnose an empty lookup.
2199///
2200/// \return false if new lookup candidates were found
2201bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2202 CorrectionCandidateCallback &CCC,
2203 TemplateArgumentListInfo *ExplicitTemplateArgs,
2204 ArrayRef<Expr *> Args, TypoExpr **Out) {
2205 DeclarationName Name = R.getLookupName();
2206
2207 unsigned diagnostic = diag::err_undeclared_var_use;
2208 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2209 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2210 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2211 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2212 diagnostic = diag::err_undeclared_use;
2213 diagnostic_suggest = diag::err_undeclared_use_suggest;
2214 }
2215
2216 // If the original lookup was an unqualified lookup, fake an
2217 // unqualified lookup. This is useful when (for example) the
2218 // original lookup would not have found something because it was a
2219 // dependent name.
2220 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2221 while (DC) {
2222 if (isa<CXXRecordDecl>(DC)) {
2223 LookupQualifiedName(R, DC);
2224
2225 if (!R.empty()) {
2226 // Don't give errors about ambiguities in this lookup.
2227 R.suppressDiagnostics();
2228
2229 // If there's a best viable function among the results, only mention
2230 // that one in the notes.
2231 OverloadCandidateSet Candidates(R.getNameLoc(),
2232 OverloadCandidateSet::CSK_Normal);
2233 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2234 OverloadCandidateSet::iterator Best;
2235 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2236 OR_Success) {
2237 R.clear();
2238 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2239 R.resolveKind();
2240 }
2241
2242 return DiagnoseDependentMemberLookup(R);
2243 }
2244
2245 R.clear();
2246 }
2247
2248 DC = DC->getLookupParent();
2249 }
2250
2251 // We didn't find anything, so try to correct for a typo.
2252 TypoCorrection Corrected;
2253 if (S && Out) {
2254 SourceLocation TypoLoc = R.getNameLoc();
2255 assert(!ExplicitTemplateArgs &&(static_cast <bool> (!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? void (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2256, __extension__ __PRETTY_FUNCTION__))
2256 "Diagnosing an empty lookup with explicit template args!")(static_cast <bool> (!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? void (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2256, __extension__ __PRETTY_FUNCTION__))
;
2257 *Out = CorrectTypoDelayed(
2258 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2259 [=](const TypoCorrection &TC) {
2260 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2261 diagnostic, diagnostic_suggest);
2262 },
2263 nullptr, CTK_ErrorRecovery);
2264 if (*Out)
2265 return true;
2266 } else if (S &&
2267 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2268 S, &SS, CCC, CTK_ErrorRecovery))) {
2269 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2270 bool DroppedSpecifier =
2271 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2272 R.setLookupName(Corrected.getCorrection());
2273
2274 bool AcceptableWithRecovery = false;
2275 bool AcceptableWithoutRecovery = false;
2276 NamedDecl *ND = Corrected.getFoundDecl();
2277 if (ND) {
2278 if (Corrected.isOverloaded()) {
2279 OverloadCandidateSet OCS(R.getNameLoc(),
2280 OverloadCandidateSet::CSK_Normal);
2281 OverloadCandidateSet::iterator Best;
2282 for (NamedDecl *CD : Corrected) {
2283 if (FunctionTemplateDecl *FTD =
2284 dyn_cast<FunctionTemplateDecl>(CD))
2285 AddTemplateOverloadCandidate(
2286 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2287 Args, OCS);
2288 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2289 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2290 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2291 Args, OCS);
2292 }
2293 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2294 case OR_Success:
2295 ND = Best->FoundDecl;
2296 Corrected.setCorrectionDecl(ND);
2297 break;
2298 default:
2299 // FIXME: Arbitrarily pick the first declaration for the note.
2300 Corrected.setCorrectionDecl(ND);
2301 break;
2302 }
2303 }
2304 R.addDecl(ND);
2305 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2306 CXXRecordDecl *Record = nullptr;
2307 if (Corrected.getCorrectionSpecifier()) {
2308 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2309 Record = Ty->getAsCXXRecordDecl();
2310 }
2311 if (!Record)
2312 Record = cast<CXXRecordDecl>(
2313 ND->getDeclContext()->getRedeclContext());
2314 R.setNamingClass(Record);
2315 }
2316
2317 auto *UnderlyingND = ND->getUnderlyingDecl();
2318 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2319 isa<FunctionTemplateDecl>(UnderlyingND);
2320 // FIXME: If we ended up with a typo for a type name or
2321 // Objective-C class name, we're in trouble because the parser
2322 // is in the wrong place to recover. Suggest the typo
2323 // correction, but don't make it a fix-it since we're not going
2324 // to recover well anyway.
2325 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2326 getAsTypeTemplateDecl(UnderlyingND) ||
2327 isa<ObjCInterfaceDecl>(UnderlyingND);
2328 } else {
2329 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2330 // because we aren't able to recover.
2331 AcceptableWithoutRecovery = true;
2332 }
2333
2334 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2335 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2336 ? diag::note_implicit_param_decl
2337 : diag::note_previous_decl;
2338 if (SS.isEmpty())
2339 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2340 PDiag(NoteID), AcceptableWithRecovery);
2341 else
2342 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2343 << Name << computeDeclContext(SS, false)
2344 << DroppedSpecifier << SS.getRange(),
2345 PDiag(NoteID), AcceptableWithRecovery);
2346
2347 // Tell the callee whether to try to recover.
2348 return !AcceptableWithRecovery;
2349 }
2350 }
2351 R.clear();
2352
2353 // Emit a special diagnostic for failed member lookups.
2354 // FIXME: computing the declaration context might fail here (?)
2355 if (!SS.isEmpty()) {
2356 Diag(R.getNameLoc(), diag::err_no_member)
2357 << Name << computeDeclContext(SS, false)
2358 << SS.getRange();
2359 return true;
2360 }
2361
2362 // Give up, we can't recover.
2363 Diag(R.getNameLoc(), diagnostic) << Name;
2364 return true;
2365}
2366
2367/// In Microsoft mode, if we are inside a template class whose parent class has
2368/// dependent base classes, and we can't resolve an unqualified identifier, then
2369/// assume the identifier is a member of a dependent base class. We can only
2370/// recover successfully in static methods, instance methods, and other contexts
2371/// where 'this' is available. This doesn't precisely match MSVC's
2372/// instantiation model, but it's close enough.
2373static Expr *
2374recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2375 DeclarationNameInfo &NameInfo,
2376 SourceLocation TemplateKWLoc,
2377 const TemplateArgumentListInfo *TemplateArgs) {
2378 // Only try to recover from lookup into dependent bases in static methods or
2379 // contexts where 'this' is available.
2380 QualType ThisType = S.getCurrentThisType();
2381 const CXXRecordDecl *RD = nullptr;
2382 if (!ThisType.isNull())
2383 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2384 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2385 RD = MD->getParent();
2386 if (!RD || !RD->hasAnyDependentBases())
2387 return nullptr;
2388
2389 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2390 // is available, suggest inserting 'this->' as a fixit.
2391 SourceLocation Loc = NameInfo.getLoc();
2392 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2393 DB << NameInfo.getName() << RD;
2394
2395 if (!ThisType.isNull()) {
2396 DB << FixItHint::CreateInsertion(Loc, "this->");
2397 return CXXDependentScopeMemberExpr::Create(
2398 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2399 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2400 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2401 }
2402
2403 // Synthesize a fake NNS that points to the derived class. This will
2404 // perform name lookup during template instantiation.
2405 CXXScopeSpec SS;
2406 auto *NNS =
2407 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2408 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2409 return DependentScopeDeclRefExpr::Create(
2410 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2411 TemplateArgs);
2412}
2413
2414ExprResult
2415Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2416 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2417 bool HasTrailingLParen, bool IsAddressOfOperand,
2418 CorrectionCandidateCallback *CCC,
2419 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2420 assert(!(IsAddressOfOperand && HasTrailingLParen) &&(static_cast <bool> (!(IsAddressOfOperand && HasTrailingLParen
) && "cannot be direct & operand and have a trailing lparen"
) ? void (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2421, __extension__ __PRETTY_FUNCTION__))
2421 "cannot be direct & operand and have a trailing lparen")(static_cast <bool> (!(IsAddressOfOperand && HasTrailingLParen
) && "cannot be direct & operand and have a trailing lparen"
) ? void (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2421, __extension__ __PRETTY_FUNCTION__))
;
2422 if (SS.isInvalid())
2423 return ExprError();
2424
2425 TemplateArgumentListInfo TemplateArgsBuffer;
2426
2427 // Decompose the UnqualifiedId into the following data.
2428 DeclarationNameInfo NameInfo;
2429 const TemplateArgumentListInfo *TemplateArgs;
2430 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2431
2432 DeclarationName Name = NameInfo.getName();
2433 IdentifierInfo *II = Name.getAsIdentifierInfo();
2434 SourceLocation NameLoc = NameInfo.getLoc();
2435
2436 if (II && II->isEditorPlaceholder()) {
2437 // FIXME: When typed placeholders are supported we can create a typed
2438 // placeholder expression node.
2439 return ExprError();
2440 }
2441
2442 // C++ [temp.dep.expr]p3:
2443 // An id-expression is type-dependent if it contains:
2444 // -- an identifier that was declared with a dependent type,
2445 // (note: handled after lookup)
2446 // -- a template-id that is dependent,
2447 // (note: handled in BuildTemplateIdExpr)
2448 // -- a conversion-function-id that specifies a dependent type,
2449 // -- a nested-name-specifier that contains a class-name that
2450 // names a dependent type.
2451 // Determine whether this is a member of an unknown specialization;
2452 // we need to handle these differently.
2453 bool DependentID = false;
2454 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2455 Name.getCXXNameType()->isDependentType()) {
2456 DependentID = true;
2457 } else if (SS.isSet()) {
2458 if (DeclContext *DC = computeDeclContext(SS, false)) {
2459 if (RequireCompleteDeclContext(SS, DC))
2460 return ExprError();
2461 } else {
2462 DependentID = true;
2463 }
2464 }
2465
2466 if (DependentID)
2467 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2468 IsAddressOfOperand, TemplateArgs);
2469
2470 // Perform the required lookup.
2471 LookupResult R(*this, NameInfo,
2472 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2473 ? LookupObjCImplicitSelfParam
2474 : LookupOrdinaryName);
2475 if (TemplateKWLoc.isValid() || TemplateArgs) {
2476 // Lookup the template name again to correctly establish the context in
2477 // which it was found. This is really unfortunate as we already did the
2478 // lookup to determine that it was a template name in the first place. If
2479 // this becomes a performance hit, we can work harder to preserve those
2480 // results until we get here but it's likely not worth it.
2481 bool MemberOfUnknownSpecialization;
2482 AssumedTemplateKind AssumedTemplate;
2483 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2484 MemberOfUnknownSpecialization, TemplateKWLoc,
2485 &AssumedTemplate))
2486 return ExprError();
2487
2488 if (MemberOfUnknownSpecialization ||
2489 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2490 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2491 IsAddressOfOperand, TemplateArgs);
2492 } else {
2493 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2494 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2495
2496 // If the result might be in a dependent base class, this is a dependent
2497 // id-expression.
2498 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2499 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2500 IsAddressOfOperand, TemplateArgs);
2501
2502 // If this reference is in an Objective-C method, then we need to do
2503 // some special Objective-C lookup, too.
2504 if (IvarLookupFollowUp) {
2505 ExprResult E(LookupInObjCMethod(R, S, II, true));
2506 if (E.isInvalid())
2507 return ExprError();
2508
2509 if (Expr *Ex = E.getAs<Expr>())
2510 return Ex;
2511 }
2512 }
2513
2514 if (R.isAmbiguous())
2515 return ExprError();
2516
2517 // This could be an implicitly declared function reference (legal in C90,
2518 // extension in C99, forbidden in C++).
2519 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2520 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2521 if (D) R.addDecl(D);
2522 }
2523
2524 // Determine whether this name might be a candidate for
2525 // argument-dependent lookup.
2526 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2527
2528 if (R.empty() && !ADL) {
2529 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2530 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2531 TemplateKWLoc, TemplateArgs))
2532 return E;
2533 }
2534
2535 // Don't diagnose an empty lookup for inline assembly.
2536 if (IsInlineAsmIdentifier)
2537 return ExprError();
2538
2539 // If this name wasn't predeclared and if this is not a function
2540 // call, diagnose the problem.
2541 TypoExpr *TE = nullptr;
2542 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2543 : nullptr);
2544 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2545 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(static_cast <bool> ((!CCC || CCC->IsAddressOfOperand
== IsAddressOfOperand) && "Typo correction callback misconfigured"
) ? void (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2546, __extension__ __PRETTY_FUNCTION__))
2546 "Typo correction callback misconfigured")(static_cast <bool> ((!CCC || CCC->IsAddressOfOperand
== IsAddressOfOperand) && "Typo correction callback misconfigured"
) ? void (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2546, __extension__ __PRETTY_FUNCTION__))
;
2547 if (CCC) {
2548 // Make sure the callback knows what the typo being diagnosed is.
2549 CCC->setTypoName(II);
2550 if (SS.isValid())
2551 CCC->setTypoNNS(SS.getScopeRep());
2552 }
2553 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2554 // a template name, but we happen to have always already looked up the name
2555 // before we get here if it must be a template name.
2556 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2557 None, &TE)) {
2558 if (TE && KeywordReplacement) {
2559 auto &State = getTypoExprState(TE);
2560 auto BestTC = State.Consumer->getNextCorrection();
2561 if (BestTC.isKeyword()) {
2562 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2563 if (State.DiagHandler)
2564 State.DiagHandler(BestTC);
2565 KeywordReplacement->startToken();
2566 KeywordReplacement->setKind(II->getTokenID());
2567 KeywordReplacement->setIdentifierInfo(II);
2568 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2569 // Clean up the state associated with the TypoExpr, since it has
2570 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2571 clearDelayedTypo(TE);
2572 // Signal that a correction to a keyword was performed by returning a
2573 // valid-but-null ExprResult.
2574 return (Expr*)nullptr;
2575 }
2576 State.Consumer->resetCorrectionStream();
2577 }
2578 return TE ? TE : ExprError();
2579 }
2580
2581 assert(!R.empty() &&(static_cast <bool> (!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? void (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2582, __extension__ __PRETTY_FUNCTION__))
2582 "DiagnoseEmptyLookup returned false but added no results")(static_cast <bool> (!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? void (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2582, __extension__ __PRETTY_FUNCTION__))
;
2583
2584 // If we found an Objective-C instance variable, let
2585 // LookupInObjCMethod build the appropriate expression to
2586 // reference the ivar.
2587 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2588 R.clear();
2589 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2590 // In a hopelessly buggy code, Objective-C instance variable
2591 // lookup fails and no expression will be built to reference it.
2592 if (!E.isInvalid() && !E.get())
2593 return ExprError();
2594 return E;
2595 }
2596 }
2597
2598 // This is guaranteed from this point on.
2599 assert(!R.empty() || ADL)(static_cast <bool> (!R.empty() || ADL) ? void (0) : __assert_fail
("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2599, __extension__ __PRETTY_FUNCTION__))
;
2600
2601 // Check whether this might be a C++ implicit instance member access.
2602 // C++ [class.mfct.non-static]p3:
2603 // When an id-expression that is not part of a class member access
2604 // syntax and not used to form a pointer to member is used in the
2605 // body of a non-static member function of class X, if name lookup
2606 // resolves the name in the id-expression to a non-static non-type
2607 // member of some class C, the id-expression is transformed into a
2608 // class member access expression using (*this) as the
2609 // postfix-expression to the left of the . operator.
2610 //
2611 // But we don't actually need to do this for '&' operands if R
2612 // resolved to a function or overloaded function set, because the
2613 // expression is ill-formed if it actually works out to be a
2614 // non-static member function:
2615 //
2616 // C++ [expr.ref]p4:
2617 // Otherwise, if E1.E2 refers to a non-static member function. . .
2618 // [t]he expression can be used only as the left-hand operand of a
2619 // member function call.
2620 //
2621 // There are other safeguards against such uses, but it's important
2622 // to get this right here so that we don't end up making a
2623 // spuriously dependent expression if we're inside a dependent
2624 // instance method.
2625 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2626 bool MightBeImplicitMember;
2627 if (!IsAddressOfOperand)
2628 MightBeImplicitMember = true;
2629 else if (!SS.isEmpty())
2630 MightBeImplicitMember = false;
2631 else if (R.isOverloadedResult())
2632 MightBeImplicitMember = false;
2633 else if (R.isUnresolvableResult())
2634 MightBeImplicitMember = true;
2635 else
2636 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2637 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2638 isa<MSPropertyDecl>(R.getFoundDecl());
2639
2640 if (MightBeImplicitMember)
2641 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2642 R, TemplateArgs, S);
2643 }
2644
2645 if (TemplateArgs || TemplateKWLoc.isValid()) {
2646
2647 // In C++1y, if this is a variable template id, then check it
2648 // in BuildTemplateIdExpr().
2649 // The single lookup result must be a variable template declaration.
2650 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2651 Id.TemplateId->Kind == TNK_Var_template) {
2652 assert(R.getAsSingle<VarTemplateDecl>() &&(static_cast <bool> (R.getAsSingle<VarTemplateDecl>
() && "There should only be one declaration found.") ?
void (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2653, __extension__ __PRETTY_FUNCTION__))
2653 "There should only be one declaration found.")(static_cast <bool> (R.getAsSingle<VarTemplateDecl>
() && "There should only be one declaration found.") ?
void (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2653, __extension__ __PRETTY_FUNCTION__))
;
2654 }
2655
2656 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2657 }
2658
2659 return BuildDeclarationNameExpr(SS, R, ADL);
2660}
2661
2662/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2663/// declaration name, generally during template instantiation.
2664/// There's a large number of things which don't need to be done along
2665/// this path.
2666ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2667 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2668 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2669 DeclContext *DC = computeDeclContext(SS, false);
2670 if (!DC)
2671 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2672 NameInfo, /*TemplateArgs=*/nullptr);
2673
2674 if (RequireCompleteDeclContext(SS, DC))
2675 return ExprError();
2676
2677 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2678 LookupQualifiedName(R, DC);
2679
2680 if (R.isAmbiguous())
2681 return ExprError();
2682
2683 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2684 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2685 NameInfo, /*TemplateArgs=*/nullptr);
2686
2687 if (R.empty()) {
2688 // Don't diagnose problems with invalid record decl, the secondary no_member
2689 // diagnostic during template instantiation is likely bogus, e.g. if a class
2690 // is invalid because it's derived from an invalid base class, then missing
2691 // members were likely supposed to be inherited.
2692 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2693 if (CD->isInvalidDecl())
2694 return ExprError();
2695 Diag(NameInfo.getLoc(), diag::err_no_member)
2696 << NameInfo.getName() << DC << SS.getRange();
2697 return ExprError();
2698 }
2699
2700 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2701 // Diagnose a missing typename if this resolved unambiguously to a type in
2702 // a dependent context. If we can recover with a type, downgrade this to
2703 // a warning in Microsoft compatibility mode.
2704 unsigned DiagID = diag::err_typename_missing;
2705 if (RecoveryTSI && getLangOpts().MSVCCompat)
2706 DiagID = diag::ext_typename_missing;
2707 SourceLocation Loc = SS.getBeginLoc();
2708 auto D = Diag(Loc, DiagID);
2709 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2710 << SourceRange(Loc, NameInfo.getEndLoc());
2711
2712 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2713 // context.
2714 if (!RecoveryTSI)
2715 return ExprError();
2716
2717 // Only issue the fixit if we're prepared to recover.
2718 D << FixItHint::CreateInsertion(Loc, "typename ");
2719
2720 // Recover by pretending this was an elaborated type.
2721 QualType Ty = Context.getTypeDeclType(TD);
2722 TypeLocBuilder TLB;
2723 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2724
2725 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2726 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2727 QTL.setElaboratedKeywordLoc(SourceLocation());
2728 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2729
2730 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2731
2732 return ExprEmpty();
2733 }
2734
2735 // Defend against this resolving to an implicit member access. We usually
2736 // won't get here if this might be a legitimate a class member (we end up in
2737 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2738 // a pointer-to-member or in an unevaluated context in C++11.
2739 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2740 return BuildPossibleImplicitMemberExpr(SS,
2741 /*TemplateKWLoc=*/SourceLocation(),
2742 R, /*TemplateArgs=*/nullptr, S);
2743
2744 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2745}
2746
2747/// The parser has read a name in, and Sema has detected that we're currently
2748/// inside an ObjC method. Perform some additional checks and determine if we
2749/// should form a reference to an ivar.
2750///
2751/// Ideally, most of this would be done by lookup, but there's
2752/// actually quite a lot of extra work involved.
2753DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2754 IdentifierInfo *II) {
2755 SourceLocation Loc = Lookup.getNameLoc();
2756 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2757
2758 // Check for error condition which is already reported.
2759 if (!CurMethod)
2760 return DeclResult(true);
2761
2762 // There are two cases to handle here. 1) scoped lookup could have failed,
2763 // in which case we should look for an ivar. 2) scoped lookup could have
2764 // found a decl, but that decl is outside the current instance method (i.e.
2765 // a global variable). In these two cases, we do a lookup for an ivar with
2766 // this name, if the lookup sucedes, we replace it our current decl.
2767
2768 // If we're in a class method, we don't normally want to look for
2769 // ivars. But if we don't find anything else, and there's an
2770 // ivar, that's an error.
2771 bool IsClassMethod = CurMethod->isClassMethod();
2772
2773 bool LookForIvars;
2774 if (Lookup.empty())
2775 LookForIvars = true;
2776 else if (IsClassMethod)
2777 LookForIvars = false;
2778 else
2779 LookForIvars = (Lookup.isSingleResult() &&
2780 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2781 ObjCInterfaceDecl *IFace = nullptr;
2782 if (LookForIvars) {
2783 IFace = CurMethod->getClassInterface();
2784 ObjCInterfaceDecl *ClassDeclared;
2785 ObjCIvarDecl *IV = nullptr;
2786 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2787 // Diagnose using an ivar in a class method.
2788 if (IsClassMethod) {
2789 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2790 return DeclResult(true);
2791 }
2792
2793 // Diagnose the use of an ivar outside of the declaring class.
2794 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2795 !declaresSameEntity(ClassDeclared, IFace) &&
2796 !getLangOpts().DebuggerSupport)
2797 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2798
2799 // Success.
2800 return IV;
2801 }
2802 } else if (CurMethod->isInstanceMethod()) {
2803 // We should warn if a local variable hides an ivar.
2804 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2805 ObjCInterfaceDecl *ClassDeclared;
2806 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2807 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2808 declaresSameEntity(IFace, ClassDeclared))
2809 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2810 }
2811 }
2812 } else if (Lookup.isSingleResult() &&
2813 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2814 // If accessing a stand-alone ivar in a class method, this is an error.
2815 if (const ObjCIvarDecl *IV =
2816 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2817 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2818 return DeclResult(true);
2819 }
2820 }
2821
2822 // Didn't encounter an error, didn't find an ivar.
2823 return DeclResult(false);
2824}
2825
2826ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2827 ObjCIvarDecl *IV) {
2828 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2829 assert(CurMethod && CurMethod->isInstanceMethod() &&(static_cast <bool> (CurMethod && CurMethod->
isInstanceMethod() && "should not reference ivar from this context"
) ? void (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2830, __extension__ __PRETTY_FUNCTION__))
2830 "should not reference ivar from this context")(static_cast <bool> (CurMethod && CurMethod->
isInstanceMethod() && "should not reference ivar from this context"
) ? void (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2830, __extension__ __PRETTY_FUNCTION__))
;
2831
2832 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2833 assert(IFace && "should not reference ivar from this context")(static_cast <bool> (IFace && "should not reference ivar from this context"
) ? void (0) : __assert_fail ("IFace && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 2833, __extension__ __PRETTY_FUNCTION__))
;
2834
2835 // If we're referencing an invalid decl, just return this as a silent
2836 // error node. The error diagnostic was already emitted on the decl.
2837 if (IV->isInvalidDecl())
2838 return ExprError();
2839
2840 // Check if referencing a field with __attribute__((deprecated)).
2841 if (DiagnoseUseOfDecl(IV, Loc))
2842 return ExprError();
2843
2844 // FIXME: This should use a new expr for a direct reference, don't
2845 // turn this into Self->ivar, just return a BareIVarExpr or something.
2846 IdentifierInfo &II = Context.Idents.get("self");
2847 UnqualifiedId SelfName;
2848 SelfName.setImplicitSelfParam(&II);
2849 CXXScopeSpec SelfScopeSpec;
2850 SourceLocation TemplateKWLoc;
2851 ExprResult SelfExpr =
2852 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2853 /*HasTrailingLParen=*/false,
2854 /*IsAddressOfOperand=*/false);
2855 if (SelfExpr.isInvalid())
2856 return ExprError();
2857
2858 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2859 if (SelfExpr.isInvalid())
2860 return ExprError();
2861
2862 MarkAnyDeclReferenced(Loc, IV, true);
2863
2864 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2865 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2866 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2867 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2868
2869 ObjCIvarRefExpr *Result = new (Context)
2870 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2871 IV->getLocation(), SelfExpr.get(), true, true);
2872
2873 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2874 if (!isUnevaluatedContext() &&
2875 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2876 getCurFunction()->recordUseOfWeak(Result);
2877 }
2878 if (getLangOpts().ObjCAutoRefCount)
2879 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2880 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2881
2882 return Result;
2883}
2884
2885/// The parser has read a name in, and Sema has detected that we're currently
2886/// inside an ObjC method. Perform some additional checks and determine if we
2887/// should form a reference to an ivar. If so, build an expression referencing
2888/// that ivar.
2889ExprResult
2890Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2891 IdentifierInfo *II, bool AllowBuiltinCreation) {
2892 // FIXME: Integrate this lookup step into LookupParsedName.
2893 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2894 if (Ivar.isInvalid())
2895 return ExprError();
2896 if (Ivar.isUsable())
2897 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2898 cast<ObjCIvarDecl>(Ivar.get()));
2899
2900 if (Lookup.empty() && II && AllowBuiltinCreation)
2901 LookupBuiltin(Lookup);
2902
2903 // Sentinel value saying that we didn't do anything special.
2904 return ExprResult(false);
2905}
2906
2907/// Cast a base object to a member's actual type.
2908///
2909/// There are two relevant checks:
2910///
2911/// C++ [class.access.base]p7:
2912///
2913/// If a class member access operator [...] is used to access a non-static
2914/// data member or non-static member function, the reference is ill-formed if
2915/// the left operand [...] cannot be implicitly converted to a pointer to the
2916/// naming class of the right operand.
2917///
2918/// C++ [expr.ref]p7:
2919///
2920/// If E2 is a non-static data member or a non-static member function, the
2921/// program is ill-formed if the class of which E2 is directly a member is an
2922/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
2923///
2924/// Note that the latter check does not consider access; the access of the
2925/// "real" base class is checked as appropriate when checking the access of the
2926/// member name.
2927ExprResult
2928Sema::PerformObjectMemberConversion(Expr *From,
2929 NestedNameSpecifier *Qualifier,
2930 NamedDecl *FoundDecl,
2931 NamedDecl *Member) {
2932 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2933 if (!RD)
2934 return From;
2935
2936 QualType DestRecordType;
2937 QualType DestType;
2938 QualType FromRecordType;
2939 QualType FromType = From->getType();
2940 bool PointerConversions = false;
2941 if (isa<FieldDecl>(Member)) {
2942 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2943 auto FromPtrType = FromType->getAs<PointerType>();
2944 DestRecordType = Context.getAddrSpaceQualType(
2945 DestRecordType, FromPtrType
2946 ? FromType->getPointeeType().getAddressSpace()
2947 : FromType.getAddressSpace());
2948
2949 if (FromPtrType) {
2950 DestType = Context.getPointerType(DestRecordType);
2951 FromRecordType = FromPtrType->getPointeeType();
2952 PointerConversions = true;
2953 } else {
2954 DestType = DestRecordType;
2955 FromRecordType = FromType;
2956 }
2957 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2958 if (Method->isStatic())
2959 return From;
2960
2961 DestType = Method->getThisType();
2962 DestRecordType = DestType->getPointeeType();
2963
2964 if (FromType->getAs<PointerType>()) {
2965 FromRecordType = FromType->getPointeeType();
2966 PointerConversions = true;
2967 } else {
2968 FromRecordType = FromType;
2969 DestType = DestRecordType;
2970 }
2971
2972 LangAS FromAS = FromRecordType.getAddressSpace();
2973 LangAS DestAS = DestRecordType.getAddressSpace();
2974 if (FromAS != DestAS) {
2975 QualType FromRecordTypeWithoutAS =
2976 Context.removeAddrSpaceQualType(FromRecordType);
2977 QualType FromTypeWithDestAS =
2978 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2979 if (PointerConversions)
2980 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2981 From = ImpCastExprToType(From, FromTypeWithDestAS,
2982 CK_AddressSpaceConversion, From->getValueKind())
2983 .get();
2984 }
2985 } else {
2986 // No conversion necessary.
2987 return From;
2988 }
2989
2990 if (DestType->isDependentType() || FromType->isDependentType())
2991 return From;
2992
2993 // If the unqualified types are the same, no conversion is necessary.
2994 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2995 return From;
2996
2997 SourceRange FromRange = From->getSourceRange();
2998 SourceLocation FromLoc = FromRange.getBegin();
2999
3000 ExprValueKind VK = From->getValueKind();
3001
3002 // C++ [class.member.lookup]p8:
3003 // [...] Ambiguities can often be resolved by qualifying a name with its
3004 // class name.
3005 //
3006 // If the member was a qualified name and the qualified referred to a
3007 // specific base subobject type, we'll cast to that intermediate type
3008 // first and then to the object in which the member is declared. That allows
3009 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3010 //
3011 // class Base { public: int x; };
3012 // class Derived1 : public Base { };
3013 // class Derived2 : public Base { };
3014 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3015 //
3016 // void VeryDerived::f() {
3017 // x = 17; // error: ambiguous base subobjects
3018 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3019 // }
3020 if (Qualifier && Qualifier->getAsType()) {
3021 QualType QType = QualType(Qualifier->getAsType(), 0);
3022 assert(QType->isRecordType() && "lookup done with non-record type")(static_cast <bool> (QType->isRecordType() &&
"lookup done with non-record type") ? void (0) : __assert_fail
("QType->isRecordType() && \"lookup done with non-record type\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3022, __extension__ __PRETTY_FUNCTION__))
;
3023
3024 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
3025
3026 // In C++98, the qualifier type doesn't actually have to be a base
3027 // type of the object type, in which case we just ignore it.
3028 // Otherwise build the appropriate casts.
3029 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3030 CXXCastPath BasePath;
3031 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3032 FromLoc, FromRange, &BasePath))
3033 return ExprError();
3034
3035 if (PointerConversions)
3036 QType = Context.getPointerType(QType);
3037 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3038 VK, &BasePath).get();
3039
3040 FromType = QType;
3041 FromRecordType = QRecordType;
3042
3043 // If the qualifier type was the same as the destination type,
3044 // we're done.
3045 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3046 return From;
3047 }
3048 }
3049
3050 CXXCastPath BasePath;
3051 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3052 FromLoc, FromRange, &BasePath,
3053 /*IgnoreAccess=*/true))
3054 return ExprError();
3055
3056 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3057 VK, &BasePath);
3058}
3059
3060bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3061 const LookupResult &R,
3062 bool HasTrailingLParen) {
3063 // Only when used directly as the postfix-expression of a call.
3064 if (!HasTrailingLParen)
3065 return false;
3066
3067 // Never if a scope specifier was provided.
3068 if (SS.isSet())
3069 return false;
3070
3071 // Only in C++ or ObjC++.
3072 if (!getLangOpts().CPlusPlus)
3073 return false;
3074
3075 // Turn off ADL when we find certain kinds of declarations during
3076 // normal lookup:
3077 for (NamedDecl *D : R) {
3078 // C++0x [basic.lookup.argdep]p3:
3079 // -- a declaration of a class member
3080 // Since using decls preserve this property, we check this on the
3081 // original decl.
3082 if (D->isCXXClassMember())
3083 return false;
3084
3085 // C++0x [basic.lookup.argdep]p3:
3086 // -- a block-scope function declaration that is not a
3087 // using-declaration
3088 // NOTE: we also trigger this for function templates (in fact, we
3089 // don't check the decl type at all, since all other decl types
3090 // turn off ADL anyway).
3091 if (isa<UsingShadowDecl>(D))
3092 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3093 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3094 return false;
3095
3096 // C++0x [basic.lookup.argdep]p3:
3097 // -- a declaration that is neither a function or a function
3098 // template
3099 // And also for builtin functions.
3100 if (isa<FunctionDecl>(D)) {
3101 FunctionDecl *FDecl = cast<FunctionDecl>(D);
3102
3103 // But also builtin functions.
3104 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3105 return false;
3106 } else if (!isa<FunctionTemplateDecl>(D))
3107 return false;
3108 }
3109
3110 return true;
3111}
3112
3113
3114/// Diagnoses obvious problems with the use of the given declaration
3115/// as an expression. This is only actually called for lookups that
3116/// were not overloaded, and it doesn't promise that the declaration
3117/// will in fact be used.
3118static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3119 if (D->isInvalidDecl())
3120 return true;
3121
3122 if (isa<TypedefNameDecl>(D)) {
3123 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3124 return true;
3125 }
3126
3127 if (isa<ObjCInterfaceDecl>(D)) {
3128 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3129 return true;
3130 }
3131
3132 if (isa<NamespaceDecl>(D)) {
3133 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3134 return true;
3135 }
3136
3137 return false;
3138}
3139
3140// Certain multiversion types should be treated as overloaded even when there is
3141// only one result.
3142static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3143 assert(R.isSingleResult() && "Expected only a single result")(static_cast <bool> (R.isSingleResult() && "Expected only a single result"
) ? void (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3143, __extension__ __PRETTY_FUNCTION__))
;
3144 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3145 return FD &&
3146 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3147}
3148
3149ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3150 LookupResult &R, bool NeedsADL,
3151 bool AcceptInvalidDecl) {
3152 // If this is a single, fully-resolved result and we don't need ADL,
3153 // just build an ordinary singleton decl ref.
3154 if (!NeedsADL && R.isSingleResult() &&
3155 !R.getAsSingle<FunctionTemplateDecl>() &&
3156 !ShouldLookupResultBeMultiVersionOverload(R))
3157 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3158 R.getRepresentativeDecl(), nullptr,
3159 AcceptInvalidDecl);
3160
3161 // We only need to check the declaration if there's exactly one
3162 // result, because in the overloaded case the results can only be
3163 // functions and function templates.
3164 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3165 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3166 return ExprError();
3167
3168 // Otherwise, just build an unresolved lookup expression. Suppress
3169 // any lookup-related diagnostics; we'll hash these out later, when
3170 // we've picked a target.
3171 R.suppressDiagnostics();
3172
3173 UnresolvedLookupExpr *ULE
3174 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3175 SS.getWithLocInContext(Context),
3176 R.getLookupNameInfo(),
3177 NeedsADL, R.isOverloadedResult(),
3178 R.begin(), R.end());
3179
3180 return ULE;
3181}
3182
3183static void
3184diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3185 ValueDecl *var, DeclContext *DC);
3186
3187/// Complete semantic analysis for a reference to the given declaration.
3188ExprResult Sema::BuildDeclarationNameExpr(
3189 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3190 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3191 bool AcceptInvalidDecl) {
3192 assert(D && "Cannot refer to a NULL declaration")(static_cast <bool> (D && "Cannot refer to a NULL declaration"
) ? void (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3192, __extension__ __PRETTY_FUNCTION__))
;
3193 assert(!isa<FunctionTemplateDecl>(D) &&(static_cast <bool> (!isa<FunctionTemplateDecl>(D
) && "Cannot refer unambiguously to a function template"
) ? void (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3194, __extension__ __PRETTY_FUNCTION__))
3194 "Cannot refer unambiguously to a function template")(static_cast <bool> (!isa<FunctionTemplateDecl>(D
) && "Cannot refer unambiguously to a function template"
) ? void (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3194, __extension__ __PRETTY_FUNCTION__))
;
3195
3196 SourceLocation Loc = NameInfo.getLoc();
3197 if (CheckDeclInExpr(*this, Loc, D))
3198 return ExprError();
3199
3200 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3201 // Specifically diagnose references to class templates that are missing
3202 // a template argument list.
3203 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3204 return ExprError();
3205 }
3206
3207 // Make sure that we're referring to a value.
3208 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3209 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3210 Diag(D->getLocation(), diag::note_declared_at);
3211 return ExprError();
3212 }
3213
3214 // Check whether this declaration can be used. Note that we suppress
3215 // this check when we're going to perform argument-dependent lookup
3216 // on this function name, because this might not be the function
3217 // that overload resolution actually selects.
3218 if (DiagnoseUseOfDecl(D, Loc))
3219 return ExprError();
3220
3221 auto *VD = cast<ValueDecl>(D);
3222
3223 // Only create DeclRefExpr's for valid Decl's.
3224 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3225 return ExprError();
3226
3227 // Handle members of anonymous structs and unions. If we got here,
3228 // and the reference is to a class member indirect field, then this
3229 // must be the subject of a pointer-to-member expression.
3230 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3231 if (!indirectField->isCXXClassMember())
3232 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3233 indirectField);
3234
3235 QualType type = VD->getType();
3236 if (type.isNull())
3237 return ExprError();
3238 ExprValueKind valueKind = VK_PRValue;
3239
3240 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3241 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3242 // is expanded by some outer '...' in the context of the use.
3243 type = type.getNonPackExpansionType();
3244
3245 switch (D->getKind()) {
3246 // Ignore all the non-ValueDecl kinds.
3247#define ABSTRACT_DECL(kind)
3248#define VALUE(type, base)
3249#define DECL(type, base) case Decl::type:
3250#include "clang/AST/DeclNodes.inc"
3251 llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3251)
;
3252
3253 // These shouldn't make it here.
3254 case Decl::ObjCAtDefsField:
3255 llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3255)
;
3256
3257 // Enum constants are always r-values and never references.
3258 // Unresolved using declarations are dependent.
3259 case Decl::EnumConstant:
3260 case Decl::UnresolvedUsingValue:
3261 case Decl::OMPDeclareReduction:
3262 case Decl::OMPDeclareMapper:
3263 valueKind = VK_PRValue;
3264 break;
3265
3266 // Fields and indirect fields that got here must be for
3267 // pointer-to-member expressions; we just call them l-values for
3268 // internal consistency, because this subexpression doesn't really
3269 // exist in the high-level semantics.
3270 case Decl::Field:
3271 case Decl::IndirectField:
3272 case Decl::ObjCIvar:
3273 assert(getLangOpts().CPlusPlus && "building reference to field in C?")(static_cast <bool> (getLangOpts().CPlusPlus &&
"building reference to field in C?") ? void (0) : __assert_fail
("getLangOpts().CPlusPlus && \"building reference to field in C?\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3273, __extension__ __PRETTY_FUNCTION__))
;
3274
3275 // These can't have reference type in well-formed programs, but
3276 // for internal consistency we do this anyway.
3277 type = type.getNonReferenceType();
3278 valueKind = VK_LValue;
3279 break;
3280
3281 // Non-type template parameters are either l-values or r-values
3282 // depending on the type.
3283 case Decl::NonTypeTemplateParm: {
3284 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3285 type = reftype->getPointeeType();
3286 valueKind = VK_LValue; // even if the parameter is an r-value reference
3287 break;
3288 }
3289
3290 // [expr.prim.id.unqual]p2:
3291 // If the entity is a template parameter object for a template
3292 // parameter of type T, the type of the expression is const T.
3293 // [...] The expression is an lvalue if the entity is a [...] template
3294 // parameter object.
3295 if (type->isRecordType()) {
3296 type = type.getUnqualifiedType().withConst();
3297 valueKind = VK_LValue;
3298 break;
3299 }
3300
3301 // For non-references, we need to strip qualifiers just in case
3302 // the template parameter was declared as 'const int' or whatever.
3303 valueKind = VK_PRValue;
3304 type = type.getUnqualifiedType();
3305 break;
3306 }
3307
3308 case Decl::Var:
3309 case Decl::VarTemplateSpecialization:
3310 case Decl::VarTemplatePartialSpecialization:
3311 case Decl::Decomposition:
3312 case Decl::OMPCapturedExpr:
3313 // In C, "extern void blah;" is valid and is an r-value.
3314 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3315 type->isVoidType()) {
3316 valueKind = VK_PRValue;
3317 break;
3318 }
3319 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3320
3321 case Decl::ImplicitParam:
3322 case Decl::ParmVar: {
3323 // These are always l-values.
3324 valueKind = VK_LValue;
3325 type = type.getNonReferenceType();
3326
3327 // FIXME: Does the addition of const really only apply in
3328 // potentially-evaluated contexts? Since the variable isn't actually
3329 // captured in an unevaluated context, it seems that the answer is no.
3330 if (!isUnevaluatedContext()) {
3331 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3332 if (!CapturedType.isNull())
3333 type = CapturedType;
3334 }
3335
3336 break;
3337 }
3338
3339 case Decl::Binding: {
3340 // These are always lvalues.
3341 valueKind = VK_LValue;
3342 type = type.getNonReferenceType();
3343 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3344 // decides how that's supposed to work.
3345 auto *BD = cast<BindingDecl>(VD);
3346 if (BD->getDeclContext() != CurContext) {
3347 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3348 if (DD && DD->hasLocalStorage())
3349 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3350 }
3351 break;
3352 }
3353
3354 case Decl::Function: {
3355 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3356 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3357 type = Context.BuiltinFnTy;
3358 valueKind = VK_PRValue;
3359 break;
3360 }
3361 }
3362
3363 const FunctionType *fty = type->castAs<FunctionType>();
3364
3365 // If we're referring to a function with an __unknown_anytype
3366 // result type, make the entire expression __unknown_anytype.
3367 if (fty->getReturnType() == Context.UnknownAnyTy) {
3368 type = Context.UnknownAnyTy;
3369 valueKind = VK_PRValue;
3370 break;
3371 }
3372
3373 // Functions are l-values in C++.
3374 if (getLangOpts().CPlusPlus) {
3375 valueKind = VK_LValue;
3376 break;
3377 }
3378
3379 // C99 DR 316 says that, if a function type comes from a
3380 // function definition (without a prototype), that type is only
3381 // used for checking compatibility. Therefore, when referencing
3382 // the function, we pretend that we don't have the full function
3383 // type.
3384 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3385 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3386 fty->getExtInfo());
3387
3388 // Functions are r-values in C.
3389 valueKind = VK_PRValue;
3390 break;
3391 }
3392
3393 case Decl::CXXDeductionGuide:
3394 llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3394)
;
3395
3396 case Decl::MSProperty:
3397 case Decl::MSGuid:
3398 case Decl::TemplateParamObject:
3399 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3400 // capture in OpenMP, or duplicated between host and device?
3401 valueKind = VK_LValue;
3402 break;
3403
3404 case Decl::CXXMethod:
3405 // If we're referring to a method with an __unknown_anytype
3406 // result type, make the entire expression __unknown_anytype.
3407 // This should only be possible with a type written directly.
3408 if (const FunctionProtoType *proto =
3409 dyn_cast<FunctionProtoType>(VD->getType()))
3410 if (proto->getReturnType() == Context.UnknownAnyTy) {
3411 type = Context.UnknownAnyTy;
3412 valueKind = VK_PRValue;
3413 break;
3414 }
3415
3416 // C++ methods are l-values if static, r-values if non-static.
3417 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3418 valueKind = VK_LValue;
3419 break;
3420 }
3421 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3422
3423 case Decl::CXXConversion:
3424 case Decl::CXXDestructor:
3425 case Decl::CXXConstructor:
3426 valueKind = VK_PRValue;
3427 break;
3428 }
3429
3430 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3431 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3432 TemplateArgs);
3433}
3434
3435static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3436 SmallString<32> &Target) {
3437 Target.resize(CharByteWidth * (Source.size() + 1));
3438 char *ResultPtr = &Target[0];
3439 const llvm::UTF8 *ErrorPtr;
3440 bool success =
3441 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3442 (void)success;
3443 assert(success)(static_cast <bool> (success) ? void (0) : __assert_fail
("success", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3443, __extension__ __PRETTY_FUNCTION__))
;
3444 Target.resize(ResultPtr - &Target[0]);
3445}
3446
3447ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3448 PredefinedExpr::IdentKind IK) {
3449 // Pick the current block, lambda, captured statement or function.
3450 Decl *currentDecl = nullptr;
3451 if (const BlockScopeInfo *BSI = getCurBlock())
3452 currentDecl = BSI->TheDecl;
3453 else if (const LambdaScopeInfo *LSI = getCurLambda())
3454 currentDecl = LSI->CallOperator;
3455 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3456 currentDecl = CSI->TheCapturedDecl;
3457 else
3458 currentDecl = getCurFunctionOrMethodDecl();
3459
3460 if (!currentDecl) {
3461 Diag(Loc, diag::ext_predef_outside_function);
3462 currentDecl = Context.getTranslationUnitDecl();
3463 }
3464
3465 QualType ResTy;
3466 StringLiteral *SL = nullptr;
3467 if (cast<DeclContext>(currentDecl)->isDependentContext())
3468 ResTy = Context.DependentTy;
3469 else {
3470 // Pre-defined identifiers are of type char[x], where x is the length of
3471 // the string.
3472 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3473 unsigned Length = Str.length();
3474
3475 llvm::APInt LengthI(32, Length + 1);
3476 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3477 ResTy =
3478 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3479 SmallString<32> RawChars;
3480 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3481 Str, RawChars);
3482 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3483 ArrayType::Normal,
3484 /*IndexTypeQuals*/ 0);
3485 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3486 /*Pascal*/ false, ResTy, Loc);
3487 } else {
3488 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3489 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3490 ArrayType::Normal,
3491 /*IndexTypeQuals*/ 0);
3492 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3493 /*Pascal*/ false, ResTy, Loc);
3494 }
3495 }
3496
3497 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3498}
3499
3500ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3501 SourceLocation LParen,
3502 SourceLocation RParen,
3503 TypeSourceInfo *TSI) {
3504 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3505}
3506
3507ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3508 SourceLocation LParen,
3509 SourceLocation RParen,
3510 ParsedType ParsedTy) {
3511 TypeSourceInfo *TSI = nullptr;
3512 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3513
3514 if (Ty.isNull())
3515 return ExprError();
3516 if (!TSI)
3517 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3518
3519 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3520}
3521
3522ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3523 PredefinedExpr::IdentKind IK;
3524
3525 switch (Kind) {
3526 default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3526)
;
3527 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3528 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3529 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3530 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3531 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3532 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3533 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3534 }
3535
3536 return BuildPredefinedExpr(Loc, IK);
3537}
3538
3539ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3540 SmallString<16> CharBuffer;
3541 bool Invalid = false;
3542 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3543 if (Invalid)
3544 return ExprError();
3545
3546 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3547 PP, Tok.getKind());
3548 if (Literal.hadError())
3549 return ExprError();
3550
3551 QualType Ty;
3552 if (Literal.isWide())
3553 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3554 else if (Literal.isUTF8() && getLangOpts().Char8)
3555 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3556 else if (Literal.isUTF16())
3557 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3558 else if (Literal.isUTF32())
3559 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3560 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3561 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3562 else
3563 Ty = Context.CharTy; // 'x' -> char in C++
3564
3565 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3566 if (Literal.isWide())
3567 Kind = CharacterLiteral::Wide;
3568 else if (Literal.isUTF16())
3569 Kind = CharacterLiteral::UTF16;
3570 else if (Literal.isUTF32())
3571 Kind = CharacterLiteral::UTF32;
3572 else if (Literal.isUTF8())
3573 Kind = CharacterLiteral::UTF8;
3574
3575 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3576 Tok.getLocation());
3577
3578 if (Literal.getUDSuffix().empty())
3579 return Lit;
3580
3581 // We're building a user-defined literal.
3582 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3583 SourceLocation UDSuffixLoc =
3584 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3585
3586 // Make sure we're allowed user-defined literals here.
3587 if (!UDLScope)
3588 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3589
3590 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3591 // operator "" X (ch)
3592 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3593 Lit, Tok.getLocation());
3594}
3595
3596ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3597 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3598 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3599 Context.IntTy, Loc);
3600}
3601
3602static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3603 QualType Ty, SourceLocation Loc) {
3604 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3605
3606 using llvm::APFloat;
3607 APFloat Val(Format);
3608
3609 APFloat::opStatus result = Literal.GetFloatValue(Val);
3610
3611 // Overflow is always an error, but underflow is only an error if
3612 // we underflowed to zero (APFloat reports denormals as underflow).
3613 if ((result & APFloat::opOverflow) ||
3614 ((result & APFloat::opUnderflow) && Val.isZero())) {
3615 unsigned diagnostic;
3616 SmallString<20> buffer;
3617 if (result & APFloat::opOverflow) {
3618 diagnostic = diag::warn_float_overflow;
3619 APFloat::getLargest(Format).toString(buffer);
3620 } else {
3621 diagnostic = diag::warn_float_underflow;
3622 APFloat::getSmallest(Format).toString(buffer);
3623 }
3624
3625 S.Diag(Loc, diagnostic)
3626 << Ty
3627 << StringRef(buffer.data(), buffer.size());
3628 }
3629
3630 bool isExact = (result == APFloat::opOK);
3631 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3632}
3633
3634bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3635 assert(E && "Invalid expression")(static_cast <bool> (E && "Invalid expression")
? void (0) : __assert_fail ("E && \"Invalid expression\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3635, __extension__ __PRETTY_FUNCTION__))
;
3636
3637 if (E->isValueDependent())
3638 return false;
3639
3640 QualType QT = E->getType();
3641 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3642 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3643 return true;
3644 }
3645
3646 llvm::APSInt ValueAPS;
3647 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3648
3649 if (R.isInvalid())
3650 return true;
3651
3652 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3653 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3654 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3655 << toString(ValueAPS, 10) << ValueIsPositive;
3656 return true;
3657 }
3658
3659 return false;
3660}
3661
3662ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3663 // Fast path for a single digit (which is quite common). A single digit
3664 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3665 if (Tok.getLength() == 1) {
3666 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3667 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3668 }
3669
3670 SmallString<128> SpellingBuffer;
3671 // NumericLiteralParser wants to overread by one character. Add padding to
3672 // the buffer in case the token is copied to the buffer. If getSpelling()
3673 // returns a StringRef to the memory buffer, it should have a null char at
3674 // the EOF, so it is also safe.
3675 SpellingBuffer.resize(Tok.getLength() + 1);
3676
3677 // Get the spelling of the token, which eliminates trigraphs, etc.
3678 bool Invalid = false;
3679 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3680 if (Invalid)
3681 return ExprError();
3682
3683 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3684 PP.getSourceManager(), PP.getLangOpts(),
3685 PP.getTargetInfo(), PP.getDiagnostics());
3686 if (Literal.hadError)
3687 return ExprError();
3688
3689 if (Literal.hasUDSuffix()) {
3690 // We're building a user-defined literal.
3691 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3692 SourceLocation UDSuffixLoc =
3693 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3694
3695 // Make sure we're allowed user-defined literals here.
3696 if (!UDLScope)
3697 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3698
3699 QualType CookedTy;
3700 if (Literal.isFloatingLiteral()) {
3701 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3702 // long double, the literal is treated as a call of the form
3703 // operator "" X (f L)
3704 CookedTy = Context.LongDoubleTy;
3705 } else {
3706 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3707 // unsigned long long, the literal is treated as a call of the form
3708 // operator "" X (n ULL)
3709 CookedTy = Context.UnsignedLongLongTy;
3710 }
3711
3712 DeclarationName OpName =
3713 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3714 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3715 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3716
3717 SourceLocation TokLoc = Tok.getLocation();
3718
3719 // Perform literal operator lookup to determine if we're building a raw
3720 // literal or a cooked one.
3721 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3722 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3723 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3724 /*AllowStringTemplatePack*/ false,
3725 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3726 case LOLR_ErrorNoDiagnostic:
3727 // Lookup failure for imaginary constants isn't fatal, there's still the
3728 // GNU extension producing _Complex types.
3729 break;
3730 case LOLR_Error:
3731 return ExprError();
3732 case LOLR_Cooked: {
3733 Expr *Lit;
3734 if (Literal.isFloatingLiteral()) {
3735 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3736 } else {
3737 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3738 if (Literal.GetIntegerValue(ResultVal))
3739 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3740 << /* Unsigned */ 1;
3741 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3742 Tok.getLocation());
3743 }
3744 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3745 }
3746
3747 case LOLR_Raw: {
3748 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3749 // literal is treated as a call of the form
3750 // operator "" X ("n")
3751 unsigned Length = Literal.getUDSuffixOffset();
3752 QualType StrTy = Context.getConstantArrayType(
3753 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3754 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3755 Expr *Lit = StringLiteral::Create(
3756 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3757 /*Pascal*/false, StrTy, &TokLoc, 1);
3758 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3759 }
3760
3761 case LOLR_Template: {
3762 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3763 // template), L is treated as a call fo the form
3764 // operator "" X <'c1', 'c2', ... 'ck'>()
3765 // where n is the source character sequence c1 c2 ... ck.
3766 TemplateArgumentListInfo ExplicitArgs;
3767 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3768 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3769 llvm::APSInt Value(CharBits, CharIsUnsigned);
3770 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3771 Value = TokSpelling[I];
3772 TemplateArgument Arg(Context, Value, Context.CharTy);
3773 TemplateArgumentLocInfo ArgInfo;
3774 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3775 }
3776 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3777 &ExplicitArgs);
3778 }
3779 case LOLR_StringTemplatePack:
3780 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3780)
;
3781 }
3782 }
3783
3784 Expr *Res;
3785
3786 if (Literal.isFixedPointLiteral()) {
3787 QualType Ty;
3788
3789 if (Literal.isAccum) {
3790 if (Literal.isHalf) {
3791 Ty = Context.ShortAccumTy;
3792 } else if (Literal.isLong) {
3793 Ty = Context.LongAccumTy;
3794 } else {
3795 Ty = Context.AccumTy;
3796 }
3797 } else if (Literal.isFract) {
3798 if (Literal.isHalf) {
3799 Ty = Context.ShortFractTy;
3800 } else if (Literal.isLong) {
3801 Ty = Context.LongFractTy;
3802 } else {
3803 Ty = Context.FractTy;
3804 }
3805 }
3806
3807 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3808
3809 bool isSigned = !Literal.isUnsigned;
3810 unsigned scale = Context.getFixedPointScale(Ty);
3811 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3812
3813 llvm::APInt Val(bit_width, 0, isSigned);
3814 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3815 bool ValIsZero = Val.isNullValue() && !Overflowed;
3816
3817 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3818 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3819 // Clause 6.4.4 - The value of a constant shall be in the range of
3820 // representable values for its type, with exception for constants of a
3821 // fract type with a value of exactly 1; such a constant shall denote
3822 // the maximal value for the type.
3823 --Val;
3824 else if (Val.ugt(MaxVal) || Overflowed)
3825 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3826
3827 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3828 Tok.getLocation(), scale);
3829 } else if (Literal.isFloatingLiteral()) {
3830 QualType Ty;
3831 if (Literal.isHalf){
3832 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3833 Ty = Context.HalfTy;
3834 else {
3835 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3836 return ExprError();
3837 }
3838 } else if (Literal.isFloat)
3839 Ty = Context.FloatTy;
3840 else if (Literal.isLong)
3841 Ty = Context.LongDoubleTy;
3842 else if (Literal.isFloat16)
3843 Ty = Context.Float16Ty;
3844 else if (Literal.isFloat128)
3845 Ty = Context.Float128Ty;
3846 else
3847 Ty = Context.DoubleTy;
3848
3849 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3850
3851 if (Ty == Context.DoubleTy) {
3852 if (getLangOpts().SinglePrecisionConstants) {
3853 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3854 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3855 }
3856 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3857 "cl_khr_fp64", getLangOpts())) {
3858 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3859 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3860 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3861 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3862 }
3863 }
3864 } else if (!Literal.isIntegerLiteral()) {
3865 return ExprError();
3866 } else {
3867 QualType Ty;
3868
3869 // 'long long' is a C99 or C++11 feature.
3870 if (!getLangOpts().C99 && Literal.isLongLong) {
3871 if (getLangOpts().CPlusPlus)
3872 Diag(Tok.getLocation(),
3873 getLangOpts().CPlusPlus11 ?
3874 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3875 else
3876 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3877 }
3878
3879 // 'z/uz' literals are a C++2b feature.
3880 if (Literal.isSizeT)
3881 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3882 ? getLangOpts().CPlusPlus2b
3883 ? diag::warn_cxx20_compat_size_t_suffix
3884 : diag::ext_cxx2b_size_t_suffix
3885 : diag::err_cxx2b_size_t_suffix);
3886
3887 // Get the value in the widest-possible width.
3888 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3889 llvm::APInt ResultVal(MaxWidth, 0);
3890
3891 if (Literal.GetIntegerValue(ResultVal)) {
3892 // If this value didn't fit into uintmax_t, error and force to ull.
3893 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3894 << /* Unsigned */ 1;
3895 Ty = Context.UnsignedLongLongTy;
3896 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&(static_cast <bool> (Context.getTypeSize(Ty) == ResultVal
.getBitWidth() && "long long is not intmax_t?") ? void
(0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3897, __extension__ __PRETTY_FUNCTION__))
3897 "long long is not intmax_t?")(static_cast <bool> (Context.getTypeSize(Ty) == ResultVal
.getBitWidth() && "long long is not intmax_t?") ? void
(0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3897, __extension__ __PRETTY_FUNCTION__))
;
3898 } else {
3899 // If this value fits into a ULL, try to figure out what else it fits into
3900 // according to the rules of C99 6.4.4.1p5.
3901
3902 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3903 // be an unsigned int.
3904 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3905
3906 // Check from smallest to largest, picking the smallest type we can.
3907 unsigned Width = 0;
3908
3909 // Microsoft specific integer suffixes are explicitly sized.
3910 if (Literal.MicrosoftInteger) {
3911 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3912 Width = 8;
3913 Ty = Context.CharTy;
3914 } else {
3915 Width = Literal.MicrosoftInteger;
3916 Ty = Context.getIntTypeForBitwidth(Width,
3917 /*Signed=*/!Literal.isUnsigned);
3918 }
3919 }
3920
3921 // Check C++2b size_t literals.
3922 if (Literal.isSizeT) {
3923 assert(!Literal.MicrosoftInteger &&(static_cast <bool> (!Literal.MicrosoftInteger &&
"size_t literals can't be Microsoft literals") ? void (0) : __assert_fail
("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3924, __extension__ __PRETTY_FUNCTION__))
3924 "size_t literals can't be Microsoft literals")(static_cast <bool> (!Literal.MicrosoftInteger &&
"size_t literals can't be Microsoft literals") ? void (0) : __assert_fail
("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 3924, __extension__ __PRETTY_FUNCTION__))
;
3925 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3926 Context.getTargetInfo().getSizeType());
3927
3928 // Does it fit in size_t?
3929 if (ResultVal.isIntN(SizeTSize)) {
3930 // Does it fit in ssize_t?
3931 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3932 Ty = Context.getSignedSizeType();
3933 else if (AllowUnsigned)
3934 Ty = Context.getSizeType();
3935 Width = SizeTSize;
3936 }
3937 }
3938
3939 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3940 !Literal.isSizeT) {
3941 // Are int/unsigned possibilities?
3942 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3943
3944 // Does it fit in a unsigned int?
3945 if (ResultVal.isIntN(IntSize)) {
3946 // Does it fit in a signed int?
3947 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3948 Ty = Context.IntTy;
3949 else if (AllowUnsigned)
3950 Ty = Context.UnsignedIntTy;
3951 Width = IntSize;
3952 }
3953 }
3954
3955 // Are long/unsigned long possibilities?
3956 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
3957 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3958
3959 // Does it fit in a unsigned long?
3960 if (ResultVal.isIntN(LongSize)) {
3961 // Does it fit in a signed long?
3962 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3963 Ty = Context.LongTy;
3964 else if (AllowUnsigned)
3965 Ty = Context.UnsignedLongTy;
3966 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3967 // is compatible.
3968 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3969 const unsigned LongLongSize =
3970 Context.getTargetInfo().getLongLongWidth();
3971 Diag(Tok.getLocation(),
3972 getLangOpts().CPlusPlus
3973 ? Literal.isLong
3974 ? diag::warn_old_implicitly_unsigned_long_cxx
3975 : /*C++98 UB*/ diag::
3976 ext_old_implicitly_unsigned_long_cxx
3977 : diag::warn_old_implicitly_unsigned_long)
3978 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3979 : /*will be ill-formed*/ 1);
3980 Ty = Context.UnsignedLongTy;
3981 }
3982 Width = LongSize;
3983 }
3984 }
3985
3986 // Check long long if needed.
3987 if (Ty.isNull() && !Literal.isSizeT) {
3988 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3989
3990 // Does it fit in a unsigned long long?
3991 if (ResultVal.isIntN(LongLongSize)) {
3992 // Does it fit in a signed long long?
3993 // To be compatible with MSVC, hex integer literals ending with the
3994 // LL or i64 suffix are always signed in Microsoft mode.
3995 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3996 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3997 Ty = Context.LongLongTy;
3998 else if (AllowUnsigned)
3999 Ty = Context.UnsignedLongLongTy;
4000 Width = LongLongSize;
4001 }
4002 }
4003
4004 // If we still couldn't decide a type, we either have 'size_t' literal
4005 // that is out of range, or a decimal literal that does not fit in a
4006 // signed long long and has no U suffix.
4007 if (Ty.isNull()) {
4008 if (Literal.isSizeT)
4009 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4010 << Literal.isUnsigned;
4011 else
4012 Diag(Tok.getLocation(),
4013 diag::ext_integer_literal_too_large_for_signed);
4014 Ty = Context.UnsignedLongLongTy;
4015 Width = Context.getTargetInfo().getLongLongWidth();
4016 }
4017
4018 if (ResultVal.getBitWidth() != Width)
4019 ResultVal = ResultVal.trunc(Width);
4020 }
4021 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4022 }
4023
4024 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4025 if (Literal.isImaginary) {
4026 Res = new (Context) ImaginaryLiteral(Res,
4027 Context.getComplexType(Res->getType()));
4028
4029 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4030 }
4031 return Res;
4032}
4033
4034ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4035 assert(E && "ActOnParenExpr() missing expr")(static_cast <bool> (E && "ActOnParenExpr() missing expr"
) ? void (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4035, __extension__ __PRETTY_FUNCTION__))
;
4036 QualType ExprTy = E->getType();
4037 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4038 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4039 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4040 return new (Context) ParenExpr(L, R, E);
4041}
4042
4043static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4044 SourceLocation Loc,
4045 SourceRange ArgRange) {
4046 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4047 // scalar or vector data type argument..."
4048 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4049 // type (C99 6.2.5p18) or void.
4050 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4051 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4052 << T << ArgRange;
4053 return true;
4054 }
4055
4056 assert((T->isVoidType() || !T->isIncompleteType()) &&(static_cast <bool> ((T->isVoidType() || !T->isIncompleteType
()) && "Scalar types should always be complete") ? void
(0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4057, __extension__ __PRETTY_FUNCTION__))
4057 "Scalar types should always be complete")(static_cast <bool> ((T->isVoidType() || !T->isIncompleteType
()) && "Scalar types should always be complete") ? void
(0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4057, __extension__ __PRETTY_FUNCTION__))
;
4058 return false;
4059}
4060
4061static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4062 SourceLocation Loc,
4063 SourceRange ArgRange,
4064 UnaryExprOrTypeTrait TraitKind) {
4065 // Invalid types must be hard errors for SFINAE in C++.
4066 if (S.LangOpts.CPlusPlus)
4067 return true;
4068
4069 // C99 6.5.3.4p1:
4070 if (T->isFunctionType() &&
4071 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4072 TraitKind == UETT_PreferredAlignOf)) {
4073 // sizeof(function)/alignof(function) is allowed as an extension.
4074 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4075 << getTraitSpelling(TraitKind) << ArgRange;
4076 return false;
4077 }
4078
4079 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4080 // this is an error (OpenCL v1.1 s6.3.k)
4081 if (T->isVoidType()) {
4082 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4083 : diag::ext_sizeof_alignof_void_type;
4084 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4085 return false;
4086 }
4087
4088 return true;
4089}
4090
4091static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4092 SourceLocation Loc,
4093 SourceRange ArgRange,
4094 UnaryExprOrTypeTrait TraitKind) {
4095 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4096 // runtime doesn't allow it.
4097 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4098 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4099 << T << (TraitKind == UETT_SizeOf)
4100 << ArgRange;
4101 return true;
4102 }
4103
4104 return false;
4105}
4106
4107/// Check whether E is a pointer from a decayed array type (the decayed
4108/// pointer type is equal to T) and emit a warning if it is.
4109static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4110 Expr *E) {
4111 // Don't warn if the operation changed the type.
4112 if (T != E->getType())
4113 return;
4114
4115 // Now look for array decays.
4116 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4117 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4118 return;
4119
4120 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4121 << ICE->getType()
4122 << ICE->getSubExpr()->getType();
4123}
4124
4125/// Check the constraints on expression operands to unary type expression
4126/// and type traits.
4127///
4128/// Completes any types necessary and validates the constraints on the operand
4129/// expression. The logic mostly mirrors the type-based overload, but may modify
4130/// the expression as it completes the type for that expression through template
4131/// instantiation, etc.
4132bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4133 UnaryExprOrTypeTrait ExprKind) {
4134 QualType ExprTy = E->getType();
4135 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4135, __extension__ __PRETTY_FUNCTION__))
;
4136
4137 bool IsUnevaluatedOperand =
4138 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4139 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4140 if (IsUnevaluatedOperand) {
4141 ExprResult Result = CheckUnevaluatedOperand(E);
4142 if (Result.isInvalid())
4143 return true;
4144 E = Result.get();
4145 }
4146
4147 // The operand for sizeof and alignof is in an unevaluated expression context,
4148 // so side effects could result in unintended consequences.
4149 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4150 // used to build SFINAE gadgets.
4151 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4152 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4153 !E->isInstantiationDependent() &&
4154 E->HasSideEffects(Context, false))
4155 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4156
4157 if (ExprKind == UETT_VecStep)
4158 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4159 E->getSourceRange());
4160
4161 // Explicitly list some types as extensions.
4162 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4163 E->getSourceRange(), ExprKind))
4164 return false;
4165
4166 // 'alignof' applied to an expression only requires the base element type of
4167 // the expression to be complete. 'sizeof' requires the expression's type to
4168 // be complete (and will attempt to complete it if it's an array of unknown
4169 // bound).
4170 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4171 if (RequireCompleteSizedType(
4172 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4173 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4174 getTraitSpelling(ExprKind), E->getSourceRange()))
4175 return true;
4176 } else {
4177 if (RequireCompleteSizedExprType(
4178 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4179 getTraitSpelling(ExprKind), E->getSourceRange()))
4180 return true;
4181 }
4182
4183 // Completing the expression's type may have changed it.
4184 ExprTy = E->getType();
4185 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4185, __extension__ __PRETTY_FUNCTION__))
;
4186
4187 if (ExprTy->isFunctionType()) {
4188 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4189 << getTraitSpelling(ExprKind) << E->getSourceRange();
4190 return true;
4191 }
4192
4193 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4194 E->getSourceRange(), ExprKind))
4195 return true;
4196
4197 if (ExprKind == UETT_SizeOf) {
4198 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4199 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4200 QualType OType = PVD->getOriginalType();
4201 QualType Type = PVD->getType();
4202 if (Type->isPointerType() && OType->isArrayType()) {
4203 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4204 << Type << OType;
4205 Diag(PVD->getLocation(), diag::note_declared_at);
4206 }
4207 }
4208 }
4209
4210 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4211 // decays into a pointer and returns an unintended result. This is most
4212 // likely a typo for "sizeof(array) op x".
4213 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4214 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4215 BO->getLHS());
4216 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4217 BO->getRHS());
4218 }
4219 }
4220
4221 return false;
4222}
4223
4224/// Check the constraints on operands to unary expression and type
4225/// traits.
4226///
4227/// This will complete any types necessary, and validate the various constraints
4228/// on those operands.
4229///
4230/// The UsualUnaryConversions() function is *not* called by this routine.
4231/// C99 6.3.2.1p[2-4] all state:
4232/// Except when it is the operand of the sizeof operator ...
4233///
4234/// C++ [expr.sizeof]p4
4235/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4236/// standard conversions are not applied to the operand of sizeof.
4237///
4238/// This policy is followed for all of the unary trait expressions.
4239bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4240 SourceLocation OpLoc,
4241 SourceRange ExprRange,
4242 UnaryExprOrTypeTrait ExprKind) {
4243 if (ExprType->isDependentType())
4244 return false;
4245
4246 // C++ [expr.sizeof]p2:
4247 // When applied to a reference or a reference type, the result
4248 // is the size of the referenced type.
4249 // C++11 [expr.alignof]p3:
4250 // When alignof is applied to a reference type, the result
4251 // shall be the alignment of the referenced type.
4252 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4253 ExprType = Ref->getPointeeType();
4254
4255 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4256 // When alignof or _Alignof is applied to an array type, the result
4257 // is the alignment of the element type.
4258 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4259 ExprKind == UETT_OpenMPRequiredSimdAlign)
4260 ExprType = Context.getBaseElementType(ExprType);
4261
4262 if (ExprKind == UETT_VecStep)
4263 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4264
4265 // Explicitly list some types as extensions.
4266 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4267 ExprKind))
4268 return false;
4269
4270 if (RequireCompleteSizedType(
4271 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4272 getTraitSpelling(ExprKind), ExprRange))
4273 return true;
4274
4275 if (ExprType->isFunctionType()) {
4276 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4277 << getTraitSpelling(ExprKind) << ExprRange;
4278 return true;
4279 }
4280
4281 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4282 ExprKind))
4283 return true;
4284
4285 return false;
4286}
4287
4288static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4289 // Cannot know anything else if the expression is dependent.
4290 if (E->isTypeDependent())
4291 return false;
4292
4293 if (E->getObjectKind() == OK_BitField) {
4294 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4295 << 1 << E->getSourceRange();
4296 return true;
4297 }
4298
4299 ValueDecl *D = nullptr;
4300 Expr *Inner = E->IgnoreParens();
4301 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4302 D = DRE->getDecl();
4303 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4304 D = ME->getMemberDecl();
4305 }
4306
4307 // If it's a field, require the containing struct to have a
4308 // complete definition so that we can compute the layout.
4309 //
4310 // This can happen in C++11 onwards, either by naming the member
4311 // in a way that is not transformed into a member access expression
4312 // (in an unevaluated operand, for instance), or by naming the member
4313 // in a trailing-return-type.
4314 //
4315 // For the record, since __alignof__ on expressions is a GCC
4316 // extension, GCC seems to permit this but always gives the
4317 // nonsensical answer 0.
4318 //
4319 // We don't really need the layout here --- we could instead just
4320 // directly check for all the appropriate alignment-lowing
4321 // attributes --- but that would require duplicating a lot of
4322 // logic that just isn't worth duplicating for such a marginal
4323 // use-case.
4324 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4325 // Fast path this check, since we at least know the record has a
4326 // definition if we can find a member of it.
4327 if (!FD->getParent()->isCompleteDefinition()) {
4328 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4329 << E->getSourceRange();
4330 return true;
4331 }
4332
4333 // Otherwise, if it's a field, and the field doesn't have
4334 // reference type, then it must have a complete type (or be a
4335 // flexible array member, which we explicitly want to
4336 // white-list anyway), which makes the following checks trivial.
4337 if (!FD->getType()->isReferenceType())
4338 return false;
4339 }
4340
4341 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4342}
4343
4344bool Sema::CheckVecStepExpr(Expr *E) {
4345 E = E->IgnoreParens();
4346
4347 // Cannot know anything else if the expression is dependent.
4348 if (E->isTypeDependent())
4349 return false;
4350
4351 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4352}
4353
4354static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4355 CapturingScopeInfo *CSI) {
4356 assert(T->isVariablyModifiedType())(static_cast <bool> (T->isVariablyModifiedType()) ? void
(0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4356, __extension__ __PRETTY_FUNCTION__))
;
4357 assert(CSI != nullptr)(static_cast <bool> (CSI != nullptr) ? void (0) : __assert_fail
("CSI != nullptr", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4357, __extension__ __PRETTY_FUNCTION__))
;
4358
4359 // We're going to walk down into the type and look for VLA expressions.
4360 do {
4361 const Type *Ty = T.getTypePtr();
4362 switch (Ty->getTypeClass()) {
4363#define TYPE(Class, Base)
4364#define ABSTRACT_TYPE(Class, Base)
4365#define NON_CANONICAL_TYPE(Class, Base)
4366#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4367#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4368#include "clang/AST/TypeNodes.inc"
4369 T = QualType();
4370 break;
4371 // These types are never variably-modified.
4372 case Type::Builtin:
4373 case Type::Complex:
4374 case Type::Vector:
4375 case Type::ExtVector:
4376 case Type::ConstantMatrix:
4377 case Type::Record:
4378 case Type::Enum:
4379 case Type::Elaborated:
4380 case Type::TemplateSpecialization:
4381 case Type::ObjCObject:
4382 case Type::ObjCInterface:
4383 case Type::ObjCObjectPointer:
4384 case Type::ObjCTypeParam:
4385 case Type::Pipe:
4386 case Type::ExtInt:
4387 llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4387)
;
4388 case Type::Adjusted:
4389 T = cast<AdjustedType>(Ty)->getOriginalType();
4390 break;
4391 case Type::Decayed:
4392 T = cast<DecayedType>(Ty)->getPointeeType();
4393 break;
4394 case Type::Pointer:
4395 T = cast<PointerType>(Ty)->getPointeeType();
4396 break;
4397 case Type::BlockPointer:
4398 T = cast<BlockPointerType>(Ty)->getPointeeType();
4399 break;
4400 case Type::LValueReference:
4401 case Type::RValueReference:
4402 T = cast<ReferenceType>(Ty)->getPointeeType();
4403 break;
4404 case Type::MemberPointer:
4405 T = cast<MemberPointerType>(Ty)->getPointeeType();
4406 break;
4407 case Type::ConstantArray:
4408 case Type::IncompleteArray:
4409 // Losing element qualification here is fine.
4410 T = cast<ArrayType>(Ty)->getElementType();
4411 break;
4412 case Type::VariableArray: {
4413 // Losing element qualification here is fine.
4414 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4415
4416 // Unknown size indication requires no size computation.
4417 // Otherwise, evaluate and record it.
4418 auto Size = VAT->getSizeExpr();
4419 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4420 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4421 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4422
4423 T = VAT->getElementType();
4424 break;
4425 }
4426 case Type::FunctionProto:
4427 case Type::FunctionNoProto:
4428 T = cast<FunctionType>(Ty)->getReturnType();
4429 break;
4430 case Type::Paren:
4431 case Type::TypeOf:
4432 case Type::UnaryTransform:
4433 case Type::Attributed:
4434 case Type::SubstTemplateTypeParm:
4435 case Type::MacroQualified:
4436 // Keep walking after single level desugaring.
4437 T = T.getSingleStepDesugaredType(Context);
4438 break;
4439 case Type::Typedef:
4440 T = cast<TypedefType>(Ty)->desugar();
4441 break;
4442 case Type::Decltype:
4443 T = cast<DecltypeType>(Ty)->desugar();
4444 break;
4445 case Type::Auto:
4446 case Type::DeducedTemplateSpecialization:
4447 T = cast<DeducedType>(Ty)->getDeducedType();
4448 break;
4449 case Type::TypeOfExpr:
4450 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4451 break;
4452 case Type::Atomic:
4453 T = cast<AtomicType>(Ty)->getValueType();
4454 break;
4455 }
4456 } while (!T.isNull() && T->isVariablyModifiedType());
4457}
4458
4459/// Build a sizeof or alignof expression given a type operand.
4460ExprResult
4461Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4462 SourceLocation OpLoc,
4463 UnaryExprOrTypeTrait ExprKind,
4464 SourceRange R) {
4465 if (!TInfo)
4466 return ExprError();
4467
4468 QualType T = TInfo->getType();
4469
4470 if (!T->isDependentType() &&
4471 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4472 return ExprError();
4473
4474 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4475 if (auto *TT = T->getAs<TypedefType>()) {
4476 for (auto I = FunctionScopes.rbegin(),
4477 E = std::prev(FunctionScopes.rend());
4478 I != E; ++I) {
4479 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4480 if (CSI == nullptr)
4481 break;
4482 DeclContext *DC = nullptr;
4483 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4484 DC = LSI->CallOperator;
4485 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4486 DC = CRSI->TheCapturedDecl;
4487 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4488 DC = BSI->TheDecl;
4489 if (DC) {
4490 if (DC->containsDecl(TT->getDecl()))
4491 break;
4492 captureVariablyModifiedType(Context, T, CSI);
4493 }
4494 }
4495 }
4496 }
4497
4498 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4499 return new (Context) UnaryExprOrTypeTraitExpr(
4500 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4501}
4502
4503/// Build a sizeof or alignof expression given an expression
4504/// operand.
4505ExprResult
4506Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4507 UnaryExprOrTypeTrait ExprKind) {
4508 ExprResult PE = CheckPlaceholderExpr(E);
4509 if (PE.isInvalid())
4510 return ExprError();
4511
4512 E = PE.get();
4513
4514 // Verify that the operand is valid.
4515 bool isInvalid = false;
4516 if (E->isTypeDependent()) {
4517 // Delay type-checking for type-dependent expressions.
4518 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4519 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4520 } else if (ExprKind == UETT_VecStep) {
4521 isInvalid = CheckVecStepExpr(E);
4522 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4523 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4524 isInvalid = true;
4525 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4526 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4527 isInvalid = true;
4528 } else {
4529 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4530 }
4531
4532 if (isInvalid)
4533 return ExprError();
4534
4535 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4536 PE = TransformToPotentiallyEvaluated(E);
4537 if (PE.isInvalid()) return ExprError();
4538 E = PE.get();
4539 }
4540
4541 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4542 return new (Context) UnaryExprOrTypeTraitExpr(
4543 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4544}
4545
4546/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4547/// expr and the same for @c alignof and @c __alignof
4548/// Note that the ArgRange is invalid if isType is false.
4549ExprResult
4550Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4551 UnaryExprOrTypeTrait ExprKind, bool IsType,
4552 void *TyOrEx, SourceRange ArgRange) {
4553 // If error parsing type, ignore.
4554 if (!TyOrEx) return ExprError();
4555
4556 if (IsType) {
4557 TypeSourceInfo *TInfo;
4558 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4559 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4560 }
4561
4562 Expr *ArgEx = (Expr *)TyOrEx;
4563 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4564 return Result;
4565}
4566
4567static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4568 bool IsReal) {
4569 if (V.get()->isTypeDependent())
4570 return S.Context.DependentTy;
4571
4572 // _Real and _Imag are only l-values for normal l-values.
4573 if (V.get()->getObjectKind() != OK_Ordinary) {
4574 V = S.DefaultLvalueConversion(V.get());
4575 if (V.isInvalid())
4576 return QualType();
4577 }
4578
4579 // These operators return the element type of a complex type.
4580 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4581 return CT->getElementType();
4582
4583 // Otherwise they pass through real integer and floating point types here.
4584 if (V.get()->getType()->isArithmeticType())
4585 return V.get()->getType();
4586
4587 // Test for placeholders.
4588 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4589 if (PR.isInvalid()) return QualType();
4590 if (PR.get() != V.get()) {
4591 V = PR;
4592 return CheckRealImagOperand(S, V, Loc, IsReal);
4593 }
4594
4595 // Reject anything else.
4596 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4597 << (IsReal ? "__real" : "__imag");
4598 return QualType();
4599}
4600
4601
4602
4603ExprResult
4604Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4605 tok::TokenKind Kind, Expr *Input) {
4606 UnaryOperatorKind Opc;
4607 switch (Kind) {
4608 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4608)
;
4609 case tok::plusplus: Opc = UO_PostInc; break;
4610 case tok::minusminus: Opc = UO_PostDec; break;
4611 }
4612
4613 // Since this might is a postfix expression, get rid of ParenListExprs.
4614 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4615 if (Result.isInvalid()) return ExprError();
4616 Input = Result.get();
4617
4618 return BuildUnaryOp(S, OpLoc, Opc, Input);
4619}
4620
4621/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4622///
4623/// \return true on error
4624static bool checkArithmeticOnObjCPointer(Sema &S,
4625 SourceLocation opLoc,
4626 Expr *op) {
4627 assert(op->getType()->isObjCObjectPointerType())(static_cast <bool> (op->getType()->isObjCObjectPointerType
()) ? void (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4627, __extension__ __PRETTY_FUNCTION__))
;
4628 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4629 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4630 return false;
4631
4632 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4633 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4634 << op->getSourceRange();
4635 return true;
4636}
4637
4638static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4639 auto *BaseNoParens = Base->IgnoreParens();
4640 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4641 return MSProp->getPropertyDecl()->getType()->isArrayType();
4642 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4643}
4644
4645ExprResult
4646Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4647 Expr *idx, SourceLocation rbLoc) {
4648 if (base && !base->getType().isNull() &&
4649 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4650 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4651 SourceLocation(), /*Length*/ nullptr,
4652 /*Stride=*/nullptr, rbLoc);
4653
4654 // Since this might be a postfix expression, get rid of ParenListExprs.
4655 if (isa<ParenListExpr>(base)) {
4656 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4657 if (result.isInvalid()) return ExprError();
4658 base = result.get();
4659 }
4660
4661 // Check if base and idx form a MatrixSubscriptExpr.
4662 //
4663 // Helper to check for comma expressions, which are not allowed as indices for
4664 // matrix subscript expressions.
4665 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4666 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4667 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4668 << SourceRange(base->getBeginLoc(), rbLoc);
4669 return true;
4670 }
4671 return false;
4672 };
4673 // The matrix subscript operator ([][])is considered a single operator.
4674 // Separating the index expressions by parenthesis is not allowed.
4675 if (base->getType()->isSpecificPlaceholderType(
4676 BuiltinType::IncompleteMatrixIdx) &&
4677 !isa<MatrixSubscriptExpr>(base)) {
4678 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4679 << SourceRange(base->getBeginLoc(), rbLoc);
4680 return ExprError();
4681 }
4682 // If the base is a MatrixSubscriptExpr, try to create a new
4683 // MatrixSubscriptExpr.
4684 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4685 if (matSubscriptE) {
4686 if (CheckAndReportCommaError(idx))
4687 return ExprError();
4688
4689 assert(matSubscriptE->isIncomplete() &&(static_cast <bool> (matSubscriptE->isIncomplete() &&
"base has to be an incomplete matrix subscript") ? void (0) :
__assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4690, __extension__ __PRETTY_FUNCTION__))
4690 "base has to be an incomplete matrix subscript")(static_cast <bool> (matSubscriptE->isIncomplete() &&
"base has to be an incomplete matrix subscript") ? void (0) :
__assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4690, __extension__ __PRETTY_FUNCTION__))
;
4691 return CreateBuiltinMatrixSubscriptExpr(
4692 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4693 }
4694
4695 // Handle any non-overload placeholder types in the base and index
4696 // expressions. We can't handle overloads here because the other
4697 // operand might be an overloadable type, in which case the overload
4698 // resolution for the operator overload should get the first crack
4699 // at the overload.
4700 bool IsMSPropertySubscript = false;
4701 if (base->getType()->isNonOverloadPlaceholderType()) {
4702 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4703 if (!IsMSPropertySubscript) {
4704 ExprResult result = CheckPlaceholderExpr(base);
4705 if (result.isInvalid())
4706 return ExprError();
4707 base = result.get();
4708 }
4709 }
4710
4711 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4712 if (base->getType()->isMatrixType()) {
4713 if (CheckAndReportCommaError(idx))
4714 return ExprError();
4715
4716 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4717 }
4718
4719 // A comma-expression as the index is deprecated in C++2a onwards.
4720 if (getLangOpts().CPlusPlus20 &&
4721 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4722 (isa<CXXOperatorCallExpr>(idx) &&
4723 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4724 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4725 << SourceRange(base->getBeginLoc(), rbLoc);
4726 }
4727
4728 if (idx->getType()->isNonOverloadPlaceholderType()) {
4729 ExprResult result = CheckPlaceholderExpr(idx);
4730 if (result.isInvalid()) return ExprError();
4731 idx = result.get();
4732 }
4733
4734 // Build an unanalyzed expression if either operand is type-dependent.
4735 if (getLangOpts().CPlusPlus &&
4736 (base->isTypeDependent() || idx->isTypeDependent())) {
4737 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4738 VK_LValue, OK_Ordinary, rbLoc);
4739 }
4740
4741 // MSDN, property (C++)
4742 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4743 // This attribute can also be used in the declaration of an empty array in a
4744 // class or structure definition. For example:
4745 // __declspec(property(get=GetX, put=PutX)) int x[];
4746 // The above statement indicates that x[] can be used with one or more array
4747 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4748 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4749 if (IsMSPropertySubscript) {
4750 // Build MS property subscript expression if base is MS property reference
4751 // or MS property subscript.
4752 return new (Context) MSPropertySubscriptExpr(
4753 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4754 }
4755
4756 // Use C++ overloaded-operator rules if either operand has record
4757 // type. The spec says to do this if either type is *overloadable*,
4758 // but enum types can't declare subscript operators or conversion
4759 // operators, so there's nothing interesting for overload resolution
4760 // to do if there aren't any record types involved.
4761 //
4762 // ObjC pointers have their own subscripting logic that is not tied
4763 // to overload resolution and so should not take this path.
4764 if (getLangOpts().CPlusPlus &&
4765 (base->getType()->isRecordType() ||
4766 (!base->getType()->isObjCObjectPointerType() &&
4767 idx->getType()->isRecordType()))) {
4768 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4769 }
4770
4771 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4772
4773 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4774 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4775
4776 return Res;
4777}
4778
4779ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4780 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4781 InitializationKind Kind =
4782 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4783 InitializationSequence InitSeq(*this, Entity, Kind, E);
4784 return InitSeq.Perform(*this, Entity, Kind, E);
4785}
4786
4787ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4788 Expr *ColumnIdx,
4789 SourceLocation RBLoc) {
4790 ExprResult BaseR = CheckPlaceholderExpr(Base);
4791 if (BaseR.isInvalid())
4792 return BaseR;
4793 Base = BaseR.get();
4794
4795 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4796 if (RowR.isInvalid())
4797 return RowR;
4798 RowIdx = RowR.get();
4799
4800 if (!ColumnIdx)
4801 return new (Context) MatrixSubscriptExpr(
4802 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4803
4804 // Build an unanalyzed expression if any of the operands is type-dependent.
4805 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4806 ColumnIdx->isTypeDependent())
4807 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4808 Context.DependentTy, RBLoc);
4809
4810 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4811 if (ColumnR.isInvalid())
4812 return ColumnR;
4813 ColumnIdx = ColumnR.get();
4814
4815 // Check that IndexExpr is an integer expression. If it is a constant
4816 // expression, check that it is less than Dim (= the number of elements in the
4817 // corresponding dimension).
4818 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4819 bool IsColumnIdx) -> Expr * {
4820 if (!IndexExpr->getType()->isIntegerType() &&
4821 !IndexExpr->isTypeDependent()) {
4822 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4823 << IsColumnIdx;
4824 return nullptr;
4825 }
4826
4827 if (Optional<llvm::APSInt> Idx =
4828 IndexExpr->getIntegerConstantExpr(Context)) {
4829 if ((*Idx < 0 || *Idx >= Dim)) {
4830 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4831 << IsColumnIdx << Dim;
4832 return nullptr;
4833 }
4834 }
4835
4836 ExprResult ConvExpr =
4837 tryConvertExprToType(IndexExpr, Context.getSizeType());
4838 assert(!ConvExpr.isInvalid() &&(static_cast <bool> (!ConvExpr.isInvalid() && "should be able to convert any integer type to size type"
) ? void (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4839, __extension__ __PRETTY_FUNCTION__))
4839 "should be able to convert any integer type to size type")(static_cast <bool> (!ConvExpr.isInvalid() && "should be able to convert any integer type to size type"
) ? void (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 4839, __extension__ __PRETTY_FUNCTION__))
;
4840 return ConvExpr.get();
4841 };
4842
4843 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4844 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4845 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4846 if (!RowIdx || !ColumnIdx)
4847 return ExprError();
4848
4849 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4850 MTy->getElementType(), RBLoc);
4851}
4852
4853void Sema::CheckAddressOfNoDeref(const Expr *E) {
4854 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4855 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4856
4857 // For expressions like `&(*s).b`, the base is recorded and what should be
4858 // checked.
4859 const MemberExpr *Member = nullptr;
4860 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4861 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4862
4863 LastRecord.PossibleDerefs.erase(StrippedExpr);
4864}
4865
4866void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4867 if (isUnevaluatedContext())
4868 return;
4869
4870 QualType ResultTy = E->getType();
4871 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4872
4873 // Bail if the element is an array since it is not memory access.
4874 if (isa<ArrayType>(ResultTy))
4875 return;
4876
4877 if (ResultTy->hasAttr(attr::NoDeref)) {
4878 LastRecord.PossibleDerefs.insert(E);
4879 return;
4880 }
4881
4882 // Check if the base type is a pointer to a member access of a struct
4883 // marked with noderef.
4884 const Expr *Base = E->getBase();
4885 QualType BaseTy = Base->getType();
4886 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4887 // Not a pointer access
4888 return;
4889
4890 const MemberExpr *Member = nullptr;
4891 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4892 Member->isArrow())
4893 Base = Member->getBase();
4894
4895 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4896 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4897 LastRecord.PossibleDerefs.insert(E);
4898 }
4899}
4900
4901ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4902 Expr *LowerBound,
4903 SourceLocation ColonLocFirst,
4904 SourceLocation ColonLocSecond,
4905 Expr *Length, Expr *Stride,
4906 SourceLocation RBLoc) {
4907 if (Base->getType()->isPlaceholderType() &&
4908 !Base->getType()->isSpecificPlaceholderType(
4909 BuiltinType::OMPArraySection)) {
4910 ExprResult Result = CheckPlaceholderExpr(Base);
4911 if (Result.isInvalid())
4912 return ExprError();
4913 Base = Result.get();
4914 }
4915 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4916 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4917 if (Result.isInvalid())
4918 return ExprError();
4919 Result = DefaultLvalueConversion(Result.get());
4920 if (Result.isInvalid())
4921 return ExprError();
4922 LowerBound = Result.get();
4923 }
4924 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4925 ExprResult Result = CheckPlaceholderExpr(Length);
4926 if (Result.isInvalid())
4927 return ExprError();
4928 Result = DefaultLvalueConversion(Result.get());
4929 if (Result.isInvalid())
4930 return ExprError();
4931 Length = Result.get();
4932 }
4933 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4934 ExprResult Result = CheckPlaceholderExpr(Stride);
4935 if (Result.isInvalid())
4936 return ExprError();
4937 Result = DefaultLvalueConversion(Result.get());
4938 if (Result.isInvalid())
4939 return ExprError();
4940 Stride = Result.get();
4941 }
4942
4943 // Build an unanalyzed expression if either operand is type-dependent.
4944 if (Base->isTypeDependent() ||
4945 (LowerBound &&
4946 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4947 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4948 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4949 return new (Context) OMPArraySectionExpr(
4950 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4951 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4952 }
4953
4954 // Perform default conversions.
4955 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4956 QualType ResultTy;
4957 if (OriginalTy->isAnyPointerType()) {
4958 ResultTy = OriginalTy->getPointeeType();
4959 } else if (OriginalTy->isArrayType()) {
4960 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4961 } else {
4962 return ExprError(
4963 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4964 << Base->getSourceRange());
4965 }
4966 // C99 6.5.2.1p1
4967 if (LowerBound) {
4968 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4969 LowerBound);
4970 if (Res.isInvalid())
4971 return ExprError(Diag(LowerBound->getExprLoc(),
4972 diag::err_omp_typecheck_section_not_integer)
4973 << 0 << LowerBound->getSourceRange());
4974 LowerBound = Res.get();
4975
4976 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4977 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4978 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4979 << 0 << LowerBound->getSourceRange();
4980 }
4981 if (Length) {
4982 auto Res =
4983 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4984 if (Res.isInvalid())
4985 return ExprError(Diag(Length->getExprLoc(),
4986 diag::err_omp_typecheck_section_not_integer)
4987 << 1 << Length->getSourceRange());
4988 Length = Res.get();
4989
4990 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4991 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4992 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4993 << 1 << Length->getSourceRange();
4994 }
4995 if (Stride) {
4996 ExprResult Res =
4997 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4998 if (Res.isInvalid())
4999 return ExprError(Diag(Stride->getExprLoc(),
5000 diag::err_omp_typecheck_section_not_integer)
5001 << 1 << Stride->getSourceRange());
5002 Stride = Res.get();
5003
5004 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5005 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5006 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5007 << 1 << Stride->getSourceRange();
5008 }
5009
5010 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5011 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5012 // type. Note that functions are not objects, and that (in C99 parlance)
5013 // incomplete types are not object types.
5014 if (ResultTy->isFunctionType()) {
5015 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5016 << ResultTy << Base->getSourceRange();
5017 return ExprError();
5018 }
5019
5020 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5021 diag::err_omp_section_incomplete_type, Base))
5022 return ExprError();
5023
5024 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5025 Expr::EvalResult Result;
5026 if (LowerBound->EvaluateAsInt(Result, Context)) {
5027 // OpenMP 5.0, [2.1.5 Array Sections]
5028 // The array section must be a subset of the original array.
5029 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5030 if (LowerBoundValue.isNegative()) {
5031 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5032 << LowerBound->getSourceRange();
5033 return ExprError();
5034 }
5035 }
5036 }
5037
5038 if (Length) {
5039 Expr::EvalResult Result;
5040 if (Length->EvaluateAsInt(Result, Context)) {
5041 // OpenMP 5.0, [2.1.5 Array Sections]
5042 // The length must evaluate to non-negative integers.
5043 llvm::APSInt LengthValue = Result.Val.getInt();
5044 if (LengthValue.isNegative()) {
5045 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5046 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5047 << Length->getSourceRange();
5048 return ExprError();
5049 }
5050 }
5051 } else if (ColonLocFirst.isValid() &&
5052 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5053 !OriginalTy->isVariableArrayType()))) {
5054 // OpenMP 5.0, [2.1.5 Array Sections]
5055 // When the size of the array dimension is not known, the length must be
5056 // specified explicitly.
5057 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5058 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5059 return ExprError();
5060 }
5061
5062 if (Stride) {
5063 Expr::EvalResult Result;
5064 if (Stride->EvaluateAsInt(Result, Context)) {
5065 // OpenMP 5.0, [2.1.5 Array Sections]
5066 // The stride must evaluate to a positive integer.
5067 llvm::APSInt StrideValue = Result.Val.getInt();
5068 if (!StrideValue.isStrictlyPositive()) {
5069 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5070 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5071 << Stride->getSourceRange();
5072 return ExprError();
5073 }
5074 }
5075 }
5076
5077 if (!Base->getType()->isSpecificPlaceholderType(
5078 BuiltinType::OMPArraySection)) {
5079 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5080 if (Result.isInvalid())
5081 return ExprError();
5082 Base = Result.get();
5083 }
5084 return new (Context) OMPArraySectionExpr(
5085 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5086 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5087}
5088
5089ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5090 SourceLocation RParenLoc,
5091 ArrayRef<Expr *> Dims,
5092 ArrayRef<SourceRange> Brackets) {
5093 if (Base->getType()->isPlaceholderType()) {
5094 ExprResult Result = CheckPlaceholderExpr(Base);
5095 if (Result.isInvalid())
5096 return ExprError();
5097 Result = DefaultLvalueConversion(Result.get());
5098 if (Result.isInvalid())
5099 return ExprError();
5100 Base = Result.get();
5101 }
5102 QualType BaseTy = Base->getType();
5103 // Delay analysis of the types/expressions if instantiation/specialization is
5104 // required.
5105 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5106 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5107 LParenLoc, RParenLoc, Dims, Brackets);
5108 if (!BaseTy->isPointerType() ||
5109 (!Base->isTypeDependent() &&
5110 BaseTy->getPointeeType()->isIncompleteType()))
5111 return ExprError(Diag(Base->getExprLoc(),
5112 diag::err_omp_non_pointer_type_array_shaping_base)
5113 << Base->getSourceRange());
5114
5115 SmallVector<Expr *, 4> NewDims;
5116 bool ErrorFound = false;
5117 for (Expr *Dim : Dims) {
5118 if (Dim->getType()->isPlaceholderType()) {
5119 ExprResult Result = CheckPlaceholderExpr(Dim);
5120 if (Result.isInvalid()) {
5121 ErrorFound = true;
5122 continue;
5123 }
5124 Result = DefaultLvalueConversion(Result.get());
5125 if (Result.isInvalid()) {
5126 ErrorFound = true;
5127 continue;
5128 }
5129 Dim = Result.get();
5130 }
5131 if (!Dim->isTypeDependent()) {
5132 ExprResult Result =
5133 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5134 if (Result.isInvalid()) {
5135 ErrorFound = true;
5136 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5137 << Dim->getSourceRange();
5138 continue;
5139 }
5140 Dim = Result.get();
5141 Expr::EvalResult EvResult;
5142 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5143 // OpenMP 5.0, [2.1.4 Array Shaping]
5144 // Each si is an integral type expression that must evaluate to a
5145 // positive integer.
5146 llvm::APSInt Value = EvResult.Val.getInt();
5147 if (!Value.isStrictlyPositive()) {
5148 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5149 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5150 << Dim->getSourceRange();
5151 ErrorFound = true;
5152 continue;
5153 }
5154 }
5155 }
5156 NewDims.push_back(Dim);
5157 }
5158 if (ErrorFound)
5159 return ExprError();
5160 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5161 LParenLoc, RParenLoc, NewDims, Brackets);
5162}
5163
5164ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5165 SourceLocation LLoc, SourceLocation RLoc,
5166 ArrayRef<OMPIteratorData> Data) {
5167 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5168 bool IsCorrect = true;
5169 for (const OMPIteratorData &D : Data) {
5170 TypeSourceInfo *TInfo = nullptr;
5171 SourceLocation StartLoc;
5172 QualType DeclTy;
5173 if (!D.Type.getAsOpaquePtr()) {
5174 // OpenMP 5.0, 2.1.6 Iterators
5175 // In an iterator-specifier, if the iterator-type is not specified then
5176 // the type of that iterator is of int type.
5177 DeclTy = Context.IntTy;
5178 StartLoc = D.DeclIdentLoc;
5179 } else {
5180 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5181 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5182 }
5183
5184 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5185 DeclTy->containsUnexpandedParameterPack() ||
5186 DeclTy->isInstantiationDependentType();
5187 if (!IsDeclTyDependent) {
5188 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5189 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5190 // The iterator-type must be an integral or pointer type.
5191 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5192 << DeclTy;
5193 IsCorrect = false;
5194 continue;
5195 }
5196 if (DeclTy.isConstant(Context)) {
5197 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5198 // The iterator-type must not be const qualified.
5199 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5200 << DeclTy;
5201 IsCorrect = false;
5202 continue;
5203 }
5204 }
5205
5206 // Iterator declaration.
5207 assert(D.DeclIdent && "Identifier expected.")(static_cast <bool> (D.DeclIdent && "Identifier expected."
) ? void (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 5207, __extension__ __PRETTY_FUNCTION__))
;
5208 // Always try to create iterator declarator to avoid extra error messages
5209 // about unknown declarations use.
5210 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5211 D.DeclIdent, DeclTy, TInfo, SC_None);
5212 VD->setImplicit();
5213 if (S) {
5214 // Check for conflicting previous declaration.
5215 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5216 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5217 ForVisibleRedeclaration);
5218 Previous.suppressDiagnostics();
5219 LookupName(Previous, S);
5220
5221 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5222 /*AllowInlineNamespace=*/false);
5223 if (!Previous.empty()) {
5224 NamedDecl *Old = Previous.getRepresentativeDecl();
5225 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5226 Diag(Old->getLocation(), diag::note_previous_definition);
5227 } else {
5228 PushOnScopeChains(VD, S);
5229 }
5230 } else {
5231 CurContext->addDecl(VD);
5232 }
5233 Expr *Begin = D.Range.Begin;
5234 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5235 ExprResult BeginRes =
5236 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5237 Begin = BeginRes.get();
5238 }
5239 Expr *End = D.Range.End;
5240 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5241 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5242 End = EndRes.get();
5243 }
5244 Expr *Step = D.Range.Step;
5245 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5246 if (!Step->getType()->isIntegralType(Context)) {
5247 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5248 << Step << Step->getSourceRange();
5249 IsCorrect = false;
5250 continue;
5251 }
5252 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5253 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5254 // If the step expression of a range-specification equals zero, the
5255 // behavior is unspecified.
5256 if (Result && Result->isNullValue()) {
5257 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5258 << Step << Step->getSourceRange();
5259 IsCorrect = false;
5260 continue;
5261 }
5262 }
5263 if (!Begin || !End || !IsCorrect) {
5264 IsCorrect = false;
5265 continue;
5266 }
5267 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5268 IDElem.IteratorDecl = VD;
5269 IDElem.AssignmentLoc = D.AssignLoc;
5270 IDElem.Range.Begin = Begin;
5271 IDElem.Range.End = End;
5272 IDElem.Range.Step = Step;
5273 IDElem.ColonLoc = D.ColonLoc;
5274 IDElem.SecondColonLoc = D.SecColonLoc;
5275 }
5276 if (!IsCorrect) {
5277 // Invalidate all created iterator declarations if error is found.
5278 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5279 if (Decl *ID = D.IteratorDecl)
5280 ID->setInvalidDecl();
5281 }
5282 return ExprError();
5283 }
5284 SmallVector<OMPIteratorHelperData, 4> Helpers;
5285 if (!CurContext->isDependentContext()) {
5286 // Build number of ityeration for each iteration range.
5287 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5288 // ((Begini-Stepi-1-Endi) / -Stepi);
5289 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5290 // (Endi - Begini)
5291 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5292 D.Range.Begin);
5293 if(!Res.isUsable()) {
5294 IsCorrect = false;
5295 continue;
5296 }
5297 ExprResult St, St1;
5298 if (D.Range.Step) {
5299 St = D.Range.Step;
5300 // (Endi - Begini) + Stepi
5301 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5302 if (!Res.isUsable()) {
5303 IsCorrect = false;
5304 continue;
5305 }
5306 // (Endi - Begini) + Stepi - 1
5307 Res =
5308 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5309 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5310 if (!Res.isUsable()) {
5311 IsCorrect = false;
5312 continue;
5313 }
5314 // ((Endi - Begini) + Stepi - 1) / Stepi
5315 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5316 if (!Res.isUsable()) {
5317 IsCorrect = false;
5318 continue;
5319 }
5320 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5321 // (Begini - Endi)
5322 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5323 D.Range.Begin, D.Range.End);
5324 if (!Res1.isUsable()) {
5325 IsCorrect = false;
5326 continue;
5327 }
5328 // (Begini - Endi) - Stepi
5329 Res1 =
5330 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5331 if (!Res1.isUsable()) {
5332 IsCorrect = false;
5333 continue;
5334 }
5335 // (Begini - Endi) - Stepi - 1
5336 Res1 =
5337 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5338 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5339 if (!Res1.isUsable()) {
5340 IsCorrect = false;
5341 continue;
5342 }
5343 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5344 Res1 =
5345 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5346 if (!Res1.isUsable()) {
5347 IsCorrect = false;
5348 continue;
5349 }
5350 // Stepi > 0.
5351 ExprResult CmpRes =
5352 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5353 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5354 if (!CmpRes.isUsable()) {
5355 IsCorrect = false;
5356 continue;
5357 }
5358 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5359 Res.get(), Res1.get());
5360 if (!Res.isUsable()) {
5361 IsCorrect = false;
5362 continue;
5363 }
5364 }
5365 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5366 if (!Res.isUsable()) {
5367 IsCorrect = false;
5368 continue;
5369 }
5370
5371 // Build counter update.
5372 // Build counter.
5373 auto *CounterVD =
5374 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5375 D.IteratorDecl->getBeginLoc(), nullptr,
5376 Res.get()->getType(), nullptr, SC_None);
5377 CounterVD->setImplicit();
5378 ExprResult RefRes =
5379 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5380 D.IteratorDecl->getBeginLoc());
5381 // Build counter update.
5382 // I = Begini + counter * Stepi;
5383 ExprResult UpdateRes;
5384 if (D.Range.Step) {
5385 UpdateRes = CreateBuiltinBinOp(
5386 D.AssignmentLoc, BO_Mul,
5387 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5388 } else {
5389 UpdateRes = DefaultLvalueConversion(RefRes.get());
5390 }
5391 if (!UpdateRes.isUsable()) {
5392 IsCorrect = false;
5393 continue;
5394 }
5395 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5396 UpdateRes.get());
5397 if (!UpdateRes.isUsable()) {
5398 IsCorrect = false;
5399 continue;
5400 }
5401 ExprResult VDRes =
5402 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5403 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5404 D.IteratorDecl->getBeginLoc());
5405 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5406 UpdateRes.get());
5407 if (!UpdateRes.isUsable()) {
5408 IsCorrect = false;
5409 continue;
5410 }
5411 UpdateRes =
5412 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5413 if (!UpdateRes.isUsable()) {
5414 IsCorrect = false;
5415 continue;
5416 }
5417 ExprResult CounterUpdateRes =
5418 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5419 if (!CounterUpdateRes.isUsable()) {
5420 IsCorrect = false;
5421 continue;
5422 }
5423 CounterUpdateRes =
5424 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5425 if (!CounterUpdateRes.isUsable()) {
5426 IsCorrect = false;
5427 continue;
5428 }
5429 OMPIteratorHelperData &HD = Helpers.emplace_back();
5430 HD.CounterVD = CounterVD;
5431 HD.Upper = Res.get();
5432 HD.Update = UpdateRes.get();
5433 HD.CounterUpdate = CounterUpdateRes.get();
5434 }
5435 } else {
5436 Helpers.assign(ID.size(), {});
5437 }
5438 if (!IsCorrect) {
5439 // Invalidate all created iterator declarations if error is found.
5440 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5441 if (Decl *ID = D.IteratorDecl)
5442 ID->setInvalidDecl();
5443 }
5444 return ExprError();
5445 }
5446 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5447 LLoc, RLoc, ID, Helpers);
5448}
5449
5450ExprResult
5451Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5452 Expr *Idx, SourceLocation RLoc) {
5453 Expr *LHSExp = Base;
5454 Expr *RHSExp = Idx;
5455
5456 ExprValueKind VK = VK_LValue;
5457 ExprObjectKind OK = OK_Ordinary;
5458
5459 // Per C++ core issue 1213, the result is an xvalue if either operand is
5460 // a non-lvalue array, and an lvalue otherwise.
5461 if (getLangOpts().CPlusPlus11) {
5462 for (auto *Op : {LHSExp, RHSExp}) {
5463 Op = Op->IgnoreImplicit();
5464 if (Op->getType()->isArrayType() && !Op->isLValue())
5465 VK = VK_XValue;
5466 }
5467 }
5468
5469 // Perform default conversions.
5470 if (!LHSExp->getType()->getAs<VectorType>()) {
5471 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5472 if (Result.isInvalid())
5473 return ExprError();
5474 LHSExp = Result.get();
5475 }
5476 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5477 if (Result.isInvalid())
5478 return ExprError();
5479 RHSExp = Result.get();
5480
5481 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5482
5483 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5484 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5485 // in the subscript position. As a result, we need to derive the array base
5486 // and index from the expression types.
5487 Expr *BaseExpr, *IndexExpr;
5488 QualType ResultType;
5489 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5490 BaseExpr = LHSExp;
5491 IndexExpr = RHSExp;
5492 ResultType = Context.DependentTy;
5493 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5494 BaseExpr = LHSExp;
5495 IndexExpr = RHSExp;
5496 ResultType = PTy->getPointeeType();
5497 } else if (const ObjCObjectPointerType *PTy =
5498 LHSTy->getAs<ObjCObjectPointerType>()) {
5499 BaseExpr = LHSExp;
5500 IndexExpr = RHSExp;
5501
5502 // Use custom logic if this should be the pseudo-object subscript
5503 // expression.
5504 if (!LangOpts.isSubscriptPointerArithmetic())
5505 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5506 nullptr);
5507
5508 ResultType = PTy->getPointeeType();
5509 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5510 // Handle the uncommon case of "123[Ptr]".
5511 BaseExpr = RHSExp;
5512 IndexExpr = LHSExp;
5513 ResultType = PTy->getPointeeType();
5514 } else if (const ObjCObjectPointerType *PTy =
5515 RHSTy->getAs<ObjCObjectPointerType>()) {
5516 // Handle the uncommon case of "123[Ptr]".
5517 BaseExpr = RHSExp;
5518 IndexExpr = LHSExp;
5519 ResultType = PTy->getPointeeType();
5520 if (!LangOpts.isSubscriptPointerArithmetic()) {
5521 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5522 << ResultType << BaseExpr->getSourceRange();
5523 return ExprError();
5524 }
5525 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5526 BaseExpr = LHSExp; // vectors: V[123]
5527 IndexExpr = RHSExp;
5528 // We apply C++ DR1213 to vector subscripting too.
5529 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5530 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5531 if (Materialized.isInvalid())
5532 return ExprError();
5533 LHSExp = Materialized.get();
5534 }
5535 VK = LHSExp->getValueKind();
5536 if (VK != VK_PRValue)
5537 OK = OK_VectorComponent;
5538
5539 ResultType = VTy->getElementType();
5540 QualType BaseType = BaseExpr->getType();
5541 Qualifiers BaseQuals = BaseType.getQualifiers();
5542 Qualifiers MemberQuals = ResultType.getQualifiers();
5543 Qualifiers Combined = BaseQuals + MemberQuals;
5544 if (Combined != MemberQuals)
5545 ResultType = Context.getQualifiedType(ResultType, Combined);
5546 } else if (LHSTy->isArrayType()) {
5547 // If we see an array that wasn't promoted by
5548 // DefaultFunctionArrayLvalueConversion, it must be an array that
5549 // wasn't promoted because of the C90 rule that doesn't
5550 // allow promoting non-lvalue arrays. Warn, then
5551 // force the promotion here.
5552 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5553 << LHSExp->getSourceRange();
5554 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5555 CK_ArrayToPointerDecay).get();
5556 LHSTy = LHSExp->getType();
5557
5558 BaseExpr = LHSExp;
5559 IndexExpr = RHSExp;
5560 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5561 } else if (RHSTy->isArrayType()) {
5562 // Same as previous, except for 123[f().a] case
5563 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5564 << RHSExp->getSourceRange();
5565 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5566 CK_ArrayToPointerDecay).get();
5567 RHSTy = RHSExp->getType();
5568
5569 BaseExpr = RHSExp;
5570 IndexExpr = LHSExp;
5571 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5572 } else {
5573 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5574 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5575 }
5576 // C99 6.5.2.1p1
5577 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5578 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5579 << IndexExpr->getSourceRange());
5580
5581 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5582 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5583 && !IndexExpr->isTypeDependent())
5584 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5585
5586 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5587 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5588 // type. Note that Functions are not objects, and that (in C99 parlance)
5589 // incomplete types are not object types.
5590 if (ResultType->isFunctionType()) {
5591 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5592 << ResultType << BaseExpr->getSourceRange();
5593 return ExprError();
5594 }
5595
5596 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5597 // GNU extension: subscripting on pointer to void
5598 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5599 << BaseExpr->getSourceRange();
5600
5601 // C forbids expressions of unqualified void type from being l-values.
5602 // See IsCForbiddenLValueType.
5603 if (!ResultType.hasQualifiers())
5604 VK = VK_PRValue;
5605 } else if (!ResultType->isDependentType() &&
5606 RequireCompleteSizedType(
5607 LLoc, ResultType,
5608 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5609 return ExprError();
5610
5611 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||(static_cast <bool> (VK == VK_PRValue || LangOpts.CPlusPlus
|| !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail
("VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 5612, __extension__ __PRETTY_FUNCTION__))
5612 !ResultType.isCForbiddenLValueType())(static_cast <bool> (VK == VK_PRValue || LangOpts.CPlusPlus
|| !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail
("VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 5612, __extension__ __PRETTY_FUNCTION__))
;
5613
5614 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5615 FunctionScopes.size() > 1) {
5616 if (auto *TT =
5617 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5618 for (auto I = FunctionScopes.rbegin(),
5619 E = std::prev(FunctionScopes.rend());
5620 I != E; ++I) {
5621 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5622 if (CSI == nullptr)
5623 break;
5624 DeclContext *DC = nullptr;
5625 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5626 DC = LSI->CallOperator;
5627 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5628 DC = CRSI->TheCapturedDecl;
5629 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5630 DC = BSI->TheDecl;
5631 if (DC) {
5632 if (DC->containsDecl(TT->getDecl()))
5633 break;
5634 captureVariablyModifiedType(
5635 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5636 }
5637 }
5638 }
5639 }
5640
5641 return new (Context)
5642 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5643}
5644
5645bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5646 ParmVarDecl *Param) {
5647 if (Param->hasUnparsedDefaultArg()) {
5648 // If we've already cleared out the location for the default argument,
5649 // that means we're parsing it right now.
5650 if (!UnparsedDefaultArgLocs.count(Param)) {
5651 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5652 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5653 Param->setInvalidDecl();
5654 return true;
5655 }
5656
5657 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5658 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5659 Diag(UnparsedDefaultArgLocs[Param],
5660 diag::note_default_argument_declared_here);
5661 return true;
5662 }
5663
5664 if (Param->hasUninstantiatedDefaultArg() &&
5665 InstantiateDefaultArgument(CallLoc, FD, Param))
5666 return true;
5667
5668 assert(Param->hasInit() && "default argument but no initializer?")(static_cast <bool> (Param->hasInit() && "default argument but no initializer?"
) ? void (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 5668, __extension__ __PRETTY_FUNCTION__))
;
5669
5670 // If the default expression creates temporaries, we need to
5671 // push them to the current stack of expression temporaries so they'll
5672 // be properly destroyed.
5673 // FIXME: We should really be rebuilding the default argument with new
5674 // bound temporaries; see the comment in PR5810.
5675 // We don't need to do that with block decls, though, because
5676 // blocks in default argument expression can never capture anything.
5677 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5678 // Set the "needs cleanups" bit regardless of whether there are
5679 // any explicit objects.
5680 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5681
5682 // Append all the objects to the cleanup list. Right now, this
5683 // should always be a no-op, because blocks in default argument
5684 // expressions should never be able to capture anything.
5685 assert(!Init->getNumObjects() &&(static_cast <bool> (!Init->getNumObjects() &&
"default argument expression has capturing blocks?") ? void (
0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 5686, __extension__ __PRETTY_FUNCTION__))
5686 "default argument expression has capturing blocks?")(static_cast <bool> (!Init->getNumObjects() &&
"default argument expression has capturing blocks?") ? void (
0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 5686, __extension__ __PRETTY_FUNCTION__))
;
5687 }
5688
5689 // We already type-checked the argument, so we know it works.
5690 // Just mark all of the declarations in this potentially-evaluated expression
5691 // as being "referenced".
5692 EnterExpressionEvaluationContext EvalContext(
5693 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5694 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5695 /*SkipLocalVariables=*/true);
5696 return false;
5697}
5698
5699ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5700 FunctionDecl *FD, ParmVarDecl *Param) {
5701 assert(Param->hasDefaultArg() && "can't build nonexistent default arg")(static_cast <bool> (Param->hasDefaultArg() &&
"can't build nonexistent default arg") ? void (0) : __assert_fail
("Param->hasDefaultArg() && \"can't build nonexistent default arg\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 5701, __extension__ __PRETTY_FUNCTION__))
;
5702 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5703 return ExprError();
5704 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5705}
5706
5707Sema::VariadicCallType
5708Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5709 Expr *Fn) {
5710 if (Proto && Proto->isVariadic()) {
5711 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5712 return VariadicConstructor;
5713 else if (Fn && Fn->getType()->isBlockPointerType())
5714 return VariadicBlock;
5715 else if (FDecl) {
5716 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5717 if (Method->isInstance())
5718 return VariadicMethod;
5719 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5720 return VariadicMethod;
5721 return VariadicFunction;
5722 }
5723 return VariadicDoesNotApply;
5724}
5725
5726namespace {
5727class FunctionCallCCC final : public FunctionCallFilterCCC {
5728public:
5729 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5730 unsigned NumArgs, MemberExpr *ME)
5731 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5732 FunctionName(FuncName) {}
5733
5734 bool ValidateCandidate(const TypoCorrection &candidate) override {
5735 if (!candidate.getCorrectionSpecifier() ||
5736 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5737 return false;
5738 }
5739
5740 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5741 }
5742
5743 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5744 return std::make_unique<FunctionCallCCC>(*this);
5745 }
5746
5747private:
5748 const IdentifierInfo *const FunctionName;
5749};
5750}
5751
5752static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5753 FunctionDecl *FDecl,
5754 ArrayRef<Expr *> Args) {
5755 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5756 DeclarationName FuncName = FDecl->getDeclName();
5757 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5758
5759 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5760 if (TypoCorrection Corrected = S.CorrectTypo(
5761 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5762 S.getScopeForContext(S.CurContext), nullptr, CCC,
5763 Sema::CTK_ErrorRecovery)) {
5764 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5765 if (Corrected.isOverloaded()) {
5766 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5767 OverloadCandidateSet::iterator Best;
5768 for (NamedDecl *CD : Corrected) {
5769 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5770 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5771 OCS);
5772 }
5773 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5774 case OR_Success:
5775 ND = Best->FoundDecl;
5776 Corrected.setCorrectionDecl(ND);
5777 break;
5778 default:
5779 break;
5780 }
5781 }
5782 ND = ND->getUnderlyingDecl();
5783 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5784 return Corrected;
5785 }
5786 }
5787 return TypoCorrection();
5788}
5789
5790/// ConvertArgumentsForCall - Converts the arguments specified in
5791/// Args/NumArgs to the parameter types of the function FDecl with
5792/// function prototype Proto. Call is the call expression itself, and
5793/// Fn is the function expression. For a C++ member function, this
5794/// routine does not attempt to convert the object argument. Returns
5795/// true if the call is ill-formed.
5796bool
5797Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5798 FunctionDecl *FDecl,
5799 const FunctionProtoType *Proto,
5800 ArrayRef<Expr *> Args,
5801 SourceLocation RParenLoc,
5802 bool IsExecConfig) {
5803 // Bail out early if calling a builtin with custom typechecking.
5804 if (FDecl)
5805 if (unsigned ID = FDecl->getBuiltinID())
5806 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5807 return false;
5808
5809 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5810 // assignment, to the types of the corresponding parameter, ...
5811 unsigned NumParams = Proto->getNumParams();
5812 bool Invalid = false;
5813 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5814 unsigned FnKind = Fn->getType()->isBlockPointerType()
5815 ? 1 /* block */
5816 : (IsExecConfig ? 3 /* kernel function (exec config) */
5817 : 0 /* function */);
5818
5819 // If too few arguments are available (and we don't have default
5820 // arguments for the remaining parameters), don't make the call.
5821 if (Args.size() < NumParams) {
5822 if (Args.size() < MinArgs) {
5823 TypoCorrection TC;
5824 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5825 unsigned diag_id =
5826 MinArgs == NumParams && !Proto->isVariadic()
5827 ? diag::err_typecheck_call_too_few_args_suggest
5828 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5829 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5830 << static_cast<unsigned>(Args.size())
5831 << TC.getCorrectionRange());
5832 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5833 Diag(RParenLoc,
5834 MinArgs == NumParams && !Proto->isVariadic()
5835 ? diag::err_typecheck_call_too_few_args_one
5836 : diag::err_typecheck_call_too_few_args_at_least_one)
5837 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5838 else
5839 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5840 ? diag::err_typecheck_call_too_few_args
5841 : diag::err_typecheck_call_too_few_args_at_least)
5842 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5843 << Fn->getSourceRange();
5844
5845 // Emit the location of the prototype.
5846 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5847 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5848
5849 return true;
5850 }
5851 // We reserve space for the default arguments when we create
5852 // the call expression, before calling ConvertArgumentsForCall.
5853 assert((Call->getNumArgs() == NumParams) &&(static_cast <bool> ((Call->getNumArgs() == NumParams
) && "We should have reserved space for the default arguments before!"
) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 5854, __extension__ __PRETTY_FUNCTION__))
5854 "We should have reserved space for the default arguments before!")(static_cast <bool> ((Call->getNumArgs() == NumParams
) && "We should have reserved space for the default arguments before!"
) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaExpr.cpp"
, 5854, __extension__ __PRETTY_FUNCTION__))
;
5855 }
5856
5857 // If too many are passed and not variadic, error on the extras and drop
5858 // them.
5859 if (Args.size() > NumParams) {
5860 if (!Proto->isVariadic()) {
5861 TypoCorrection TC;
5862 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5863 unsigned diag_id =
5864 MinArgs == NumParams && !Proto->isVariadic()
5865 ? diag::err_typecheck_call_too_many_args_suggest
5866 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5867 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5868 << static_cast<unsigned>(Args.size())
5869 << TC.getCorrectionRange());
5870 } else if (NumParams == 1 && FDecl &&
5871 FDecl->getParamDecl(0)->getDeclName())
5872 Diag(Args[NumParams]->getBeginLoc(),
5873 MinArgs == NumParams
5874 ? diag::err_typecheck_call_too_many_args_one
5875 : diag::err_typecheck_call_too_many_args_at_most_one)
5876 << FnKind << FDecl->getParamDecl(0)
5877 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5878 << SourceRange(Args[NumParams]->getBeginLoc(),
5879 Args.back()->getEndLoc());
5880 else
5881 Diag(Args[NumParams]->getBeginLoc(),
5882 MinArgs == NumParams
5883 ? diag::err_typecheck_call_too_many_args
5884 : diag::err_typecheck_call_too_many_args_at_most)
5885 << FnKind << NumParams << static_cast<unsigned>(Args.size())
5886 << Fn->getSourceRange()
5887 << SourceRange(Args[NumParams]->getBeginLoc(),
5888 Args.back()->getEndLoc());
5889
5890 // Emit the location of the prototype.
5891 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5892 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5893
5894 // This deletes the extra arguments.
5895 Call->shrinkNumArgs(NumParams);
5896 return true;
5897 }
5898 }
5899 SmallVector<Expr *, 8> AllArgs;
5900 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5901
5902 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5903 AllArgs, CallType);
5904 if (Invalid)
5905 return true;
5906 unsigned TotalNumArgs = AllArgs.size();
5907 for (unsigned i = 0; i < TotalNumArgs; ++i)
5908 Call->setArg(i, AllArgs[i]);
5909
5910 Call->computeDependence();
5911 return false;
5912}
5913
5914bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5915 const FunctionProtoType *Proto,
5916 unsigned FirstParam, ArrayRef<Expr *> Args,
5917 SmallVectorImpl<Expr *> &AllArgs,
5918 VariadicCallType CallType, bool AllowExplicit,
5919 bool IsListInitialization) {
5920 unsigned NumParams = Proto->getNumParams();
5921 bool Invalid = false;
5922 size_t ArgIx = 0;
5923 // Continue to check argument types (even if