Bug Summary

File:build/source/clang/lib/Sema/SemaExpr.cpp
Warning:line 9706, column 29
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaExpr.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1670191760 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-12-05-012027-15999-1 -x c++ /build/source/clang/lib/Sema/SemaExpr.cpp

/build/source/clang/lib/Sema/SemaExpr.cpp

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