Bug Summary

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