Bug Summary

File:src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaExpr.cpp
Warning:line 8160, column 26
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaExpr.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSema/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libclangSema/obj/../include/clang/Sema -I /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/include -I /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libclangSema/../include -I /usr/src/gnu/usr.bin/clang/libclangSema/obj -I /usr/src/gnu/usr.bin/clang/libclangSema/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSema/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaExpr.cpp

/usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaExpr.cpp

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