Bug Summary

File:clang/lib/Sema/SemaExpr.cpp
Warning:line 7343, column 38
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 -fhalf-no-semantic-interposition -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~++20210506100649+6304c0836a4d/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~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/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~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d=. -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-05-07-005843-9350-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Sema/SemaExpr.cpp

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