Bug Summary

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