Bug Summary

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