Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaExpr.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -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-14~++20220116100644+5f782d25a742/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.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-14~++20220116100644+5f782d25a742/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/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-14/lib/clang/14.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-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -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-01-16-232930-107970-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/lib/Sema/SemaExpr.cpp

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