Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaExpr.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/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())(static_cast<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")(static_cast<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")(static_cast<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?")(static_cast<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")(static_cast<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")(static_cast<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() &&(static_cast<void> (0))
850 "Unexpected typesize for LongLongTy")(static_cast<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())(static_cast<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())(static_cast<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")(static_cast<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)(static_cast<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() &&(static_cast<void> (0))
1213 "The remaining types must be floating point types.")(static_cast<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)(static_cast<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.")(static_cast<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()) &&(static_cast<void> (0))
1405 "Expected at least one of the operands to be a fixed point type")(static_cast<void> (0));
1406 assert((LHSTy->isFixedPointOrIntegerType() ||(static_cast<void> (0))
1407 RHSTy->isFixedPointOrIntegerType()) &&(static_cast<void> (0))
1408 "Special fixed point arithmetic operation conversions are only "(static_cast<void> (0))
1409 "applied to ints or other fixed point types")(static_cast<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())(static_cast<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())(static_cast<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")(static_cast<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!")(static_cast<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())(static_cast<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 &&(static_cast<void> (0))
2269 "Diagnosing an empty lookup with explicit template args!")(static_cast<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) &&(static_cast<void> (0))
2434 "cannot be direct & operand and have a trailing lparen")(static_cast<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) &&(static_cast<void> (0))
2559 "Typo correction callback misconfigured")(static_cast<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() &&(static_cast<void> (0))
2595 "DiagnoseEmptyLookup returned false but added no results")(static_cast<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)(static_cast<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>() &&(static_cast<void> (0))
2666 "There should only be one declaration found.")(static_cast<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() &&(static_cast<void> (0))
2843 "should not reference ivar from this context")(static_cast<void> (0));
2844
2845 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2846 assert(IFace && "should not reference ivar from this context")(static_cast<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")(static_cast<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")(static_cast<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")(static_cast<void> (0));
3206 assert(!isa<FunctionTemplateDecl>(D) &&(static_cast<void> (0))
3207 "Cannot refer unambiguously to a function template")(static_cast<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) << D << SS.getRange();
3223 Diag(D->getLocation(), diag::note_declared_at);
3224 return ExprError();
3225 }
3226
3227 // Check whether this declaration can be used. Note that we suppress
3228 // this check when we're going to perform argument-dependent lookup
3229 // on this function name, because this might not be the function
3230 // that overload resolution actually selects.
3231 if (DiagnoseUseOfDecl(D, Loc))
3232 return ExprError();
3233
3234 auto *VD = cast<ValueDecl>(D);
3235
3236 // Only create DeclRefExpr's for valid Decl's.
3237 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3238 return ExprError();
3239
3240 // Handle members of anonymous structs and unions. If we got here,
3241 // and the reference is to a class member indirect field, then this
3242 // must be the subject of a pointer-to-member expression.
3243 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3244 if (!indirectField->isCXXClassMember())
3245 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3246 indirectField);
3247
3248 QualType type = VD->getType();
3249 if (type.isNull())
3250 return ExprError();
3251 ExprValueKind valueKind = VK_PRValue;
3252
3253 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3254 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3255 // is expanded by some outer '...' in the context of the use.
3256 type = type.getNonPackExpansionType();
3257
3258 switch (D->getKind()) {
3259 // Ignore all the non-ValueDecl kinds.
3260#define ABSTRACT_DECL(kind)
3261#define VALUE(type, base)
3262#define DECL(type, base) case Decl::type:
3263#include "clang/AST/DeclNodes.inc"
3264 llvm_unreachable("invalid value decl kind")__builtin_unreachable();
3265
3266 // These shouldn't make it here.
3267 case Decl::ObjCAtDefsField:
3268 llvm_unreachable("forming non-member reference to ivar?")__builtin_unreachable();
3269
3270 // Enum constants are always r-values and never references.
3271 // Unresolved using declarations are dependent.
3272 case Decl::EnumConstant:
3273 case Decl::UnresolvedUsingValue:
3274 case Decl::OMPDeclareReduction:
3275 case Decl::OMPDeclareMapper:
3276 valueKind = VK_PRValue;
3277 break;
3278
3279 // Fields and indirect fields that got here must be for
3280 // pointer-to-member expressions; we just call them l-values for
3281 // internal consistency, because this subexpression doesn't really
3282 // exist in the high-level semantics.
3283 case Decl::Field:
3284 case Decl::IndirectField:
3285 case Decl::ObjCIvar:
3286 assert(getLangOpts().CPlusPlus && "building reference to field in C?")(static_cast<void> (0));
3287
3288 // These can't have reference type in well-formed programs, but
3289 // for internal consistency we do this anyway.
3290 type = type.getNonReferenceType();
3291 valueKind = VK_LValue;
3292 break;
3293
3294 // Non-type template parameters are either l-values or r-values
3295 // depending on the type.
3296 case Decl::NonTypeTemplateParm: {
3297 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3298 type = reftype->getPointeeType();
3299 valueKind = VK_LValue; // even if the parameter is an r-value reference
3300 break;
3301 }
3302
3303 // [expr.prim.id.unqual]p2:
3304 // If the entity is a template parameter object for a template
3305 // parameter of type T, the type of the expression is const T.
3306 // [...] The expression is an lvalue if the entity is a [...] template
3307 // parameter object.
3308 if (type->isRecordType()) {
3309 type = type.getUnqualifiedType().withConst();
3310 valueKind = VK_LValue;
3311 break;
3312 }
3313
3314 // For non-references, we need to strip qualifiers just in case
3315 // the template parameter was declared as 'const int' or whatever.
3316 valueKind = VK_PRValue;
3317 type = type.getUnqualifiedType();
3318 break;
3319 }
3320
3321 case Decl::Var:
3322 case Decl::VarTemplateSpecialization:
3323 case Decl::VarTemplatePartialSpecialization:
3324 case Decl::Decomposition:
3325 case Decl::OMPCapturedExpr:
3326 // In C, "extern void blah;" is valid and is an r-value.
3327 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3328 type->isVoidType()) {
3329 valueKind = VK_PRValue;
3330 break;
3331 }
3332 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3333
3334 case Decl::ImplicitParam:
3335 case Decl::ParmVar: {
3336 // These are always l-values.
3337 valueKind = VK_LValue;
3338 type = type.getNonReferenceType();
3339
3340 // FIXME: Does the addition of const really only apply in
3341 // potentially-evaluated contexts? Since the variable isn't actually
3342 // captured in an unevaluated context, it seems that the answer is no.
3343 if (!isUnevaluatedContext()) {
3344 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3345 if (!CapturedType.isNull())
3346 type = CapturedType;
3347 }
3348
3349 break;
3350 }
3351
3352 case Decl::Binding: {
3353 // These are always lvalues.
3354 valueKind = VK_LValue;
3355 type = type.getNonReferenceType();
3356 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3357 // decides how that's supposed to work.
3358 auto *BD = cast<BindingDecl>(VD);
3359 if (BD->getDeclContext() != CurContext) {
3360 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3361 if (DD && DD->hasLocalStorage())
3362 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3363 }
3364 break;
3365 }
3366
3367 case Decl::Function: {
3368 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3369 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3370 type = Context.BuiltinFnTy;
3371 valueKind = VK_PRValue;
3372 break;
3373 }
3374 }
3375
3376 const FunctionType *fty = type->castAs<FunctionType>();
3377
3378 // If we're referring to a function with an __unknown_anytype
3379 // result type, make the entire expression __unknown_anytype.
3380 if (fty->getReturnType() == Context.UnknownAnyTy) {
3381 type = Context.UnknownAnyTy;
3382 valueKind = VK_PRValue;
3383 break;
3384 }
3385
3386 // Functions are l-values in C++.
3387 if (getLangOpts().CPlusPlus) {
3388 valueKind = VK_LValue;
3389 break;
3390 }
3391
3392 // C99 DR 316 says that, if a function type comes from a
3393 // function definition (without a prototype), that type is only
3394 // used for checking compatibility. Therefore, when referencing
3395 // the function, we pretend that we don't have the full function
3396 // type.
3397 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3398 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3399 fty->getExtInfo());
3400
3401 // Functions are r-values in C.
3402 valueKind = VK_PRValue;
3403 break;
3404 }
3405
3406 case Decl::CXXDeductionGuide:
3407 llvm_unreachable("building reference to deduction guide")__builtin_unreachable();
3408
3409 case Decl::MSProperty:
3410 case Decl::MSGuid:
3411 case Decl::TemplateParamObject:
3412 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3413 // capture in OpenMP, or duplicated between host and device?
3414 valueKind = VK_LValue;
3415 break;
3416
3417 case Decl::CXXMethod:
3418 // If we're referring to a method with an __unknown_anytype
3419 // result type, make the entire expression __unknown_anytype.
3420 // This should only be possible with a type written directly.
3421 if (const FunctionProtoType *proto =
3422 dyn_cast<FunctionProtoType>(VD->getType()))
3423 if (proto->getReturnType() == Context.UnknownAnyTy) {
3424 type = Context.UnknownAnyTy;
3425 valueKind = VK_PRValue;
3426 break;
3427 }
3428
3429 // C++ methods are l-values if static, r-values if non-static.
3430 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3431 valueKind = VK_LValue;
3432 break;
3433 }
3434 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3435
3436 case Decl::CXXConversion:
3437 case Decl::CXXDestructor:
3438 case Decl::CXXConstructor:
3439 valueKind = VK_PRValue;
3440 break;
3441 }
3442
3443 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3444 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3445 TemplateArgs);
3446}
3447
3448static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3449 SmallString<32> &Target) {
3450 Target.resize(CharByteWidth * (Source.size() + 1));
3451 char *ResultPtr = &Target[0];
3452 const llvm::UTF8 *ErrorPtr;
3453 bool success =
3454 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3455 (void)success;
3456 assert(success)(static_cast<void> (0));
3457 Target.resize(ResultPtr - &Target[0]);
3458}
3459
3460ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3461 PredefinedExpr::IdentKind IK) {
3462 // Pick the current block, lambda, captured statement or function.
3463 Decl *currentDecl = nullptr;
3464 if (const BlockScopeInfo *BSI = getCurBlock())
3465 currentDecl = BSI->TheDecl;
3466 else if (const LambdaScopeInfo *LSI = getCurLambda())
3467 currentDecl = LSI->CallOperator;
3468 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3469 currentDecl = CSI->TheCapturedDecl;
3470 else
3471 currentDecl = getCurFunctionOrMethodDecl();
3472
3473 if (!currentDecl) {
3474 Diag(Loc, diag::ext_predef_outside_function);
3475 currentDecl = Context.getTranslationUnitDecl();
3476 }
3477
3478 QualType ResTy;
3479 StringLiteral *SL = nullptr;
3480 if (cast<DeclContext>(currentDecl)->isDependentContext())
3481 ResTy = Context.DependentTy;
3482 else {
3483 // Pre-defined identifiers are of type char[x], where x is the length of
3484 // the string.
3485 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3486 unsigned Length = Str.length();
3487
3488 llvm::APInt LengthI(32, Length + 1);
3489 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3490 ResTy =
3491 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3492 SmallString<32> RawChars;
3493 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3494 Str, RawChars);
3495 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3496 ArrayType::Normal,
3497 /*IndexTypeQuals*/ 0);
3498 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3499 /*Pascal*/ false, ResTy, Loc);
3500 } else {
3501 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3502 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3503 ArrayType::Normal,
3504 /*IndexTypeQuals*/ 0);
3505 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3506 /*Pascal*/ false, ResTy, Loc);
3507 }
3508 }
3509
3510 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3511}
3512
3513ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3514 SourceLocation LParen,
3515 SourceLocation RParen,
3516 TypeSourceInfo *TSI) {
3517 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3518}
3519
3520ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3521 SourceLocation LParen,
3522 SourceLocation RParen,
3523 ParsedType ParsedTy) {
3524 TypeSourceInfo *TSI = nullptr;
3525 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3526
3527 if (Ty.isNull())
3528 return ExprError();
3529 if (!TSI)
3530 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3531
3532 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3533}
3534
3535ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3536 PredefinedExpr::IdentKind IK;
3537
3538 switch (Kind) {
3539 default: llvm_unreachable("Unknown simple primary expr!")__builtin_unreachable();
3540 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3541 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3542 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3543 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3544 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3545 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3546 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3547 }
3548
3549 return BuildPredefinedExpr(Loc, IK);
3550}
3551
3552ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3553 SmallString<16> CharBuffer;
3554 bool Invalid = false;
3555 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3556 if (Invalid)
3557 return ExprError();
3558
3559 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3560 PP, Tok.getKind());
3561 if (Literal.hadError())
3562 return ExprError();
3563
3564 QualType Ty;
3565 if (Literal.isWide())
3566 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3567 else if (Literal.isUTF8() && getLangOpts().Char8)
3568 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3569 else if (Literal.isUTF16())
3570 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3571 else if (Literal.isUTF32())
3572 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3573 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3574 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3575 else
3576 Ty = Context.CharTy; // 'x' -> char in C++
3577
3578 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3579 if (Literal.isWide())
3580 Kind = CharacterLiteral::Wide;
3581 else if (Literal.isUTF16())
3582 Kind = CharacterLiteral::UTF16;
3583 else if (Literal.isUTF32())
3584 Kind = CharacterLiteral::UTF32;
3585 else if (Literal.isUTF8())
3586 Kind = CharacterLiteral::UTF8;
3587
3588 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3589 Tok.getLocation());
3590
3591 if (Literal.getUDSuffix().empty())
3592 return Lit;
3593
3594 // We're building a user-defined literal.
3595 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3596 SourceLocation UDSuffixLoc =
3597 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3598
3599 // Make sure we're allowed user-defined literals here.
3600 if (!UDLScope)
3601 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3602
3603 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3604 // operator "" X (ch)
3605 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3606 Lit, Tok.getLocation());
3607}
3608
3609ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3610 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3611 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3612 Context.IntTy, Loc);
3613}
3614
3615static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3616 QualType Ty, SourceLocation Loc) {
3617 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3618
3619 using llvm::APFloat;
3620 APFloat Val(Format);
3621
3622 APFloat::opStatus result = Literal.GetFloatValue(Val);
3623
3624 // Overflow is always an error, but underflow is only an error if
3625 // we underflowed to zero (APFloat reports denormals as underflow).
3626 if ((result & APFloat::opOverflow) ||
3627 ((result & APFloat::opUnderflow) && Val.isZero())) {
3628 unsigned diagnostic;
3629 SmallString<20> buffer;
3630 if (result & APFloat::opOverflow) {
3631 diagnostic = diag::warn_float_overflow;
3632 APFloat::getLargest(Format).toString(buffer);
3633 } else {
3634 diagnostic = diag::warn_float_underflow;
3635 APFloat::getSmallest(Format).toString(buffer);
3636 }
3637
3638 S.Diag(Loc, diagnostic)
3639 << Ty
3640 << StringRef(buffer.data(), buffer.size());
3641 }
3642
3643 bool isExact = (result == APFloat::opOK);
3644 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3645}
3646
3647bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3648 assert(E && "Invalid expression")(static_cast<void> (0));
3649
3650 if (E->isValueDependent())
3651 return false;
3652
3653 QualType QT = E->getType();
3654 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3655 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3656 return true;
3657 }
3658
3659 llvm::APSInt ValueAPS;
3660 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3661
3662 if (R.isInvalid())
3663 return true;
3664
3665 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3666 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3667 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3668 << toString(ValueAPS, 10) << ValueIsPositive;
3669 return true;
3670 }
3671
3672 return false;
3673}
3674
3675ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3676 // Fast path for a single digit (which is quite common). A single digit
3677 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3678 if (Tok.getLength() == 1) {
3679 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3680 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3681 }
3682
3683 SmallString<128> SpellingBuffer;
3684 // NumericLiteralParser wants to overread by one character. Add padding to
3685 // the buffer in case the token is copied to the buffer. If getSpelling()
3686 // returns a StringRef to the memory buffer, it should have a null char at
3687 // the EOF, so it is also safe.
3688 SpellingBuffer.resize(Tok.getLength() + 1);
3689
3690 // Get the spelling of the token, which eliminates trigraphs, etc.
3691 bool Invalid = false;
3692 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3693 if (Invalid)
3694 return ExprError();
3695
3696 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3697 PP.getSourceManager(), PP.getLangOpts(),
3698 PP.getTargetInfo(), PP.getDiagnostics());
3699 if (Literal.hadError)
3700 return ExprError();
3701
3702 if (Literal.hasUDSuffix()) {
3703 // We're building a user-defined literal.
3704 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3705 SourceLocation UDSuffixLoc =
3706 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3707
3708 // Make sure we're allowed user-defined literals here.
3709 if (!UDLScope)
3710 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3711
3712 QualType CookedTy;
3713 if (Literal.isFloatingLiteral()) {
3714 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3715 // long double, the literal is treated as a call of the form
3716 // operator "" X (f L)
3717 CookedTy = Context.LongDoubleTy;
3718 } else {
3719 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3720 // unsigned long long, the literal is treated as a call of the form
3721 // operator "" X (n ULL)
3722 CookedTy = Context.UnsignedLongLongTy;
3723 }
3724
3725 DeclarationName OpName =
3726 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3727 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3728 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3729
3730 SourceLocation TokLoc = Tok.getLocation();
3731
3732 // Perform literal operator lookup to determine if we're building a raw
3733 // literal or a cooked one.
3734 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3735 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3736 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3737 /*AllowStringTemplatePack*/ false,
3738 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3739 case LOLR_ErrorNoDiagnostic:
3740 // Lookup failure for imaginary constants isn't fatal, there's still the
3741 // GNU extension producing _Complex types.
3742 break;
3743 case LOLR_Error:
3744 return ExprError();
3745 case LOLR_Cooked: {
3746 Expr *Lit;
3747 if (Literal.isFloatingLiteral()) {
3748 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3749 } else {
3750 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3751 if (Literal.GetIntegerValue(ResultVal))
3752 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3753 << /* Unsigned */ 1;
3754 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3755 Tok.getLocation());
3756 }
3757 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3758 }
3759
3760 case LOLR_Raw: {
3761 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3762 // literal is treated as a call of the form
3763 // operator "" X ("n")
3764 unsigned Length = Literal.getUDSuffixOffset();
3765 QualType StrTy = Context.getConstantArrayType(
3766 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3767 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3768 Expr *Lit = StringLiteral::Create(
3769 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3770 /*Pascal*/false, StrTy, &TokLoc, 1);
3771 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3772 }
3773
3774 case LOLR_Template: {
3775 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3776 // template), L is treated as a call fo the form
3777 // operator "" X <'c1', 'c2', ... 'ck'>()
3778 // where n is the source character sequence c1 c2 ... ck.
3779 TemplateArgumentListInfo ExplicitArgs;
3780 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3781 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3782 llvm::APSInt Value(CharBits, CharIsUnsigned);
3783 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3784 Value = TokSpelling[I];
3785 TemplateArgument Arg(Context, Value, Context.CharTy);
3786 TemplateArgumentLocInfo ArgInfo;
3787 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3788 }
3789 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3790 &ExplicitArgs);
3791 }
3792 case LOLR_StringTemplatePack:
3793 llvm_unreachable("unexpected literal operator lookup result")__builtin_unreachable();
3794 }
3795 }
3796
3797 Expr *Res;
3798
3799 if (Literal.isFixedPointLiteral()) {
3800 QualType Ty;
3801
3802 if (Literal.isAccum) {
3803 if (Literal.isHalf) {
3804 Ty = Context.ShortAccumTy;
3805 } else if (Literal.isLong) {
3806 Ty = Context.LongAccumTy;
3807 } else {
3808 Ty = Context.AccumTy;
3809 }
3810 } else if (Literal.isFract) {
3811 if (Literal.isHalf) {
3812 Ty = Context.ShortFractTy;
3813 } else if (Literal.isLong) {
3814 Ty = Context.LongFractTy;
3815 } else {
3816 Ty = Context.FractTy;
3817 }
3818 }
3819
3820 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3821
3822 bool isSigned = !Literal.isUnsigned;
3823 unsigned scale = Context.getFixedPointScale(Ty);
3824 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3825
3826 llvm::APInt Val(bit_width, 0, isSigned);
3827 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3828 bool ValIsZero = Val.isNullValue() && !Overflowed;
3829
3830 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3831 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3832 // Clause 6.4.4 - The value of a constant shall be in the range of
3833 // representable values for its type, with exception for constants of a
3834 // fract type with a value of exactly 1; such a constant shall denote
3835 // the maximal value for the type.
3836 --Val;
3837 else if (Val.ugt(MaxVal) || Overflowed)
3838 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3839
3840 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3841 Tok.getLocation(), scale);
3842 } else if (Literal.isFloatingLiteral()) {
3843 QualType Ty;
3844 if (Literal.isHalf){
3845 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3846 Ty = Context.HalfTy;
3847 else {
3848 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3849 return ExprError();
3850 }
3851 } else if (Literal.isFloat)
3852 Ty = Context.FloatTy;
3853 else if (Literal.isLong)
3854 Ty = Context.LongDoubleTy;
3855 else if (Literal.isFloat16)
3856 Ty = Context.Float16Ty;
3857 else if (Literal.isFloat128)
3858 Ty = Context.Float128Ty;
3859 else
3860 Ty = Context.DoubleTy;
3861
3862 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3863
3864 if (Ty == Context.DoubleTy) {
3865 if (getLangOpts().SinglePrecisionConstants) {
3866 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3867 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3868 }
3869 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3870 "cl_khr_fp64", getLangOpts())) {
3871 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3872 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3873 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3874 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3875 }
3876 }
3877 } else if (!Literal.isIntegerLiteral()) {
3878 return ExprError();
3879 } else {
3880 QualType Ty;
3881
3882 // 'long long' is a C99 or C++11 feature.
3883 if (!getLangOpts().C99 && Literal.isLongLong) {
3884 if (getLangOpts().CPlusPlus)
3885 Diag(Tok.getLocation(),
3886 getLangOpts().CPlusPlus11 ?
3887 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3888 else
3889 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3890 }
3891
3892 // 'z/uz' literals are a C++2b feature.
3893 if (Literal.isSizeT)
3894 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3895 ? getLangOpts().CPlusPlus2b
3896 ? diag::warn_cxx20_compat_size_t_suffix
3897 : diag::ext_cxx2b_size_t_suffix
3898 : diag::err_cxx2b_size_t_suffix);
3899
3900 // Get the value in the widest-possible width.
3901 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3902 llvm::APInt ResultVal(MaxWidth, 0);
3903
3904 if (Literal.GetIntegerValue(ResultVal)) {
3905 // If this value didn't fit into uintmax_t, error and force to ull.
3906 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3907 << /* Unsigned */ 1;
3908 Ty = Context.UnsignedLongLongTy;
3909 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&(static_cast<void> (0))
3910 "long long is not intmax_t?")(static_cast<void> (0));
3911 } else {
3912 // If this value fits into a ULL, try to figure out what else it fits into
3913 // according to the rules of C99 6.4.4.1p5.
3914
3915 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3916 // be an unsigned int.
3917 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3918
3919 // Check from smallest to largest, picking the smallest type we can.
3920 unsigned Width = 0;
3921
3922 // Microsoft specific integer suffixes are explicitly sized.
3923 if (Literal.MicrosoftInteger) {
3924 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3925 Width = 8;
3926 Ty = Context.CharTy;
3927 } else {
3928 Width = Literal.MicrosoftInteger;
3929 Ty = Context.getIntTypeForBitwidth(Width,
3930 /*Signed=*/!Literal.isUnsigned);
3931 }
3932 }
3933
3934 // Check C++2b size_t literals.
3935 if (Literal.isSizeT) {
3936 assert(!Literal.MicrosoftInteger &&(static_cast<void> (0))
3937 "size_t literals can't be Microsoft literals")(static_cast<void> (0));
3938 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3939 Context.getTargetInfo().getSizeType());
3940
3941 // Does it fit in size_t?
3942 if (ResultVal.isIntN(SizeTSize)) {
3943 // Does it fit in ssize_t?
3944 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3945 Ty = Context.getSignedSizeType();
3946 else if (AllowUnsigned)
3947 Ty = Context.getSizeType();
3948 Width = SizeTSize;
3949 }
3950 }
3951
3952 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3953 !Literal.isSizeT) {
3954 // Are int/unsigned possibilities?
3955 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3956
3957 // Does it fit in a unsigned int?
3958 if (ResultVal.isIntN(IntSize)) {
3959 // Does it fit in a signed int?
3960 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3961 Ty = Context.IntTy;
3962 else if (AllowUnsigned)
3963 Ty = Context.UnsignedIntTy;
3964 Width = IntSize;
3965 }
3966 }
3967
3968 // Are long/unsigned long possibilities?
3969 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
3970 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3971
3972 // Does it fit in a unsigned long?
3973 if (ResultVal.isIntN(LongSize)) {
3974 // Does it fit in a signed long?
3975 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3976 Ty = Context.LongTy;
3977 else if (AllowUnsigned)
3978 Ty = Context.UnsignedLongTy;
3979 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3980 // is compatible.
3981 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3982 const unsigned LongLongSize =
3983 Context.getTargetInfo().getLongLongWidth();
3984 Diag(Tok.getLocation(),
3985 getLangOpts().CPlusPlus
3986 ? Literal.isLong
3987 ? diag::warn_old_implicitly_unsigned_long_cxx
3988 : /*C++98 UB*/ diag::
3989 ext_old_implicitly_unsigned_long_cxx
3990 : diag::warn_old_implicitly_unsigned_long)
3991 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3992 : /*will be ill-formed*/ 1);
3993 Ty = Context.UnsignedLongTy;
3994 }
3995 Width = LongSize;
3996 }
3997 }
3998
3999 // Check long long if needed.
4000 if (Ty.isNull() && !Literal.isSizeT) {
4001 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4002
4003 // Does it fit in a unsigned long long?
4004 if (ResultVal.isIntN(LongLongSize)) {
4005 // Does it fit in a signed long long?
4006 // To be compatible with MSVC, hex integer literals ending with the
4007 // LL or i64 suffix are always signed in Microsoft mode.
4008 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4009 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4010 Ty = Context.LongLongTy;
4011 else if (AllowUnsigned)
4012 Ty = Context.UnsignedLongLongTy;
4013 Width = LongLongSize;
4014 }
4015 }
4016
4017 // If we still couldn't decide a type, we either have 'size_t' literal
4018 // that is out of range, or a decimal literal that does not fit in a
4019 // signed long long and has no U suffix.
4020 if (Ty.isNull()) {
4021 if (Literal.isSizeT)
4022 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4023 << Literal.isUnsigned;
4024 else
4025 Diag(Tok.getLocation(),
4026 diag::ext_integer_literal_too_large_for_signed);
4027 Ty = Context.UnsignedLongLongTy;
4028 Width = Context.getTargetInfo().getLongLongWidth();
4029 }
4030
4031 if (ResultVal.getBitWidth() != Width)
4032 ResultVal = ResultVal.trunc(Width);
4033 }
4034 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4035 }
4036
4037 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4038 if (Literal.isImaginary) {
4039 Res = new (Context) ImaginaryLiteral(Res,
4040 Context.getComplexType(Res->getType()));
4041
4042 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4043 }
4044 return Res;
4045}
4046
4047ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4048 assert(E && "ActOnParenExpr() missing expr")(static_cast<void> (0));
4049 QualType ExprTy = E->getType();
4050 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4051 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4052 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4053 return new (Context) ParenExpr(L, R, E);
4054}
4055
4056static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4057 SourceLocation Loc,
4058 SourceRange ArgRange) {
4059 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4060 // scalar or vector data type argument..."
4061 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4062 // type (C99 6.2.5p18) or void.
4063 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4064 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4065 << T << ArgRange;
4066 return true;
4067 }
4068
4069 assert((T->isVoidType() || !T->isIncompleteType()) &&(static_cast<void> (0))
4070 "Scalar types should always be complete")(static_cast<void> (0));
4071 return false;
4072}
4073
4074static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4075 SourceLocation Loc,
4076 SourceRange ArgRange,
4077 UnaryExprOrTypeTrait TraitKind) {
4078 // Invalid types must be hard errors for SFINAE in C++.
4079 if (S.LangOpts.CPlusPlus)
4080 return true;
4081
4082 // C99 6.5.3.4p1:
4083 if (T->isFunctionType() &&
4084 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4085 TraitKind == UETT_PreferredAlignOf)) {
4086 // sizeof(function)/alignof(function) is allowed as an extension.
4087 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4088 << getTraitSpelling(TraitKind) << ArgRange;
4089 return false;
4090 }
4091
4092 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4093 // this is an error (OpenCL v1.1 s6.3.k)
4094 if (T->isVoidType()) {
4095 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4096 : diag::ext_sizeof_alignof_void_type;
4097 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4098 return false;
4099 }
4100
4101 return true;
4102}
4103
4104static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4105 SourceLocation Loc,
4106 SourceRange ArgRange,
4107 UnaryExprOrTypeTrait TraitKind) {
4108 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4109 // runtime doesn't allow it.
4110 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4111 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4112 << T << (TraitKind == UETT_SizeOf)
4113 << ArgRange;
4114 return true;
4115 }
4116
4117 return false;
4118}
4119
4120/// Check whether E is a pointer from a decayed array type (the decayed
4121/// pointer type is equal to T) and emit a warning if it is.
4122static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4123 Expr *E) {
4124 // Don't warn if the operation changed the type.
4125 if (T != E->getType())
4126 return;
4127
4128 // Now look for array decays.
4129 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4130 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4131 return;
4132
4133 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4134 << ICE->getType()
4135 << ICE->getSubExpr()->getType();
4136}
4137
4138/// Check the constraints on expression operands to unary type expression
4139/// and type traits.
4140///
4141/// Completes any types necessary and validates the constraints on the operand
4142/// expression. The logic mostly mirrors the type-based overload, but may modify
4143/// the expression as it completes the type for that expression through template
4144/// instantiation, etc.
4145bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4146 UnaryExprOrTypeTrait ExprKind) {
4147 QualType ExprTy = E->getType();
4148 assert(!ExprTy->isReferenceType())(static_cast<void> (0));
4149
4150 bool IsUnevaluatedOperand =
4151 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4152 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4153 if (IsUnevaluatedOperand) {
4154 ExprResult Result = CheckUnevaluatedOperand(E);
4155 if (Result.isInvalid())
4156 return true;
4157 E = Result.get();
4158 }
4159
4160 // The operand for sizeof and alignof is in an unevaluated expression context,
4161 // so side effects could result in unintended consequences.
4162 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4163 // used to build SFINAE gadgets.
4164 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4165 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4166 !E->isInstantiationDependent() &&
4167 E->HasSideEffects(Context, false))
4168 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4169
4170 if (ExprKind == UETT_VecStep)
4171 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4172 E->getSourceRange());
4173
4174 // Explicitly list some types as extensions.
4175 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4176 E->getSourceRange(), ExprKind))
4177 return false;
4178
4179 // 'alignof' applied to an expression only requires the base element type of
4180 // the expression to be complete. 'sizeof' requires the expression's type to
4181 // be complete (and will attempt to complete it if it's an array of unknown
4182 // bound).
4183 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4184 if (RequireCompleteSizedType(
4185 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4186 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4187 getTraitSpelling(ExprKind), E->getSourceRange()))
4188 return true;
4189 } else {
4190 if (RequireCompleteSizedExprType(
4191 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4192 getTraitSpelling(ExprKind), E->getSourceRange()))
4193 return true;
4194 }
4195
4196 // Completing the expression's type may have changed it.
4197 ExprTy = E->getType();
4198 assert(!ExprTy->isReferenceType())(static_cast<void> (0));
4199
4200 if (ExprTy->isFunctionType()) {
4201 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4202 << getTraitSpelling(ExprKind) << E->getSourceRange();
4203 return true;
4204 }
4205
4206 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4207 E->getSourceRange(), ExprKind))
4208 return true;
4209
4210 if (ExprKind == UETT_SizeOf) {
4211 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4212 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4213 QualType OType = PVD->getOriginalType();
4214 QualType Type = PVD->getType();
4215 if (Type->isPointerType() && OType->isArrayType()) {
4216 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4217 << Type << OType;
4218 Diag(PVD->getLocation(), diag::note_declared_at);
4219 }
4220 }
4221 }
4222
4223 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4224 // decays into a pointer and returns an unintended result. This is most
4225 // likely a typo for "sizeof(array) op x".
4226 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4227 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4228 BO->getLHS());
4229 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4230 BO->getRHS());
4231 }
4232 }
4233
4234 return false;
4235}
4236
4237/// Check the constraints on operands to unary expression and type
4238/// traits.
4239///
4240/// This will complete any types necessary, and validate the various constraints
4241/// on those operands.
4242///
4243/// The UsualUnaryConversions() function is *not* called by this routine.
4244/// C99 6.3.2.1p[2-4] all state:
4245/// Except when it is the operand of the sizeof operator ...
4246///
4247/// C++ [expr.sizeof]p4
4248/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4249/// standard conversions are not applied to the operand of sizeof.
4250///
4251/// This policy is followed for all of the unary trait expressions.
4252bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4253 SourceLocation OpLoc,
4254 SourceRange ExprRange,
4255 UnaryExprOrTypeTrait ExprKind) {
4256 if (ExprType->isDependentType())
4257 return false;
4258
4259 // C++ [expr.sizeof]p2:
4260 // When applied to a reference or a reference type, the result
4261 // is the size of the referenced type.
4262 // C++11 [expr.alignof]p3:
4263 // When alignof is applied to a reference type, the result
4264 // shall be the alignment of the referenced type.
4265 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4266 ExprType = Ref->getPointeeType();
4267
4268 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4269 // When alignof or _Alignof is applied to an array type, the result
4270 // is the alignment of the element type.
4271 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4272 ExprKind == UETT_OpenMPRequiredSimdAlign)
4273 ExprType = Context.getBaseElementType(ExprType);
4274
4275 if (ExprKind == UETT_VecStep)
4276 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4277
4278 // Explicitly list some types as extensions.
4279 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4280 ExprKind))
4281 return false;
4282
4283 if (RequireCompleteSizedType(
4284 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4285 getTraitSpelling(ExprKind), ExprRange))
4286 return true;
4287
4288 if (ExprType->isFunctionType()) {
4289 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4290 << getTraitSpelling(ExprKind) << ExprRange;
4291 return true;
4292 }
4293
4294 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4295 ExprKind))
4296 return true;
4297
4298 return false;
4299}
4300
4301static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4302 // Cannot know anything else if the expression is dependent.
4303 if (E->isTypeDependent())
4304 return false;
4305
4306 if (E->getObjectKind() == OK_BitField) {
4307 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4308 << 1 << E->getSourceRange();
4309 return true;
4310 }
4311
4312 ValueDecl *D = nullptr;
4313 Expr *Inner = E->IgnoreParens();
4314 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4315 D = DRE->getDecl();
4316 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4317 D = ME->getMemberDecl();
4318 }
4319
4320 // If it's a field, require the containing struct to have a
4321 // complete definition so that we can compute the layout.
4322 //
4323 // This can happen in C++11 onwards, either by naming the member
4324 // in a way that is not transformed into a member access expression
4325 // (in an unevaluated operand, for instance), or by naming the member
4326 // in a trailing-return-type.
4327 //
4328 // For the record, since __alignof__ on expressions is a GCC
4329 // extension, GCC seems to permit this but always gives the
4330 // nonsensical answer 0.
4331 //
4332 // We don't really need the layout here --- we could instead just
4333 // directly check for all the appropriate alignment-lowing
4334 // attributes --- but that would require duplicating a lot of
4335 // logic that just isn't worth duplicating for such a marginal
4336 // use-case.
4337 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4338 // Fast path this check, since we at least know the record has a
4339 // definition if we can find a member of it.
4340 if (!FD->getParent()->isCompleteDefinition()) {
4341 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4342 << E->getSourceRange();
4343 return true;
4344 }
4345
4346 // Otherwise, if it's a field, and the field doesn't have
4347 // reference type, then it must have a complete type (or be a
4348 // flexible array member, which we explicitly want to
4349 // white-list anyway), which makes the following checks trivial.
4350 if (!FD->getType()->isReferenceType())
4351 return false;
4352 }
4353
4354 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4355}
4356
4357bool Sema::CheckVecStepExpr(Expr *E) {
4358 E = E->IgnoreParens();
4359
4360 // Cannot know anything else if the expression is dependent.
4361 if (E->isTypeDependent())
4362 return false;
4363
4364 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4365}
4366
4367static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4368 CapturingScopeInfo *CSI) {
4369 assert(T->isVariablyModifiedType())(static_cast<void> (0));
4370 assert(CSI != nullptr)(static_cast<void> (0));
4371
4372 // We're going to walk down into the type and look for VLA expressions.
4373 do {
4374 const Type *Ty = T.getTypePtr();
4375 switch (Ty->getTypeClass()) {
4376#define TYPE(Class, Base)
4377#define ABSTRACT_TYPE(Class, Base)
4378#define NON_CANONICAL_TYPE(Class, Base)
4379#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4380#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4381#include "clang/AST/TypeNodes.inc"
4382 T = QualType();
4383 break;
4384 // These types are never variably-modified.
4385 case Type::Builtin:
4386 case Type::Complex:
4387 case Type::Vector:
4388 case Type::ExtVector:
4389 case Type::ConstantMatrix:
4390 case Type::Record:
4391 case Type::Enum:
4392 case Type::Elaborated:
4393 case Type::TemplateSpecialization:
4394 case Type::ObjCObject:
4395 case Type::ObjCInterface:
4396 case Type::ObjCObjectPointer:
4397 case Type::ObjCTypeParam:
4398 case Type::Pipe:
4399 case Type::ExtInt:
4400 llvm_unreachable("type class is never variably-modified!")__builtin_unreachable();
4401 case Type::Adjusted:
4402 T = cast<AdjustedType>(Ty)->getOriginalType();
4403 break;
4404 case Type::Decayed:
4405 T = cast<DecayedType>(Ty)->getPointeeType();
4406 break;
4407 case Type::Pointer:
4408 T = cast<PointerType>(Ty)->getPointeeType();
4409 break;
4410 case Type::BlockPointer:
4411 T = cast<BlockPointerType>(Ty)->getPointeeType();
4412 break;
4413 case Type::LValueReference:
4414 case Type::RValueReference:
4415 T = cast<ReferenceType>(Ty)->getPointeeType();
4416 break;
4417 case Type::MemberPointer:
4418 T = cast<MemberPointerType>(Ty)->getPointeeType();
4419 break;
4420 case Type::ConstantArray:
4421 case Type::IncompleteArray:
4422 // Losing element qualification here is fine.
4423 T = cast<ArrayType>(Ty)->getElementType();
4424 break;
4425 case Type::VariableArray: {
4426 // Losing element qualification here is fine.
4427 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4428
4429 // Unknown size indication requires no size computation.
4430 // Otherwise, evaluate and record it.
4431 auto Size = VAT->getSizeExpr();
4432 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4433 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4434 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4435
4436 T = VAT->getElementType();
4437 break;
4438 }
4439 case Type::FunctionProto:
4440 case Type::FunctionNoProto:
4441 T = cast<FunctionType>(Ty)->getReturnType();
4442 break;
4443 case Type::Paren:
4444 case Type::TypeOf:
4445 case Type::UnaryTransform:
4446 case Type::Attributed:
4447 case Type::SubstTemplateTypeParm:
4448 case Type::MacroQualified:
4449 // Keep walking after single level desugaring.
4450 T = T.getSingleStepDesugaredType(Context);
4451 break;
4452 case Type::Typedef:
4453 T = cast<TypedefType>(Ty)->desugar();
4454 break;
4455 case Type::Decltype:
4456 T = cast<DecltypeType>(Ty)->desugar();
4457 break;
4458 case Type::Auto:
4459 case Type::DeducedTemplateSpecialization:
4460 T = cast<DeducedType>(Ty)->getDeducedType();
4461 break;
4462 case Type::TypeOfExpr:
4463 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4464 break;
4465 case Type::Atomic:
4466 T = cast<AtomicType>(Ty)->getValueType();
4467 break;
4468 }
4469 } while (!T.isNull() && T->isVariablyModifiedType());
4470}
4471
4472/// Build a sizeof or alignof expression given a type operand.
4473ExprResult
4474Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4475 SourceLocation OpLoc,
4476 UnaryExprOrTypeTrait ExprKind,
4477 SourceRange R) {
4478 if (!TInfo)
4479 return ExprError();
4480
4481 QualType T = TInfo->getType();
4482
4483 if (!T->isDependentType() &&
4484 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4485 return ExprError();
4486
4487 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4488 if (auto *TT = T->getAs<TypedefType>()) {
4489 for (auto I = FunctionScopes.rbegin(),
4490 E = std::prev(FunctionScopes.rend());
4491 I != E; ++I) {
4492 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4493 if (CSI == nullptr)
4494 break;
4495 DeclContext *DC = nullptr;
4496 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4497 DC = LSI->CallOperator;
4498 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4499 DC = CRSI->TheCapturedDecl;
4500 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4501 DC = BSI->TheDecl;
4502 if (DC) {
4503 if (DC->containsDecl(TT->getDecl()))
4504 break;
4505 captureVariablyModifiedType(Context, T, CSI);
4506 }
4507 }
4508 }
4509 }
4510
4511 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4512 return new (Context) UnaryExprOrTypeTraitExpr(
4513 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4514}
4515
4516/// Build a sizeof or alignof expression given an expression
4517/// operand.
4518ExprResult
4519Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4520 UnaryExprOrTypeTrait ExprKind) {
4521 ExprResult PE = CheckPlaceholderExpr(E);
4522 if (PE.isInvalid())
4523 return ExprError();
4524
4525 E = PE.get();
4526
4527 // Verify that the operand is valid.
4528 bool isInvalid = false;
4529 if (E->isTypeDependent()) {
4530 // Delay type-checking for type-dependent expressions.
4531 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4532 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4533 } else if (ExprKind == UETT_VecStep) {
4534 isInvalid = CheckVecStepExpr(E);
4535 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4536 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4537 isInvalid = true;
4538 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4539 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4540 isInvalid = true;
4541 } else {
4542 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4543 }
4544
4545 if (isInvalid)
4546 return ExprError();
4547
4548 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4549 PE = TransformToPotentiallyEvaluated(E);
4550 if (PE.isInvalid()) return ExprError();
4551 E = PE.get();
4552 }
4553
4554 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4555 return new (Context) UnaryExprOrTypeTraitExpr(
4556 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4557}
4558
4559/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4560/// expr and the same for @c alignof and @c __alignof
4561/// Note that the ArgRange is invalid if isType is false.
4562ExprResult
4563Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4564 UnaryExprOrTypeTrait ExprKind, bool IsType,
4565 void *TyOrEx, SourceRange ArgRange) {
4566 // If error parsing type, ignore.
4567 if (!TyOrEx) return ExprError();
4568
4569 if (IsType) {
4570 TypeSourceInfo *TInfo;
4571 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4572 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4573 }
4574
4575 Expr *ArgEx = (Expr *)TyOrEx;
4576 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4577 return Result;
4578}
4579
4580static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4581 bool IsReal) {
4582 if (V.get()->isTypeDependent())
4583 return S.Context.DependentTy;
4584
4585 // _Real and _Imag are only l-values for normal l-values.
4586 if (V.get()->getObjectKind() != OK_Ordinary) {
4587 V = S.DefaultLvalueConversion(V.get());
4588 if (V.isInvalid())
4589 return QualType();
4590 }
4591
4592 // These operators return the element type of a complex type.
4593 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4594 return CT->getElementType();
4595
4596 // Otherwise they pass through real integer and floating point types here.
4597 if (V.get()->getType()->isArithmeticType())
4598 return V.get()->getType();
4599
4600 // Test for placeholders.
4601 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4602 if (PR.isInvalid()) return QualType();
4603 if (PR.get() != V.get()) {
4604 V = PR;
4605 return CheckRealImagOperand(S, V, Loc, IsReal);
4606 }
4607
4608 // Reject anything else.
4609 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4610 << (IsReal ? "__real" : "__imag");
4611 return QualType();
4612}
4613
4614
4615
4616ExprResult
4617Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4618 tok::TokenKind Kind, Expr *Input) {
4619 UnaryOperatorKind Opc;
4620 switch (Kind) {
4621 default: llvm_unreachable("Unknown unary op!")__builtin_unreachable();
4622 case tok::plusplus: Opc = UO_PostInc; break;
4623 case tok::minusminus: Opc = UO_PostDec; break;
4624 }
4625
4626 // Since this might is a postfix expression, get rid of ParenListExprs.
4627 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4628 if (Result.isInvalid()) return ExprError();
4629 Input = Result.get();
4630
4631 return BuildUnaryOp(S, OpLoc, Opc, Input);
4632}
4633
4634/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4635///
4636/// \return true on error
4637static bool checkArithmeticOnObjCPointer(Sema &S,
4638 SourceLocation opLoc,
4639 Expr *op) {
4640 assert(op->getType()->isObjCObjectPointerType())(static_cast<void> (0));
4641 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4642 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4643 return false;
4644
4645 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4646 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4647 << op->getSourceRange();
4648 return true;
4649}
4650
4651static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4652 auto *BaseNoParens = Base->IgnoreParens();
4653 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4654 return MSProp->getPropertyDecl()->getType()->isArrayType();
4655 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4656}
4657
4658ExprResult
4659Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4660 Expr *idx, SourceLocation rbLoc) {
4661 if (base && !base->getType().isNull() &&
4662 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4663 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4664 SourceLocation(), /*Length*/ nullptr,
4665 /*Stride=*/nullptr, rbLoc);
4666
4667 // Since this might be a postfix expression, get rid of ParenListExprs.
4668 if (isa<ParenListExpr>(base)) {
4669 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4670 if (result.isInvalid()) return ExprError();
4671 base = result.get();
4672 }
4673
4674 // Check if base and idx form a MatrixSubscriptExpr.
4675 //
4676 // Helper to check for comma expressions, which are not allowed as indices for
4677 // matrix subscript expressions.
4678 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4679 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4680 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4681 << SourceRange(base->getBeginLoc(), rbLoc);
4682 return true;
4683 }
4684 return false;
4685 };
4686 // The matrix subscript operator ([][])is considered a single operator.
4687 // Separating the index expressions by parenthesis is not allowed.
4688 if (base->getType()->isSpecificPlaceholderType(
4689 BuiltinType::IncompleteMatrixIdx) &&
4690 !isa<MatrixSubscriptExpr>(base)) {
4691 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4692 << SourceRange(base->getBeginLoc(), rbLoc);
4693 return ExprError();
4694 }
4695 // If the base is a MatrixSubscriptExpr, try to create a new
4696 // MatrixSubscriptExpr.
4697 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4698 if (matSubscriptE) {
4699 if (CheckAndReportCommaError(idx))
4700 return ExprError();
4701
4702 assert(matSubscriptE->isIncomplete() &&(static_cast<void> (0))
4703 "base has to be an incomplete matrix subscript")(static_cast<void> (0));
4704 return CreateBuiltinMatrixSubscriptExpr(
4705 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4706 }
4707
4708 // Handle any non-overload placeholder types in the base and index
4709 // expressions. We can't handle overloads here because the other
4710 // operand might be an overloadable type, in which case the overload
4711 // resolution for the operator overload should get the first crack
4712 // at the overload.
4713 bool IsMSPropertySubscript = false;
4714 if (base->getType()->isNonOverloadPlaceholderType()) {
4715 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4716 if (!IsMSPropertySubscript) {
4717 ExprResult result = CheckPlaceholderExpr(base);
4718 if (result.isInvalid())
4719 return ExprError();
4720 base = result.get();
4721 }
4722 }
4723
4724 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4725 if (base->getType()->isMatrixType()) {
4726 if (CheckAndReportCommaError(idx))
4727 return ExprError();
4728
4729 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4730 }
4731
4732 // A comma-expression as the index is deprecated in C++2a onwards.
4733 if (getLangOpts().CPlusPlus20 &&
4734 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4735 (isa<CXXOperatorCallExpr>(idx) &&
4736 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4737 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4738 << SourceRange(base->getBeginLoc(), rbLoc);
4739 }
4740
4741 if (idx->getType()->isNonOverloadPlaceholderType()) {
4742 ExprResult result = CheckPlaceholderExpr(idx);
4743 if (result.isInvalid()) return ExprError();
4744 idx = result.get();
4745 }
4746
4747 // Build an unanalyzed expression if either operand is type-dependent.
4748 if (getLangOpts().CPlusPlus &&
4749 (base->isTypeDependent() || idx->isTypeDependent())) {
4750 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4751 VK_LValue, OK_Ordinary, rbLoc);
4752 }
4753
4754 // MSDN, property (C++)
4755 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4756 // This attribute can also be used in the declaration of an empty array in a
4757 // class or structure definition. For example:
4758 // __declspec(property(get=GetX, put=PutX)) int x[];
4759 // The above statement indicates that x[] can be used with one or more array
4760 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4761 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4762 if (IsMSPropertySubscript) {
4763 // Build MS property subscript expression if base is MS property reference
4764 // or MS property subscript.
4765 return new (Context) MSPropertySubscriptExpr(
4766 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4767 }
4768
4769 // Use C++ overloaded-operator rules if either operand has record
4770 // type. The spec says to do this if either type is *overloadable*,
4771 // but enum types can't declare subscript operators or conversion
4772 // operators, so there's nothing interesting for overload resolution
4773 // to do if there aren't any record types involved.
4774 //
4775 // ObjC pointers have their own subscripting logic that is not tied
4776 // to overload resolution and so should not take this path.
4777 if (getLangOpts().CPlusPlus &&
4778 (base->getType()->isRecordType() ||
4779 (!base->getType()->isObjCObjectPointerType() &&
4780 idx->getType()->isRecordType()))) {
4781 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4782 }
4783
4784 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4785
4786 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4787 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4788
4789 return Res;
4790}
4791
4792ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4793 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4794 InitializationKind Kind =
4795 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4796 InitializationSequence InitSeq(*this, Entity, Kind, E);
4797 return InitSeq.Perform(*this, Entity, Kind, E);
4798}
4799
4800ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4801 Expr *ColumnIdx,
4802 SourceLocation RBLoc) {
4803 ExprResult BaseR = CheckPlaceholderExpr(Base);
4804 if (BaseR.isInvalid())
4805 return BaseR;
4806 Base = BaseR.get();
4807
4808 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4809 if (RowR.isInvalid())
4810 return RowR;
4811 RowIdx = RowR.get();
4812
4813 if (!ColumnIdx)
4814 return new (Context) MatrixSubscriptExpr(
4815 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4816
4817 // Build an unanalyzed expression if any of the operands is type-dependent.
4818 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4819 ColumnIdx->isTypeDependent())
4820 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4821 Context.DependentTy, RBLoc);
4822
4823 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4824 if (ColumnR.isInvalid())
4825 return ColumnR;
4826 ColumnIdx = ColumnR.get();
4827
4828 // Check that IndexExpr is an integer expression. If it is a constant
4829 // expression, check that it is less than Dim (= the number of elements in the
4830 // corresponding dimension).
4831 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4832 bool IsColumnIdx) -> Expr * {
4833 if (!IndexExpr->getType()->isIntegerType() &&
4834 !IndexExpr->isTypeDependent()) {
4835 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4836 << IsColumnIdx;
4837 return nullptr;
4838 }
4839
4840 if (Optional<llvm::APSInt> Idx =
4841 IndexExpr->getIntegerConstantExpr(Context)) {
4842 if ((*Idx < 0 || *Idx >= Dim)) {
4843 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4844 << IsColumnIdx << Dim;
4845 return nullptr;
4846 }
4847 }
4848
4849 ExprResult ConvExpr =
4850 tryConvertExprToType(IndexExpr, Context.getSizeType());
4851 assert(!ConvExpr.isInvalid() &&(static_cast<void> (0))
4852 "should be able to convert any integer type to size type")(static_cast<void> (0));
4853 return ConvExpr.get();
4854 };
4855
4856 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4857 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4858 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4859 if (!RowIdx || !ColumnIdx)
4860 return ExprError();
4861
4862 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4863 MTy->getElementType(), RBLoc);
4864}
4865
4866void Sema::CheckAddressOfNoDeref(const Expr *E) {
4867 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4868 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4869
4870 // For expressions like `&(*s).b`, the base is recorded and what should be
4871 // checked.
4872 const MemberExpr *Member = nullptr;
4873 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4874 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4875
4876 LastRecord.PossibleDerefs.erase(StrippedExpr);
4877}
4878
4879void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4880 if (isUnevaluatedContext())
4881 return;
4882
4883 QualType ResultTy = E->getType();
4884 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4885
4886 // Bail if the element is an array since it is not memory access.
4887 if (isa<ArrayType>(ResultTy))
4888 return;
4889
4890 if (ResultTy->hasAttr(attr::NoDeref)) {
4891 LastRecord.PossibleDerefs.insert(E);
4892 return;
4893 }
4894
4895 // Check if the base type is a pointer to a member access of a struct
4896 // marked with noderef.
4897 const Expr *Base = E->getBase();
4898 QualType BaseTy = Base->getType();
4899 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4900 // Not a pointer access
4901 return;
4902
4903 const MemberExpr *Member = nullptr;
4904 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4905 Member->isArrow())
4906 Base = Member->getBase();
4907
4908 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4909 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4910 LastRecord.PossibleDerefs.insert(E);
4911 }
4912}
4913
4914ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4915 Expr *LowerBound,
4916 SourceLocation ColonLocFirst,
4917 SourceLocation ColonLocSecond,
4918 Expr *Length, Expr *Stride,
4919 SourceLocation RBLoc) {
4920 if (Base->getType()->isPlaceholderType() &&
4921 !Base->getType()->isSpecificPlaceholderType(
4922 BuiltinType::OMPArraySection)) {
4923 ExprResult Result = CheckPlaceholderExpr(Base);
4924 if (Result.isInvalid())
4925 return ExprError();
4926 Base = Result.get();
4927 }
4928 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4929 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4930 if (Result.isInvalid())
4931 return ExprError();
4932 Result = DefaultLvalueConversion(Result.get());
4933 if (Result.isInvalid())
4934 return ExprError();
4935 LowerBound = Result.get();
4936 }
4937 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4938 ExprResult Result = CheckPlaceholderExpr(Length);
4939 if (Result.isInvalid())
4940 return ExprError();
4941 Result = DefaultLvalueConversion(Result.get());
4942 if (Result.isInvalid())
4943 return ExprError();
4944 Length = Result.get();
4945 }
4946 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4947 ExprResult Result = CheckPlaceholderExpr(Stride);
4948 if (Result.isInvalid())
4949 return ExprError();
4950 Result = DefaultLvalueConversion(Result.get());
4951 if (Result.isInvalid())
4952 return ExprError();
4953 Stride = Result.get();
4954 }
4955
4956 // Build an unanalyzed expression if either operand is type-dependent.
4957 if (Base->isTypeDependent() ||
4958 (LowerBound &&
4959 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4960 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4961 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4962 return new (Context) OMPArraySectionExpr(
4963 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4964 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4965 }
4966
4967 // Perform default conversions.
4968 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4969 QualType ResultTy;
4970 if (OriginalTy->isAnyPointerType()) {
4971 ResultTy = OriginalTy->getPointeeType();
4972 } else if (OriginalTy->isArrayType()) {
4973 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4974 } else {
4975 return ExprError(
4976 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4977 << Base->getSourceRange());
4978 }
4979 // C99 6.5.2.1p1
4980 if (LowerBound) {
4981 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4982 LowerBound);
4983 if (Res.isInvalid())
4984 return ExprError(Diag(LowerBound->getExprLoc(),
4985 diag::err_omp_typecheck_section_not_integer)
4986 << 0 << LowerBound->getSourceRange());
4987 LowerBound = Res.get();
4988
4989 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4990 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4991 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4992 << 0 << LowerBound->getSourceRange();
4993 }
4994 if (Length) {
4995 auto Res =
4996 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4997 if (Res.isInvalid())
4998 return ExprError(Diag(Length->getExprLoc(),
4999 diag::err_omp_typecheck_section_not_integer)
5000 << 1 << Length->getSourceRange());
5001 Length = Res.get();
5002
5003 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5004 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5005 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5006 << 1 << Length->getSourceRange();
5007 }
5008 if (Stride) {
5009 ExprResult Res =
5010 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5011 if (Res.isInvalid())
5012 return ExprError(Diag(Stride->getExprLoc(),
5013 diag::err_omp_typecheck_section_not_integer)
5014 << 1 << Stride->getSourceRange());
5015 Stride = Res.get();
5016
5017 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5018 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5019 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5020 << 1 << Stride->getSourceRange();
5021 }
5022
5023 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5024 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5025 // type. Note that functions are not objects, and that (in C99 parlance)
5026 // incomplete types are not object types.
5027 if (ResultTy->isFunctionType()) {
5028 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5029 << ResultTy << Base->getSourceRange();
5030 return ExprError();
5031 }
5032
5033 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5034 diag::err_omp_section_incomplete_type, Base))
5035 return ExprError();
5036
5037 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5038 Expr::EvalResult Result;
5039 if (LowerBound->EvaluateAsInt(Result, Context)) {
5040 // OpenMP 5.0, [2.1.5 Array Sections]
5041 // The array section must be a subset of the original array.
5042 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5043 if (LowerBoundValue.isNegative()) {
5044 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5045 << LowerBound->getSourceRange();
5046 return ExprError();
5047 }
5048 }
5049 }
5050
5051 if (Length) {
5052 Expr::EvalResult Result;
5053 if (Length->EvaluateAsInt(Result, Context)) {
5054 // OpenMP 5.0, [2.1.5 Array Sections]
5055 // The length must evaluate to non-negative integers.
5056 llvm::APSInt LengthValue = Result.Val.getInt();
5057 if (LengthValue.isNegative()) {
5058 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5059 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5060 << Length->getSourceRange();
5061 return ExprError();
5062 }
5063 }
5064 } else if (ColonLocFirst.isValid() &&
5065 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5066 !OriginalTy->isVariableArrayType()))) {
5067 // OpenMP 5.0, [2.1.5 Array Sections]
5068 // When the size of the array dimension is not known, the length must be
5069 // specified explicitly.
5070 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5071 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5072 return ExprError();
5073 }
5074
5075 if (Stride) {
5076 Expr::EvalResult Result;
5077 if (Stride->EvaluateAsInt(Result, Context)) {
5078 // OpenMP 5.0, [2.1.5 Array Sections]
5079 // The stride must evaluate to a positive integer.
5080 llvm::APSInt StrideValue = Result.Val.getInt();
5081 if (!StrideValue.isStrictlyPositive()) {
5082 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5083 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5084 << Stride->getSourceRange();
5085 return ExprError();
5086 }
5087 }
5088 }
5089
5090 if (!Base->getType()->isSpecificPlaceholderType(
5091 BuiltinType::OMPArraySection)) {
5092 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5093 if (Result.isInvalid())
5094 return ExprError();
5095 Base = Result.get();
5096 }
5097 return new (Context) OMPArraySectionExpr(
5098 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5099 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5100}
5101
5102ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5103 SourceLocation RParenLoc,
5104 ArrayRef<Expr *> Dims,
5105 ArrayRef<SourceRange> Brackets) {
5106 if (Base->getType()->isPlaceholderType()) {
5107 ExprResult Result = CheckPlaceholderExpr(Base);
5108 if (Result.isInvalid())
5109 return ExprError();
5110 Result = DefaultLvalueConversion(Result.get());
5111 if (Result.isInvalid())
5112 return ExprError();
5113 Base = Result.get();
5114 }
5115 QualType BaseTy = Base->getType();
5116 // Delay analysis of the types/expressions if instantiation/specialization is
5117 // required.
5118 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5119 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5120 LParenLoc, RParenLoc, Dims, Brackets);
5121 if (!BaseTy->isPointerType() ||
5122 (!Base->isTypeDependent() &&
5123 BaseTy->getPointeeType()->isIncompleteType()))
5124 return ExprError(Diag(Base->getExprLoc(),
5125 diag::err_omp_non_pointer_type_array_shaping_base)
5126 << Base->getSourceRange());
5127
5128 SmallVector<Expr *, 4> NewDims;
5129 bool ErrorFound = false;
5130 for (Expr *Dim : Dims) {
5131 if (Dim->getType()->isPlaceholderType()) {
5132 ExprResult Result = CheckPlaceholderExpr(Dim);
5133 if (Result.isInvalid()) {
5134 ErrorFound = true;
5135 continue;
5136 }
5137 Result = DefaultLvalueConversion(Result.get());
5138 if (Result.isInvalid()) {
5139 ErrorFound = true;
5140 continue;
5141 }
5142 Dim = Result.get();
5143 }
5144 if (!Dim->isTypeDependent()) {
5145 ExprResult Result =
5146 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5147 if (Result.isInvalid()) {
5148 ErrorFound = true;
5149 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5150 << Dim->getSourceRange();
5151 continue;
5152 }
5153 Dim = Result.get();
5154 Expr::EvalResult EvResult;
5155 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5156 // OpenMP 5.0, [2.1.4 Array Shaping]
5157 // Each si is an integral type expression that must evaluate to a
5158 // positive integer.
5159 llvm::APSInt Value = EvResult.Val.getInt();
5160 if (!Value.isStrictlyPositive()) {
5161 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5162 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5163 << Dim->getSourceRange();
5164 ErrorFound = true;
5165 continue;
5166 }
5167 }
5168 }
5169 NewDims.push_back(Dim);
5170 }
5171 if (ErrorFound)
5172 return ExprError();
5173 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5174 LParenLoc, RParenLoc, NewDims, Brackets);
5175}
5176
5177ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5178 SourceLocation LLoc, SourceLocation RLoc,
5179 ArrayRef<OMPIteratorData> Data) {
5180 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5181 bool IsCorrect = true;
5182 for (const OMPIteratorData &D : Data) {
5183 TypeSourceInfo *TInfo = nullptr;
5184 SourceLocation StartLoc;
5185 QualType DeclTy;
5186 if (!D.Type.getAsOpaquePtr()) {
5187 // OpenMP 5.0, 2.1.6 Iterators
5188 // In an iterator-specifier, if the iterator-type is not specified then
5189 // the type of that iterator is of int type.
5190 DeclTy = Context.IntTy;
5191 StartLoc = D.DeclIdentLoc;
5192 } else {
5193 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5194 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5195 }
5196
5197 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5198 DeclTy->containsUnexpandedParameterPack() ||
5199 DeclTy->isInstantiationDependentType();
5200 if (!IsDeclTyDependent) {
5201 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5202 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5203 // The iterator-type must be an integral or pointer type.
5204 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5205 << DeclTy;
5206 IsCorrect = false;
5207 continue;
5208 }
5209 if (DeclTy.isConstant(Context)) {
5210 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5211 // The iterator-type must not be const qualified.
5212 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5213 << DeclTy;
5214 IsCorrect = false;
5215 continue;
5216 }
5217 }
5218
5219 // Iterator declaration.
5220 assert(D.DeclIdent && "Identifier expected.")(static_cast<void> (0));
5221 // Always try to create iterator declarator to avoid extra error messages
5222 // about unknown declarations use.
5223 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5224 D.DeclIdent, DeclTy, TInfo, SC_None);
5225 VD->setImplicit();
5226 if (S) {
5227 // Check for conflicting previous declaration.
5228 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5229 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5230 ForVisibleRedeclaration);
5231 Previous.suppressDiagnostics();
5232 LookupName(Previous, S);
5233
5234 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5235 /*AllowInlineNamespace=*/false);
5236 if (!Previous.empty()) {
5237 NamedDecl *Old = Previous.getRepresentativeDecl();
5238 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5239 Diag(Old->getLocation(), diag::note_previous_definition);
5240 } else {
5241 PushOnScopeChains(VD, S);
5242 }
5243 } else {
5244 CurContext->addDecl(VD);
5245 }
5246 Expr *Begin = D.Range.Begin;
5247 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5248 ExprResult BeginRes =
5249 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5250 Begin = BeginRes.get();
5251 }
5252 Expr *End = D.Range.End;
5253 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5254 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5255 End = EndRes.get();
5256 }
5257 Expr *Step = D.Range.Step;
5258 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5259 if (!Step->getType()->isIntegralType(Context)) {
5260 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5261 << Step << Step->getSourceRange();
5262 IsCorrect = false;
5263 continue;
5264 }
5265 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5266 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5267 // If the step expression of a range-specification equals zero, the
5268 // behavior is unspecified.
5269 if (Result && Result->isNullValue()) {
5270 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5271 << Step << Step->getSourceRange();
5272 IsCorrect = false;
5273 continue;
5274 }
5275 }
5276 if (!Begin || !End || !IsCorrect) {
5277 IsCorrect = false;
5278 continue;
5279 }
5280 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5281 IDElem.IteratorDecl = VD;
5282 IDElem.AssignmentLoc = D.AssignLoc;
5283 IDElem.Range.Begin = Begin;
5284 IDElem.Range.End = End;
5285 IDElem.Range.Step = Step;
5286 IDElem.ColonLoc = D.ColonLoc;
5287 IDElem.SecondColonLoc = D.SecColonLoc;
5288 }
5289 if (!IsCorrect) {
5290 // Invalidate all created iterator declarations if error is found.
5291 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5292 if (Decl *ID = D.IteratorDecl)
5293 ID->setInvalidDecl();
5294 }
5295 return ExprError();
5296 }
5297 SmallVector<OMPIteratorHelperData, 4> Helpers;
5298 if (!CurContext->isDependentContext()) {
5299 // Build number of ityeration for each iteration range.
5300 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5301 // ((Begini-Stepi-1-Endi) / -Stepi);
5302 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5303 // (Endi - Begini)
5304 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5305 D.Range.Begin);
5306 if(!Res.isUsable()) {
5307 IsCorrect = false;
5308 continue;
5309 }
5310 ExprResult St, St1;
5311 if (D.Range.Step) {
5312 St = D.Range.Step;
5313 // (Endi - Begini) + Stepi
5314 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5315 if (!Res.isUsable()) {
5316 IsCorrect = false;
5317 continue;
5318 }
5319 // (Endi - Begini) + Stepi - 1
5320 Res =
5321 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5322 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5323 if (!Res.isUsable()) {
5324 IsCorrect = false;
5325 continue;
5326 }
5327 // ((Endi - Begini) + Stepi - 1) / Stepi
5328 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5329 if (!Res.isUsable()) {
5330 IsCorrect = false;
5331 continue;
5332 }
5333 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5334 // (Begini - Endi)
5335 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5336 D.Range.Begin, D.Range.End);
5337 if (!Res1.isUsable()) {
5338 IsCorrect = false;
5339 continue;
5340 }
5341 // (Begini - Endi) - Stepi
5342 Res1 =
5343 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5344 if (!Res1.isUsable()) {
5345 IsCorrect = false;
5346 continue;
5347 }
5348 // (Begini - Endi) - Stepi - 1
5349 Res1 =
5350 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5351 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5352 if (!Res1.isUsable()) {
5353 IsCorrect = false;
5354 continue;
5355 }
5356 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5357 Res1 =
5358 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5359 if (!Res1.isUsable()) {
5360 IsCorrect = false;
5361 continue;
5362 }
5363 // Stepi > 0.
5364 ExprResult CmpRes =
5365 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5366 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5367 if (!CmpRes.isUsable()) {
5368 IsCorrect = false;
5369 continue;
5370 }
5371 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5372 Res.get(), Res1.get());
5373 if (!Res.isUsable()) {
5374 IsCorrect = false;
5375 continue;
5376 }
5377 }
5378 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5379 if (!Res.isUsable()) {
5380 IsCorrect = false;
5381 continue;
5382 }
5383
5384 // Build counter update.
5385 // Build counter.
5386 auto *CounterVD =
5387 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5388 D.IteratorDecl->getBeginLoc(), nullptr,
5389 Res.get()->getType(), nullptr, SC_None);
5390 CounterVD->setImplicit();
5391 ExprResult RefRes =
5392 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5393 D.IteratorDecl->getBeginLoc());
5394 // Build counter update.
5395 // I = Begini + counter * Stepi;
5396 ExprResult UpdateRes;
5397 if (D.Range.Step) {
5398 UpdateRes = CreateBuiltinBinOp(
5399 D.AssignmentLoc, BO_Mul,
5400 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5401 } else {
5402 UpdateRes = DefaultLvalueConversion(RefRes.get());
5403 }
5404 if (!UpdateRes.isUsable()) {
5405 IsCorrect = false;
5406 continue;
5407 }
5408 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5409 UpdateRes.get());
5410 if (!UpdateRes.isUsable()) {
5411 IsCorrect = false;
5412 continue;
5413 }
5414 ExprResult VDRes =
5415 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5416 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5417 D.IteratorDecl->getBeginLoc());
5418 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5419 UpdateRes.get());
5420 if (!UpdateRes.isUsable()) {
5421 IsCorrect = false;
5422 continue;
5423 }
5424 UpdateRes =
5425 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5426 if (!UpdateRes.isUsable()) {
5427 IsCorrect = false;
5428 continue;
5429 }
5430 ExprResult CounterUpdateRes =
5431 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5432 if (!CounterUpdateRes.isUsable()) {
5433 IsCorrect = false;
5434 continue;
5435 }
5436 CounterUpdateRes =
5437 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5438 if (!CounterUpdateRes.isUsable()) {
5439 IsCorrect = false;
5440 continue;
5441 }
5442 OMPIteratorHelperData &HD = Helpers.emplace_back();
5443 HD.CounterVD = CounterVD;
5444 HD.Upper = Res.get();
5445 HD.Update = UpdateRes.get();
5446 HD.CounterUpdate = CounterUpdateRes.get();
5447 }
5448 } else {
5449 Helpers.assign(ID.size(), {});
5450 }
5451 if (!IsCorrect) {
5452 // Invalidate all created iterator declarations if error is found.
5453 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5454 if (Decl *ID = D.IteratorDecl)
5455 ID->setInvalidDecl();
5456 }
5457 return ExprError();
5458 }
5459 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5460 LLoc, RLoc, ID, Helpers);
5461}
5462
5463ExprResult
5464Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5465 Expr *Idx, SourceLocation RLoc) {
5466 Expr *LHSExp = Base;
5467 Expr *RHSExp = Idx;
5468
5469 ExprValueKind VK = VK_LValue;
5470 ExprObjectKind OK = OK_Ordinary;
5471
5472 // Per C++ core issue 1213, the result is an xvalue if either operand is
5473 // a non-lvalue array, and an lvalue otherwise.
5474 if (getLangOpts().CPlusPlus11) {
5475 for (auto *Op : {LHSExp, RHSExp}) {
5476 Op = Op->IgnoreImplicit();
5477 if (Op->getType()->isArrayType() && !Op->isLValue())
5478 VK = VK_XValue;
5479 }
5480 }
5481
5482 // Perform default conversions.
5483 if (!LHSExp->getType()->getAs<VectorType>()) {
5484 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5485 if (Result.isInvalid())
5486 return ExprError();
5487 LHSExp = Result.get();
5488 }
5489 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5490 if (Result.isInvalid())
5491 return ExprError();
5492 RHSExp = Result.get();
5493
5494 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5495
5496 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5497 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5498 // in the subscript position. As a result, we need to derive the array base
5499 // and index from the expression types.
5500 Expr *BaseExpr, *IndexExpr;
5501 QualType ResultType;
5502 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5503 BaseExpr = LHSExp;
5504 IndexExpr = RHSExp;
5505 ResultType = Context.DependentTy;
5506 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5507 BaseExpr = LHSExp;
5508 IndexExpr = RHSExp;
5509 ResultType = PTy->getPointeeType();
5510 } else if (const ObjCObjectPointerType *PTy =
5511 LHSTy->getAs<ObjCObjectPointerType>()) {
5512 BaseExpr = LHSExp;
5513 IndexExpr = RHSExp;
5514
5515 // Use custom logic if this should be the pseudo-object subscript
5516 // expression.
5517 if (!LangOpts.isSubscriptPointerArithmetic())
5518 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5519 nullptr);
5520
5521 ResultType = PTy->getPointeeType();
5522 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5523 // Handle the uncommon case of "123[Ptr]".
5524 BaseExpr = RHSExp;
5525 IndexExpr = LHSExp;
5526 ResultType = PTy->getPointeeType();
5527 } else if (const ObjCObjectPointerType *PTy =
5528 RHSTy->getAs<ObjCObjectPointerType>()) {
5529 // Handle the uncommon case of "123[Ptr]".
5530 BaseExpr = RHSExp;
5531 IndexExpr = LHSExp;
5532 ResultType = PTy->getPointeeType();
5533 if (!LangOpts.isSubscriptPointerArithmetic()) {
5534 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5535 << ResultType << BaseExpr->getSourceRange();
5536 return ExprError();
5537 }
5538 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5539 BaseExpr = LHSExp; // vectors: V[123]
5540 IndexExpr = RHSExp;
5541 // We apply C++ DR1213 to vector subscripting too.
5542 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5543 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5544 if (Materialized.isInvalid())
5545 return ExprError();
5546 LHSExp = Materialized.get();
5547 }
5548 VK = LHSExp->getValueKind();
5549 if (VK != VK_PRValue)
5550 OK = OK_VectorComponent;
5551
5552 ResultType = VTy->getElementType();
5553 QualType BaseType = BaseExpr->getType();
5554 Qualifiers BaseQuals = BaseType.getQualifiers();
5555 Qualifiers MemberQuals = ResultType.getQualifiers();
5556 Qualifiers Combined = BaseQuals + MemberQuals;
5557 if (Combined != MemberQuals)
5558 ResultType = Context.getQualifiedType(ResultType, Combined);
5559 } else if (LHSTy->isArrayType()) {
5560 // If we see an array that wasn't promoted by
5561 // DefaultFunctionArrayLvalueConversion, it must be an array that
5562 // wasn't promoted because of the C90 rule that doesn't
5563 // allow promoting non-lvalue arrays. Warn, then
5564 // force the promotion here.
5565 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5566 << LHSExp->getSourceRange();
5567 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5568 CK_ArrayToPointerDecay).get();
5569 LHSTy = LHSExp->getType();
5570
5571 BaseExpr = LHSExp;
5572 IndexExpr = RHSExp;
5573 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5574 } else if (RHSTy->isArrayType()) {
5575 // Same as previous, except for 123[f().a] case
5576 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5577 << RHSExp->getSourceRange();
5578 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5579 CK_ArrayToPointerDecay).get();
5580 RHSTy = RHSExp->getType();
5581
5582 BaseExpr = RHSExp;
5583 IndexExpr = LHSExp;
5584 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5585 } else {
5586 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5587 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5588 }
5589 // C99 6.5.2.1p1
5590 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5591 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5592 << IndexExpr->getSourceRange());
5593
5594 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5595 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5596 && !IndexExpr->isTypeDependent())
5597 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5598
5599 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5600 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5601 // type. Note that Functions are not objects, and that (in C99 parlance)
5602 // incomplete types are not object types.
5603 if (ResultType->isFunctionType()) {
5604 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5605 << ResultType << BaseExpr->getSourceRange();
5606 return ExprError();
5607 }
5608
5609 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5610 // GNU extension: subscripting on pointer to void
5611 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5612 << BaseExpr->getSourceRange();
5613
5614 // C forbids expressions of unqualified void type from being l-values.
5615 // See IsCForbiddenLValueType.
5616 if (!ResultType.hasQualifiers())
5617 VK = VK_PRValue;
5618 } else if (!ResultType->isDependentType() &&
5619 RequireCompleteSizedType(
5620 LLoc, ResultType,
5621 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5622 return ExprError();
5623
5624 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||(static_cast<void> (0))
5625 !ResultType.isCForbiddenLValueType())(static_cast<void> (0));
5626
5627 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5628 FunctionScopes.size() > 1) {
5629 if (auto *TT =
5630 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5631 for (auto I = FunctionScopes.rbegin(),
5632 E = std::prev(FunctionScopes.rend());
5633 I != E; ++I) {
5634 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5635 if (CSI == nullptr)
5636 break;
5637 DeclContext *DC = nullptr;
5638 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5639 DC = LSI->CallOperator;
5640 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5641 DC = CRSI->TheCapturedDecl;
5642 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5643 DC = BSI->TheDecl;
5644 if (DC) {
5645 if (DC->containsDecl(TT->getDecl()))
5646 break;
5647 captureVariablyModifiedType(
5648 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5649 }
5650 }
5651 }
5652 }
5653
5654 return new (Context)
5655 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5656}
5657
5658bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5659 ParmVarDecl *Param) {
5660 if (Param->hasUnparsedDefaultArg()) {
5661 // If we've already cleared out the location for the default argument,
5662 // that means we're parsing it right now.
5663 if (!UnparsedDefaultArgLocs.count(Param)) {
5664 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5665 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5666 Param->setInvalidDecl();
5667 return true;
5668 }
5669
5670 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5671 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5672 Diag(UnparsedDefaultArgLocs[Param],
5673 diag::note_default_argument_declared_here);
5674 return true;
5675 }
5676
5677 if (Param->hasUninstantiatedDefaultArg() &&
5678 InstantiateDefaultArgument(CallLoc, FD, Param))
5679 return true;
5680
5681 assert(Param->hasInit() && "default argument but no initializer?")(static_cast<void> (0));
5682
5683 // If the default expression creates temporaries, we need to
5684 // push them to the current stack of expression temporaries so they'll
5685 // be properly destroyed.
5686 // FIXME: We should really be rebuilding the default argument with new
5687 // bound temporaries; see the comment in PR5810.
5688 // We don't need to do that with block decls, though, because
5689 // blocks in default argument expression can never capture anything.
5690 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5691 // Set the "needs cleanups" bit regardless of whether there are
5692 // any explicit objects.
5693 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5694
5695 // Append all the objects to the cleanup list. Right now, this
5696 // should always be a no-op, because blocks in default argument
5697 // expressions should never be able to capture anything.
5698 assert(!Init->getNumObjects() &&(static_cast<void> (0))
5699 "default argument expression has capturing blocks?")(static_cast<void> (0));
5700 }
5701
5702 // We already type-checked the argument, so we know it works.
5703 // Just mark all of the declarations in this potentially-evaluated expression
5704 // as being "referenced".
5705 EnterExpressionEvaluationContext EvalContext(
5706 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5707 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5708 /*SkipLocalVariables=*/true);
5709 return false;
5710}
5711
5712ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5713 FunctionDecl *FD, ParmVarDecl *Param) {
5714 assert(Param->hasDefaultArg() && "can't build nonexistent default arg")(static_cast<void> (0));
5715 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5716 return ExprError();
5717 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5718}
5719
5720Sema::VariadicCallType
5721Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5722 Expr *Fn) {
5723 if (Proto && Proto->isVariadic()) {
5724 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5725 return VariadicConstructor;
5726 else if (Fn && Fn->getType()->isBlockPointerType())
5727 return VariadicBlock;
5728 else if (FDecl) {
5729 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5730 if (Method->isInstance())
5731 return VariadicMethod;
5732 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5733 return VariadicMethod;
5734 return VariadicFunction;
5735 }
5736 return VariadicDoesNotApply;
5737}
5738
5739namespace {
5740class FunctionCallCCC final : public FunctionCallFilterCCC {
5741public:
5742 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5743 unsigned NumArgs, MemberExpr *ME)
5744 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5745 FunctionName(FuncName) {}
5746
5747 bool ValidateCandidate(const TypoCorrection &candidate) override {
5748 if (!candidate.getCorrectionSpecifier() ||
5749 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5750 return false;
5751 }
5752
5753 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5754 }
5755
5756 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5757 return std::make_unique<FunctionCallCCC>(*this);
5758 }
5759
5760private:
5761 const IdentifierInfo *const FunctionName;
5762};
5763}
5764
5765static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5766 FunctionDecl *FDecl,
5767 ArrayRef<Expr *> Args) {
5768 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5769 DeclarationName FuncName = FDecl->getDeclName();
5770 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5771
5772 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5773 if (TypoCorrection Corrected = S.CorrectTypo(
5774 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5775 S.getScopeForContext(S.CurContext), nullptr, CCC,
5776 Sema::CTK_ErrorRecovery)) {
5777 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5778 if (Corrected.isOverloaded()) {
5779 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5780 OverloadCandidateSet::iterator Best;
5781 for (NamedDecl *CD : Corrected) {
5782 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5783 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5784 OCS);
5785 }
5786 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5787 case OR_Success:
5788 ND = Best->FoundDecl;
5789 Corrected.setCorrectionDecl(ND);
5790 break;
5791 default:
5792 break;
5793 }
5794 }
5795 ND = ND->getUnderlyingDecl();
5796 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5797 return Corrected;
5798 }
5799 }
5800 return TypoCorrection();
5801}
5802
5803/// ConvertArgumentsForCall - Converts the arguments specified in
5804/// Args/NumArgs to the parameter types of the function FDecl with
5805/// function prototype Proto. Call is the call expression itself, and
5806/// Fn is the function expression. For a C++ member function, this
5807/// routine does not attempt to convert the object argument. Returns
5808/// true if the call is ill-formed.
5809bool
5810Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5811 FunctionDecl *FDecl,
5812 const FunctionProtoType *Proto,
5813 ArrayRef<Expr *> Args,
5814 SourceLocation RParenLoc,
5815 bool IsExecConfig) {
5816 // Bail out early if calling a builtin with custom typechecking.
5817 if (FDecl)
5818 if (unsigned ID = FDecl->getBuiltinID())
5819 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5820 return false;
5821
5822 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5823 // assignment, to the types of the corresponding parameter, ...
5824 unsigned NumParams = Proto->getNumParams();
5825 bool Invalid = false;
5826 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5827 unsigned FnKind = Fn->getType()->isBlockPointerType()
5828 ? 1 /* block */
5829 : (IsExecConfig ? 3 /* kernel function (exec config) */
5830 : 0 /* function */);
5831
5832 // If too few arguments are available (and we don't have default
5833 // arguments for the remaining parameters), don't make the call.
5834 if (Args.size() < NumParams) {
5835 if (Args.size() < MinArgs) {
5836 TypoCorrection TC;
5837 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5838 unsigned diag_id =
5839 MinArgs == NumParams && !Proto->isVariadic()
5840 ? diag::err_typecheck_call_too_few_args_suggest
5841 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5842 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5843 << static_cast<unsigned>(Args.size())
5844 << TC.getCorrectionRange());
5845 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5846 Diag(RParenLoc,
5847 MinArgs == NumParams && !Proto->isVariadic()
5848 ? diag::err_typecheck_call_too_few_args_one
5849 : diag::err_typecheck_call_too_few_args_at_least_one)
5850 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5851 else
5852 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5853 ? diag::err_typecheck_call_too_few_args
5854 : diag::err_typecheck_call_too_few_args_at_least)
5855 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5856 << Fn->getSourceRange();
5857
5858 // Emit the location of the prototype.
5859 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5860 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5861
5862 return true;
5863 }
5864 // We reserve space for the default arguments when we create
5865 // the call expression, before calling ConvertArgumentsForCall.
5866 assert((Call->getNumArgs() == NumParams) &&(static_cast<void> (0))
5867 "We should have reserved space for the default arguments before!")(static_cast<void> (0));
5868 }
5869
5870 // If too many are passed and not variadic, error on the extras and drop
5871 // them.
5872 if (Args.size() > NumParams) {
5873 if (!Proto->isVariadic()) {
5874 TypoCorrection TC;
5875 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5876 unsigned diag_id =
5877 MinArgs == NumParams && !Proto->isVariadic()
5878 ? diag::err_typecheck_call_too_many_args_suggest
5879 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5880 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5881 << static_cast<unsigned>(Args.size())
5882 << TC.getCorrectionRange());
5883 } else if (NumParams == 1 && FDecl &&
5884 FDecl->getParamDecl(0)->getDeclName())
5885 Diag(Args[NumParams]->getBeginLoc(),
5886 MinArgs == NumParams
5887 ? diag::err_typecheck_call_too_many_args_one
5888 : diag::err_typecheck_call_too_many_args_at_most_one)
5889 << FnKind << FDecl->getParamDecl(0)
5890 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5891 << SourceRange(Args[NumParams]->getBeginLoc(),
5892 Args.back()->getEndLoc());
5893 else
5894 Diag(Args[NumParams]->getBeginLoc(),
5895 MinArgs == NumParams
5896 ? diag::err_typecheck_call_too_many_args
5897 : diag::err_typecheck_call_too_many_args_at_most)
5898 << FnKind << NumParams << static_cast<unsigned>(Args.size())
5899 << Fn->getSourceRange()
5900 << SourceRange(Args[NumParams]->getBeginLoc(),
5901 Args.back()->getEndLoc());
5902
5903 // Emit the location of the prototype.
5904 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5905 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5906
5907 // This deletes the extra arguments.
5908 Call->shrinkNumArgs(NumParams);
5909 return true;
5910 }
5911 }
5912 SmallVector<Expr *, 8> AllArgs;
5913 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5914
5915 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5916 AllArgs, CallType);
5917 if (Invalid)
5918 return true;
5919 unsigned TotalNumArgs = AllArgs.size();
5920 for (unsigned i = 0; i < TotalNumArgs; ++i)
5921 Call->setArg(i, AllArgs[i]);
5922
5923 Call->computeDependence();
5924 return false;
5925}
5926
5927bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5928 const FunctionProtoType *Proto,
5929 unsigned FirstParam, ArrayRef<Expr *> Args,
5930 SmallVectorImpl<Expr *> &AllArgs,
5931 VariadicCallType CallType, bool AllowExplicit,
5932 bool IsListInitialization) {
5933 unsigned NumParams = Proto->getNumParams();
5934 bool Invalid = false;
5935 size_t ArgIx = 0;
5936 // Continue to check argument types (even if we have too few/many args).
5937 for (unsigned i = FirstParam; i < NumParams; i++) {
5938 QualType ProtoArgType = Proto->getParamType(i);
5939
5940 Expr *Arg;
5941 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5942 if (ArgIx < Args.size()) {
5943 Arg = Args[ArgIx++];
5944
5945 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5946 diag::err_call_incomplete_argument, Arg))
5947 return true;
5948
5949 // Strip the unbridged-cast placeholder expression off, if applicable.
5950 bool CFAudited = false;
5951 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5952 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5953 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5954 Arg = stripARCUnbridgedCast(Arg);
5955 else if (getLangOpts().ObjCAutoRefCount &&
5956 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5957 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5958 CFAudited = true;
5959
5960 if (Proto->getExtParameterInfo(i).isNoEscape() &&
5961 ProtoArgType->isBlockPointerType())
5962 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5963 BE->getBlockDecl()->setDoesNotEscape();
5964
5965 InitializedEntity Entity =
5966 Param ? InitializedEntity::InitializeParameter(Context, Param,
5967 ProtoArgType)
5968 : InitializedEntity::InitializeParameter(
5969 Context, ProtoArgType, Proto->isParamConsumed(i));
5970
5971 // Remember that parameter belongs to a CF audited API.
5972 if (CFAudited)
5973 Entity.setParameterCFAudited();
5974
5975 ExprResult ArgE = PerformCopyInitialization(
5976 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5977 if (ArgE.isInvalid())
5978 return true;
5979
5980 Arg = ArgE.getAs<Expr>();
5981 } else {
5982 assert(Param && "can't use default arguments without a known callee")(static_cast<void> (0));
5983
5984 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5985 if (ArgExpr.isInvalid())
5986 return true;
5987
5988 Arg = ArgExpr.getAs<Expr>();
5989 }
5990
5991 // Check for array bounds violations for each argument to the call. This
5992 // check only triggers warnings when the argument isn't a more complex Expr
5993 // with its own checking, such as a BinaryOperator.
5994 CheckArrayAccess(Arg);
5995
5996 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5997 CheckStaticArrayArgument(CallLoc, Param, Arg);
5998
5999 AllArgs.push_back(Arg);
6000 }
6001
6002 // If this is a variadic call, handle args passed through "...".
6003 if (CallType != VariadicDoesNotApply) {
6004 // Assume that extern "C" functions with variadic arguments that
6005 // return __unknown_anytype aren't *really* variadic.
6006 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6007 FDecl->isExternC()) {
6008 for (Expr *A : Args.slice(ArgIx)) {
6009 QualType paramType; // ignored
6010 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6011 Invalid |= arg.isInvalid();
6012 AllArgs.push_back(arg.get());
6013 }
6014
6015 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6016 } else {
6017 for (Expr *A : Args.slice(ArgIx)) {
6018 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6019 Invalid |= Arg.isInvalid();
6020 AllArgs.push_back(Arg.get());
6021 }
6022 }
6023
6024 // Check for array bounds violations.
6025 for (Expr *A : Args.slice(ArgIx))
6026 CheckArrayAccess(A);
6027 }
6028 return Invalid;
6029}
6030
6031static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6032 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6033 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6034 TL = DTL.getOriginalLoc();
6035 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6036 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6037 << ATL.getLocalSourceRange();
6038}
6039
6040/// CheckStaticArrayArgument - If the given argument corresponds to a static
6041/// array parameter, check that it is non-null, and that if it is formed by
6042/// array-to-pointer decay, the underlying array is sufficiently large.
6043///
6044/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6045/// array type derivation, then for each call to the function, the value of the
6046/// corresponding actual argument shall provide access to the first element of
6047/// an array with at least as many elements as specified by the size expression.
6048void
6049Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6050 ParmVarDecl *Param,
6051 const Expr *ArgExpr) {
6052 // Static array parameters are not supported in C++.
6053 if (!Param || getLangOpts().CPlusPlus)
6054 return;
6055
6056 QualType OrigTy = Param->getOriginalType();
6057
6058 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6059 if (!AT || AT->getSizeModifier() != ArrayType::Static)
6060 return;
6061
6062 if (ArgExpr->isNullPointerConstant(Context,
6063 Expr::NPC_NeverValueDependent)) {
6064 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6065 DiagnoseCalleeStaticArrayParam(*this, Param);
6066 return;
6067 }
6068
6069 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6070 if (!CAT)
6071 return;
6072
6073 const ConstantArrayType *ArgCAT =
6074 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6075 if (!ArgCAT)
6076 return;
6077
6078 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6079 ArgCAT->getElementType())) {
6080 if (ArgCAT->getSize().ult(CAT->getSize())) {
6081 Diag(CallLoc, diag::warn_static_array_too_small)
6082 << ArgExpr->getSourceRange()
6083 << (unsigned)ArgCAT->getSize().getZExtValue()
6084 << (unsigned)CAT->getSize().getZExtValue() << 0;
6085 DiagnoseCalleeStaticArrayParam(*this, Param);
6086 }
6087 return;
6088 }
6089
6090 Optional<CharUnits> ArgSize =
6091 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6092 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6093 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6094 Diag(CallLoc, diag::warn_static_array_too_small)
6095 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6096 << (unsigned)ParmSize->getQuantity() << 1;
6097 DiagnoseCalleeStaticArrayParam(*this, Param);
6098 }
6099}
6100
6101/// Given a function expression of unknown-any type, try to rebuild it