Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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