Bug Summary

File:clang/lib/Sema/SemaExpr.cpp
Warning:line 1359, column 11
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>();
27
Assuming the object is not a 'BuiltinType'
28
'BTy' initialized to a null pointer value
1357 assert(BTy && "Expected a builtin type.")(static_cast<void> (0));
1358
1359 switch (BTy->getKind()) {
29
Called C++ object pointer is null
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);
26
Calling 'GetFixedPointRank'
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
4.1
'ACK' is not equal to ACK_CompAssign
!= ACK_CompAssign) {
5
Taking true branch
1505 LHS = UsualUnaryConversions(LHS.get());
1506 if (LHS.isInvalid())
6
Assuming the condition is false
7
Taking false branch
1507 return QualType();
1508 }
1509
1510 RHS = UsualUnaryConversions(RHS.get());
1511 if (RHS.isInvalid())
8
Assuming the condition is false
9
Taking false branch
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
10.1
'AtomicLHS' is null
= LHSType->getAs<AtomicType>())
10
Assuming the object is not a 'AtomicType'
11
Taking false branch
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())
12
Assuming the condition is false
13
Assuming the condition is false
14
Taking false branch
1532 return QualType();
1533
1534 // Apply unary and bitfield promotions to the LHS's type.
1535 QualType LHSUnpromotedType = LHSType;
1536 if (LHSType->isPromotableIntegerType())
15
Assuming the condition is false
16
Taking false branch
1537 LHSType = Context.getPromotedIntegerType(LHSType);
1538 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1539 if (!LHSBitfieldPromoteTy.isNull())
17
Taking true branch
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)
18
Taking false branch
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())
19
Assuming the condition is false
20
Assuming the condition is false
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())
21
Assuming the condition is false
22
Assuming the condition is false
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())
23
Assuming the condition is false
24
Assuming the condition is false
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);
25
Calling 'handleFixedPointConversion'
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
6102/// to have a function type.
6103static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6104
6105/// Is the given type a placeholder that we need to lower out
6106/// immediately during argument processing?
6107static bool isPlaceholderToRemoveAsArg(QualType type) {
6108 // Placeholders are never sugared.
6109 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6110 if (!placeholder) return false;
6111
6112 switch (placeholder->getKind()) {
6113 // Ignore all the non-placeholder types.
6114#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6115 case BuiltinType::Id:
6116#include "clang/Basic/OpenCLImageTypes.def"
6117#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6118 case BuiltinType::Id:
6119#include "clang/Basic/OpenCLExtensionTypes.def"
6120 // In practice we'll never use this, since all SVE types are sugared
6121 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6122#define SVE_TYPE(Name, Id, SingletonId) \
6123 case BuiltinType::Id:
6124#include "clang/Basic/AArch64SVEACLETypes.def"
6125#define PPC_VECTOR_TYPE(Name, Id, Size) \
6126 case BuiltinType::Id:
6127#include "clang/Basic/PPCTypes.def"
6128#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6129#include "clang/Basic/RISCVVTypes.def"
6130#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6131#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6132#include "clang/AST/BuiltinTypes.def"
6133 return false;
6134
6135 // We cannot lower out overload sets; they might validly be resolved
6136 // by the call machinery.
6137 case BuiltinType::Overload:
6138 return false;
6139
6140 // Unbridged casts in ARC can be handled in some call positions and
6141 // should be left in place.
6142 case BuiltinType::ARCUnbridgedCast:
6143 return false;
6144
6145 // Pseudo-objects should be converted as soon as possible.
6146 case BuiltinType::PseudoObject:
6147 return true;
6148
6149 // The debugger mode could theoretically but currently does not try
6150 // to resolve unknown-typed arguments based on known parameter types.
6151 case BuiltinType::UnknownAny:
6152 return true;
6153
6154 // These are always invalid as call arguments and should be reported.
6155 case BuiltinType::BoundMember:
6156 case BuiltinType::BuiltinFn:
6157 case BuiltinType::IncompleteMatrixIdx:
6158 case BuiltinType::OMPArraySection:
6159 case BuiltinType::OMPArrayShaping:
6160 case BuiltinType::OMPIterator:
6161 return true;
6162
6163 }
6164 llvm_unreachable("bad builtin type kind")__builtin_unreachable();
6165}
6166
6167/// Check an argument list for placeholders that we won't try to
6168/// handle later.
6169static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6170 // Apply this processing to all the arguments at once instead of
6171 // dying at the first failure.
6172 bool hasInvalid = false;
6173 for (size_t i = 0, e = args.size(); i != e; i++) {
6174 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6175 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6176 if (result.isInvalid()) hasInvalid = true;
6177 else args[i] = result.get();
6178 }
6179 }
6180 return hasInvalid;
6181}
6182
6183/// If a builtin function has a pointer argument with no explicit address
6184/// space, then it should be able to accept a pointer to any address
6185/// space as input. In order to do this, we need to replace the
6186/// standard builtin declaration with one that uses the same address space
6187/// as the call.
6188///
6189/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6190/// it does not contain any pointer arguments without
6191/// an address space qualifer. Otherwise the rewritten
6192/// FunctionDecl is returned.
6193/// TODO: Handle pointer return types.
6194static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6195 FunctionDecl *FDecl,
6196 MultiExprArg ArgExprs) {
6197
6198 QualType DeclType = FDecl->getType();
6199 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6200
6201 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6202 ArgExprs.size() < FT->getNumParams())
6203 return nullptr;
6204
6205 bool NeedsNewDecl = false;
6206 unsigned i = 0;
6207 SmallVector<QualType, 8> OverloadParams;
6208
6209 for (QualType ParamType : FT->param_types()) {
6210
6211 // Convert array arguments to pointer to simplify type lookup.
6212 ExprResult ArgRes =
6213 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6214 if (ArgRes.isInvalid())
6215 return nullptr;
6216 Expr *Arg = ArgRes.get();
6217 QualType ArgType = Arg->getType();
6218 if (!ParamType->isPointerType() ||
6219 ParamType.hasAddressSpace() ||
6220 !ArgType->isPointerType() ||
6221 !ArgType->getPointeeType().hasAddressSpace()) {
6222 OverloadParams.push_back(ParamType);
6223 continue;
6224 }
6225
6226 QualType PointeeType = ParamType->getPointeeType();
6227 if (PointeeType.hasAddressSpace())
6228 continue;
6229
6230 NeedsNewDecl = true;
6231 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6232
6233 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6234 OverloadParams.push_back(Context.getPointerType(PointeeType));
6235 }
6236
6237 if (!NeedsNewDecl)
6238 return nullptr;
6239
6240 FunctionProtoType::ExtProtoInfo EPI;
6241 EPI.Variadic = FT->isVariadic();
6242 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6243 OverloadParams, EPI);
6244 DeclContext *Parent = FDecl->getParent();
6245 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6246 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6247 FDecl->getIdentifier(), OverloadTy,
6248 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6249 false,
6250 /*hasPrototype=*/true);
6251 SmallVector<ParmVarDecl*, 16> Params;
6252 FT = cast<FunctionProtoType>(OverloadTy);
6253 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6254 QualType ParamType = FT->getParamType(i);
6255 ParmVarDecl *Parm =
6256 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6257 SourceLocation(), nullptr, ParamType,
6258 /*TInfo=*/nullptr, SC_None, nullptr);
6259 Parm->setScopeInfo(0, i);
6260 Params.push_back(Parm);
6261 }
6262 OverloadDecl->setParams(Params);
6263 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6264 return OverloadDecl;
6265}
6266
6267static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6268 FunctionDecl *Callee,
6269 MultiExprArg ArgExprs) {
6270 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6271 // similar attributes) really don't like it when functions are called with an
6272 // invalid number of args.
6273 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6274 /*PartialOverloading=*/false) &&
6275 !Callee->isVariadic())
6276 return;
6277 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6278 return;
6279
6280 if (const EnableIfAttr *Attr =
6281 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6282 S.Diag(Fn->getBeginLoc(),
6283 isa<CXXMethodDecl>(Callee)
6284 ? diag::err_ovl_no_viable_member_function_in_call
6285 : diag::err_ovl_no_viable_function_in_call)
6286 << Callee << Callee->getSourceRange();
6287 S.Diag(Callee->getLocation(),
6288 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6289 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6290 return;
6291 }
6292}
6293
6294static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6295 const UnresolvedMemberExpr *const UME, Sema &S) {
6296
6297 const auto GetFunctionLevelDCIfCXXClass =
6298 [](Sema &S) -> const CXXRecordDecl * {
6299 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6300 if (!DC || !DC->getParent())
6301 return nullptr;
6302
6303 // If the call to some member function was made from within a member
6304 // function body 'M' return return 'M's parent.
6305 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6306 return MD->getParent()->getCanonicalDecl();
6307 // else the call was made from within a default member initializer of a
6308 // class, so return the class.
6309 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6310 return RD->getCanonicalDecl();
6311 return nullptr;
6312 };
6313 // If our DeclContext is neither a member function nor a class (in the
6314 // case of a lambda in a default member initializer), we can't have an
6315 // enclosing 'this'.
6316
6317 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6318 if (!CurParentClass)
6319 return false;
6320
6321 // The naming class for implicit member functions call is the class in which
6322 // name lookup starts.
6323 const CXXRecordDecl *const NamingClass =
6324 UME->getNamingClass()->getCanonicalDecl();
6325 assert(NamingClass && "Must have naming class even for implicit access")(static_cast<void> (0));
6326
6327 // If the unresolved member functions were found in a 'naming class' that is
6328 // related (either the same or derived from) to the class that contains the
6329 // member function that itself contained the implicit member access.
6330
6331 return CurParentClass == NamingClass ||
6332 CurParentClass->isDerivedFrom(NamingClass);
6333}
6334
6335static void
6336tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6337 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6338
6339 if (!UME)
6340 return;
6341
6342 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6343 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6344 // already been captured, or if this is an implicit member function call (if
6345 // it isn't, an attempt to capture 'this' should already have been made).
6346 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6347 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6348 return;
6349
6350 // Check if the naming class in which the unresolved members were found is
6351 // related (same as or is a base of) to the enclosing class.
6352
6353 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6354 return;
6355
6356
6357 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6358 // If the enclosing function is not dependent, then this lambda is
6359 // capture ready, so if we can capture this, do so.
6360 if (!EnclosingFunctionCtx->isDependentContext()) {
6361 // If the current lambda and all enclosing lambdas can capture 'this' -
6362 // then go ahead and capture 'this' (since our unresolved overload set
6363 // contains at least one non-static member function).
6364 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6365 S.CheckCXXThisCapture(CallLoc);
6366 } else if (S.CurContext->isDependentContext()) {
6367 // ... since this is an implicit member reference, that might potentially
6368 // involve a 'this' capture, mark 'this' for potential capture in
6369 // enclosing lambdas.
6370 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6371 CurLSI->addPotentialThisCapture(CallLoc);
6372 }
6373}
6374
6375ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6376 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6377 Expr *ExecConfig) {
6378 ExprResult Call =
6379 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6380 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6381 if (Call.isInvalid())
6382 return Call;
6383
6384 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6385 // language modes.
6386 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6387 if (ULE->hasExplicitTemplateArgs() &&
6388 ULE->decls_begin() == ULE->decls_end()) {
6389 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6390 ? diag::warn_cxx17_compat_adl_only_template_id
6391 : diag::ext_adl_only_template_id)
6392 << ULE->getName();
6393 }
6394 }
6395
6396 if (LangOpts.OpenMP)
6397 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6398 ExecConfig);
6399
6400 return Call;
6401}
6402
6403/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6404/// This provides the location of the left/right parens and a list of comma
6405/// locations.
6406ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6407 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6408 Expr *ExecConfig, bool IsExecConfig,
6409 bool AllowRecovery) {
6410 // Since this might be a postfix expression, get rid of ParenListExprs.
6411 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6412 if (Result.isInvalid()) return ExprError();
6413 Fn = Result.get();
6414
6415 if (checkArgsForPlaceholders(*this, ArgExprs))
6416 return ExprError();
6417
6418 if (getLangOpts().CPlusPlus) {
6419 // If this is a pseudo-destructor expression, build the call immediately.
6420 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6421 if (!ArgExprs.empty()) {
6422 // Pseudo-destructor calls should not have any arguments.
6423 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6424 << FixItHint::CreateRemoval(
6425 SourceRange(ArgExprs.front()->getBeginLoc(),
6426 ArgExprs.back()->getEndLoc()));
6427 }
6428
6429 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6430 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6431 }
6432 if (Fn->getType() == Context.PseudoObjectTy) {
6433 ExprResult result = CheckPlaceholderExpr(Fn);
6434 if (result.isInvalid()) return ExprError();
6435 Fn = result.get();
6436 }
6437
6438 // Determine whether this is a dependent call inside a C++ template,
6439 // in which case we won't do any semantic analysis now.
6440 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6441 if (ExecConfig) {
6442 return CUDAKernelCallExpr::Create(Context, Fn,
6443 cast<CallExpr>(ExecConfig), ArgExprs,
6444 Context.DependentTy, VK_PRValue,
6445 RParenLoc, CurFPFeatureOverrides());
6446 } else {
6447
6448 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6449 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6450 Fn->getBeginLoc());
6451
6452 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6453 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6454 }
6455 }
6456
6457 // Determine whether this is a call to an object (C++ [over.call.object]).
6458 if (Fn->getType()->isRecordType())
6459 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6460 RParenLoc);
6461
6462 if (Fn->getType() == Context.UnknownAnyTy) {
6463 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6464 if (result.isInvalid()) return ExprError();
6465 Fn = result.get();
6466 }
6467
6468 if (Fn->getType() == Context.BoundMemberTy) {
6469 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6470 RParenLoc, AllowRecovery);
6471 }
6472 }
6473
6474 // Check for overloaded calls. This can happen even in C due to extensions.
6475 if (Fn->getType() == Context.OverloadTy) {
6476 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6477
6478 // We aren't supposed to apply this logic if there's an '&' involved.
6479 if (!find.HasFormOfMemberPointer) {
6480 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6481 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6482 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6483 OverloadExpr *ovl = find.Expression;
6484 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6485 return BuildOverloadedCallExpr(
6486 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6487 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6488 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6489 RParenLoc, AllowRecovery);
6490 }
6491 }
6492
6493 // If we're directly calling a function, get the appropriate declaration.
6494 if (Fn->getType() == Context.UnknownAnyTy) {
6495 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6496 if (result.isInvalid()) return ExprError();
6497 Fn = result.get();
6498 }
6499
6500 Expr *NakedFn = Fn->IgnoreParens();
6501
6502 bool CallingNDeclIndirectly = false;
6503 NamedDecl *NDecl = nullptr;
6504 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6505 if (UnOp->getOpcode() == UO_AddrOf) {
6506 CallingNDeclIndirectly = true;
6507 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6508 }
6509 }
6510
6511 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6512 NDecl = DRE->getDecl();
6513
6514 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6515 if (FDecl && FDecl->getBuiltinID()) {
6516 // Rewrite the function decl for this builtin by replacing parameters
6517 // with no explicit address space with the address space of the arguments
6518 // in ArgExprs.
6519 if ((FDecl =
6520 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6521 NDecl = FDecl;
6522 Fn = DeclRefExpr::Create(
6523 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6524 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6525 nullptr, DRE->isNonOdrUse());
6526 }
6527 }
6528 } else if (isa<MemberExpr>(NakedFn))
6529 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6530
6531 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6532 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6533 FD, /*Complain=*/true, Fn->getBeginLoc()))
6534 return ExprError();
6535
6536 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6537
6538 // If this expression is a call to a builtin function in HIP device
6539 // compilation, allow a pointer-type argument to default address space to be
6540 // passed as a pointer-type parameter to a non-default address space.
6541 // If Arg is declared in the default address space and Param is declared
6542 // in a non-default address space, perform an implicit address space cast to
6543 // the parameter type.
6544 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6545 FD->getBuiltinID()) {
6546 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6547 ParmVarDecl *Param = FD->getParamDecl(Idx);
6548 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6549 !ArgExprs[Idx]->getType()->isPointerType())
6550 continue;
6551
6552 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6553 auto ArgTy = ArgExprs[Idx]->getType();
6554 auto ArgPtTy = ArgTy->getPointeeType();
6555 auto ArgAS = ArgPtTy.getAddressSpace();
6556
6557 // Only allow implicit casting from a non-default address space pointee
6558 // type to a default address space pointee type
6559 if (ArgAS != LangAS::Default || ParamAS == LangAS::Default)
6560 continue;
6561
6562 // First, ensure that the Arg is an RValue.
6563 if (ArgExprs[Idx]->isGLValue()) {
6564 ArgExprs[Idx] = ImplicitCastExpr::Create(
6565 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6566 nullptr, VK_PRValue, FPOptionsOverride());
6567 }
6568
6569 // Construct a new arg type with address space of Param
6570 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6571 ArgPtQuals.setAddressSpace(ParamAS);
6572 auto NewArgPtTy =
6573 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6574 auto NewArgTy =
6575 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6576 ArgTy.getQualifiers());
6577
6578 // Finally perform an implicit address space cast
6579 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6580 CK_AddressSpaceConversion)
6581 .get();
6582 }
6583 }
6584 }
6585
6586 if (Context.isDependenceAllowed() &&
6587 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6588 assert(!getLangOpts().CPlusPlus)(static_cast<void> (0));
6589 assert((Fn->containsErrors() ||(static_cast<void> (0))
6590 llvm::any_of(ArgExprs,(static_cast<void> (0))
6591 [](clang::Expr *E) { return E->containsErrors(); })) &&(static_cast<void> (0))
6592 "should only occur in error-recovery path.")(static_cast<void> (0));
6593 QualType ReturnType =
6594 llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6595 ? cast<FunctionDecl>(NDecl)->getCallResultType()
6596 : Context.DependentTy;
6597 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6598 Expr::getValueKindForType(ReturnType), RParenLoc,
6599 CurFPFeatureOverrides());
6600 }
6601 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6602 ExecConfig, IsExecConfig);
6603}
6604
6605/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6606// with the specified CallArgs
6607Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6608 MultiExprArg CallArgs) {
6609 StringRef Name = Context.BuiltinInfo.getName(Id);
6610 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6611 Sema::LookupOrdinaryName);
6612 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6613
6614 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6615 assert(BuiltInDecl && "failed to find builtin declaration")(static_cast<void> (0));
6616
6617 ExprResult DeclRef =
6618 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6619 assert(DeclRef.isUsable() && "Builtin reference cannot fail")(static_cast<void> (0));
6620
6621 ExprResult Call =
6622 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6623
6624 assert(!Call.isInvalid() && "Call to builtin cannot fail!")(static_cast<void> (0));
6625 return Call.get();
6626}
6627
6628/// Parse a __builtin_astype expression.
6629///
6630/// __builtin_astype( value, dst type )
6631///
6632ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6633 SourceLocation BuiltinLoc,
6634 SourceLocation RParenLoc) {
6635 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6636 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6637}
6638
6639/// Create a new AsTypeExpr node (bitcast) from the arguments.
6640ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6641 SourceLocation BuiltinLoc,
6642 SourceLocation RParenLoc) {
6643 ExprValueKind VK = VK_PRValue;
6644 ExprObjectKind OK = OK_Ordinary;
6645 QualType SrcTy = E->getType();
6646 if (!SrcTy->isDependentType() &&
6647 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6648 return ExprError(
6649 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6650 << DestTy << SrcTy << E->getSourceRange());
6651 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6652}
6653
6654/// ActOnConvertVectorExpr - create a new convert-vector expression from the
6655/// provided arguments.
6656///
6657/// __builtin_convertvector( value, dst type )
6658///
6659ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6660 SourceLocation BuiltinLoc,
6661 SourceLocation RParenLoc) {
6662 TypeSourceInfo *TInfo;
6663 GetTypeFromParser(ParsedDestTy, &TInfo);
6664 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6665}
6666
6667/// BuildResolvedCallExpr - Build a call to a resolved expression,
6668/// i.e. an expression not of \p OverloadTy. The expression should
6669/// unary-convert to an expression of function-pointer or
6670/// block-pointer type.
6671///
6672/// \param NDecl the declaration being called, if available
6673ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6674 SourceLocation LParenLoc,
6675 ArrayRef<Expr *> Args,
6676 SourceLocation RParenLoc, Expr *Config,
6677 bool IsExecConfig, ADLCallKind UsesADL) {
6678 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6679 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6680
6681 // Functions with 'interrupt' attribute cannot be called directly.
6682 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6683 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6684 return ExprError();
6685 }
6686
6687 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6688 // so there's some risk when calling out to non-interrupt handler functions
6689 // that the callee might not preserve them. This is easy to diagnose here,
6690 // but can be very challenging to debug.
6691 // Likewise, X86 interrupt handlers may only call routines with attribute
6692 // no_caller_saved_registers since there is no efficient way to
6693 // save and restore the non-GPR state.
6694 if (auto *Caller = getCurFunctionDecl()) {
6695 if (Caller->hasAttr<ARMInterruptAttr>()) {
6696 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6697 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6698 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6699 if (FDecl)
6700 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6701 }
6702 }
6703 if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6704 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6705 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6706 if (FDecl)
6707 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6708 }
6709 }
6710
6711 // Promote the function operand.
6712 // We special-case function promotion here because we only allow promoting
6713 // builtin functions to function pointers in the callee of a call.
6714 ExprResult Result;
6715 QualType ResultTy;
6716 if (BuiltinID &&
6717 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6718 // Extract the return type from the (builtin) function pointer type.
6719 // FIXME Several builtins still have setType in
6720 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6721 // Builtins.def to ensure they are correct before removing setType calls.
6722 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6723 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6724 ResultTy = FDecl->getCallResultType();
6725 } else {
6726 Result = CallExprUnaryConversions(Fn);
6727 ResultTy = Context.BoolTy;
6728 }
6729 if (Result.isInvalid())
6730 return ExprError();
6731 Fn = Result.get();
6732
6733 // Check for a valid function type, but only if it is not a builtin which
6734 // requires custom type checking. These will be handled by
6735 // CheckBuiltinFunctionCall below just after creation of the call expression.
6736 const FunctionType *FuncT = nullptr;
6737 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6738 retry:
6739 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6740 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6741 // have type pointer to function".
6742 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6743 if (!FuncT)
6744 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6745 << Fn->getType() << Fn->getSourceRange());
6746 } else if (const BlockPointerType *BPT =
6747 Fn->getType()->getAs<BlockPointerType>()) {
6748 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6749 } else {
6750 // Handle calls to expressions of unknown-any type.
6751 if (Fn->getType() == Context.UnknownAnyTy) {
6752 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6753 if (rewrite.isInvalid())
6754 return ExprError();
6755 Fn = rewrite.get();
6756 goto retry;
6757 }
6758
6759 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6760 << Fn->getType() << Fn->getSourceRange());
6761 }
6762 }
6763
6764 // Get the number of parameters in the function prototype, if any.
6765 // We will allocate space for max(Args.size(), NumParams) arguments
6766 // in the call expression.
6767 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6768 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6769
6770 CallExpr *TheCall;
6771 if (Config) {
6772 assert(UsesADL == ADLCallKind::NotADL &&(static_cast<void> (0))
6773 "CUDAKernelCallExpr should not use ADL")(static_cast<void> (0));
6774 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6775 Args, ResultTy, VK_PRValue, RParenLoc,
6776 CurFPFeatureOverrides(), NumParams);
6777 } else {
6778 TheCall =
6779 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6780 CurFPFeatureOverrides(), NumParams, UsesADL);
6781 }
6782
6783 if (!Context.isDependenceAllowed()) {
6784 // Forget about the nulled arguments since typo correction
6785 // do not handle them well.
6786 TheCall->shrinkNumArgs(Args.size());
6787 // C cannot always handle TypoExpr nodes in builtin calls and direct
6788 // function calls as their argument checking don't necessarily handle
6789 // dependent types properly, so make sure any TypoExprs have been
6790 // dealt with.
6791 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6792 if (!Result.isUsable()) return ExprError();
6793 CallExpr *TheOldCall = TheCall;
6794 TheCall = dyn_cast<CallExpr>(Result.get());
6795 bool CorrectedTypos = TheCall != TheOldCall;
6796 if (!TheCall) return Result;
6797 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6798
6799 // A new call expression node was created if some typos were corrected.
6800 // However it may not have been constructed with enough storage. In this
6801 // case, rebuild the node with enough storage. The waste of space is
6802 // immaterial since this only happens when some typos were corrected.
6803 if (CorrectedTypos && Args.size() < NumParams) {
6804 if (Config)
6805 TheCall = CUDAKernelCallExpr::Create(
6806 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6807 RParenLoc, CurFPFeatureOverrides(), NumParams);
6808 else
6809 TheCall =
6810 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6811 CurFPFeatureOverrides(), NumParams, UsesADL);
6812 }
6813 // We can now handle the nulled arguments for the default arguments.
6814 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6815 }
6816
6817 // Bail out early if calling a builtin with custom type checking.
6818 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6819 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6820
6821 if (getLangOpts().CUDA) {
6822 if (Config) {
6823 // CUDA: Kernel calls must be to global functions
6824 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6825 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6826 << FDecl << Fn->getSourceRange());
6827
6828 // CUDA: Kernel function must have 'void' return type
6829 if (!FuncT->getReturnType()->isVoidType() &&
6830 !FuncT->getReturnType()->getAs<AutoType>() &&
6831 !FuncT->getReturnType()->isInstantiationDependentType())
6832 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6833 << Fn->getType() << Fn->getSourceRange());
6834 } else {
6835 // CUDA: Calls to global functions must be configured
6836 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6837 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6838 << FDecl << Fn->getSourceRange());
6839 }
6840 }
6841
6842 // Check for a valid return type
6843 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6844 FDecl))
6845 return ExprError();
6846
6847 // We know the result type of the call, set it.
6848 TheCall->setType(FuncT->getCallResultType(Context));
6849 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6850
6851 if (Proto) {
6852 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6853 IsExecConfig))
6854 return ExprError();
6855 } else {
6856 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")(static_cast<void> (0));
6857
6858 if (FDecl) {
6859 // Check if we have too few/too many template arguments, based
6860 // on our knowledge of the function definition.
6861 const FunctionDecl *Def = nullptr;
6862 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6863 Proto = Def->getType()->getAs<FunctionProtoType>();
6864 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6865 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6866 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6867 }
6868
6869 // If the function we're calling isn't a function prototype, but we have
6870 // a function prototype from a prior declaratiom, use that prototype.
6871 if (!FDecl->hasPrototype())
6872 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6873 }
6874
6875 // Promote the arguments (C99 6.5.2.2p6).
6876 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6877 Expr *Arg = Args[i];
6878
6879 if (Proto && i < Proto->getNumParams()) {
6880 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6881 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6882 ExprResult ArgE =
6883 PerformCopyInitialization(Entity, SourceLocation(), Arg);
6884 if (ArgE.isInvalid())
6885 return true;
6886
6887 Arg = ArgE.getAs<Expr>();
6888
6889 } else {
6890 ExprResult ArgE = DefaultArgumentPromotion(Arg);
6891
6892 if (ArgE.isInvalid())
6893 return true;
6894
6895 Arg = ArgE.getAs<Expr>();
6896 }
6897
6898 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6899 diag::err_call_incomplete_argument, Arg))
6900 return ExprError();
6901
6902 TheCall->setArg(i, Arg);
6903 }
6904 TheCall->computeDependence();
6905 }
6906
6907 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6908 if (!Method->isStatic())
6909 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6910 << Fn->getSourceRange());
6911
6912 // Check for sentinels
6913 if (NDecl)
6914 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6915
6916 // Warn for unions passing across security boundary (CMSE).
6917 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6918 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6919 if (const auto *RT =
6920 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6921 if (RT->getDecl()->isOrContainsUnion())
6922 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6923 << 0 << i;
6924 }
6925 }
6926 }
6927
6928 // Do special checking on direct calls to functions.
6929 if (FDecl) {
6930 if (CheckFunctionCall(FDecl, TheCall, Proto))
6931 return ExprError();
6932
6933 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6934
6935 if (BuiltinID)
6936 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6937 } else if (NDecl) {
6938 if (CheckPointerCall(NDecl, TheCall, Proto))
6939 return ExprError();
6940 } else {
6941 if (CheckOtherCall(TheCall, Proto))
6942 return ExprError();
6943 }
6944
6945 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6946}
6947
6948ExprResult
6949Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6950 SourceLocation RParenLoc, Expr *InitExpr) {
6951 assert(Ty && "ActOnCompoundLiteral(): missing type")(static_cast<void> (0));
6952 assert(InitExpr && "ActOnCompoundLiteral(): missing expression")(static_cast<void> (0));
6953
6954 TypeSourceInfo *TInfo;
6955 QualType literalType = GetTypeFromParser(Ty, &TInfo);
6956 if (!TInfo)
6957 TInfo = Context.getTrivialTypeSourceInfo(literalType);
6958
6959 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6960}
6961
6962ExprResult
6963Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6964 SourceLocation RParenLoc, Expr *LiteralExpr) {
6965 QualType literalType = TInfo->getType();
6966
6967 if (literalType->isArrayType()) {
6968 if (RequireCompleteSizedType(
6969 LParenLoc, Context.getBaseElementType(literalType),
6970 diag::err_array_incomplete_or_sizeless_type,
6971 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6972 return ExprError();
6973 if (literalType->isVariableArrayType()) {
6974 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
6975 diag::err_variable_object_no_init)) {
6976 return ExprError();
6977 }
6978 }
6979 } else if (!literalType->isDependentType() &&
6980 RequireCompleteType(LParenLoc, literalType,
6981 diag::err_typecheck_decl_incomplete_type,
6982 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6983 return ExprError();
6984
6985 InitializedEntity Entity
6986 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6987 InitializationKind Kind
6988 = InitializationKind::CreateCStyleCast(LParenLoc,
6989 SourceRange(LParenLoc, RParenLoc),
6990 /*InitList=*/true);
6991 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6992 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6993 &literalType);
6994 if (Result.isInvalid())
6995 return ExprError();
6996 LiteralExpr = Result.get();
6997
6998 bool isFileScope = !CurContext->isFunctionOrMethod();
6999
7000 // In C, compound literals are l-values for some reason.
7001 // For GCC compatibility, in C++, file-scope array compound literals with
7002 // constant initializers are also l-values, and compound literals are
7003 // otherwise prvalues.
7004 //
7005 // (GCC also treats C++ list-initialized file-scope array prvalues with
7006 // constant initializers as l-values, but that's non-conforming, so we don't
7007 // follow it there.)
7008 //
7009 // FIXME: It would be better to handle the lvalue cases as materializing and
7010 // lifetime-extending a temporary object, but our materialized temporaries
7011 // representation only supports lifetime extension from a variable, not "out
7012 // of thin air".
7013 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7014 // is bound to the result of applying array-to-pointer decay to the compound
7015 // literal.
7016 // FIXME: GCC supports compound literals of reference type, which should
7017 // obviously have a value kind derived from the kind of reference involved.
7018 ExprValueKind VK =
7019 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7020 ? VK_PRValue
7021 : VK_LValue;
7022
7023 if (isFileScope)
7024 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7025 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7026 Expr *Init = ILE->getInit(i);
7027 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7028 }
7029
7030 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7031 VK, LiteralExpr, isFileScope);
7032 if (isFileScope) {
7033 if (!LiteralExpr->isTypeDependent() &&
7034 !LiteralExpr->isValueDependent() &&
7035 !literalType->isDependentType()) // C99 6.5.2.5p3
7036 if (CheckForConstantInitializer(LiteralExpr, literalType))
7037 return ExprError();
7038 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7039 literalType.getAddressSpace() != LangAS::Default) {
7040 // Embedded-C extensions to C99 6.5.2.5:
7041 // "If the compound literal occurs inside the body of a function, the
7042 // type name shall not be qualified by an address-space qualifier."
7043 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7044 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7045 return ExprError();
7046 }
7047
7048 if (!isFileScope && !getLangOpts().CPlusPlus) {
7049 // Compound literals that have automatic storage duration are destroyed at
7050 // the end of the scope in C; in C++, they're just temporaries.
7051
7052 // Emit diagnostics if it is or contains a C union type that is non-trivial
7053 // to destruct.
7054 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7055 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7056 NTCUC_CompoundLiteral, NTCUK_Destruct);
7057
7058 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7059 if (literalType.isDestructedType()) {
7060 Cleanup.setExprNeedsCleanups(true);
7061 ExprCleanupObjects.push_back(E);
7062 getCurFunction()->setHasBranchProtectedScope();
7063 }
7064 }
7065
7066 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7067 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7068 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7069 E->getInitializer()->getExprLoc());
7070
7071 return MaybeBindToTemporary(E);
7072}
7073
7074ExprResult
7075Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7076 SourceLocation RBraceLoc) {
7077 // Only produce each kind of designated initialization diagnostic once.
7078 SourceLocation FirstDesignator;
7079 bool DiagnosedArrayDesignator = false;
7080 bool DiagnosedNestedDesignator = false;
7081 bool DiagnosedMixedDesignator = false;
7082
7083 // Check that any designated initializers are syntactically valid in the
7084 // current language mode.
7085 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7086 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7087 if (FirstDesignator.isInvalid())
7088 FirstDesignator = DIE->getBeginLoc();
7089
7090 if (!getLangOpts().CPlusPlus)
7091 break;
7092
7093 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7094 DiagnosedNestedDesignator = true;
7095 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7096 << DIE->getDesignatorsSourceRange();
7097 }
7098
7099 for (auto &Desig : DIE->designators()) {
7100 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7101 DiagnosedArrayDesignator = true;
7102 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7103 << Desig.getSourceRange();
7104 }
7105 }
7106
7107 if (!DiagnosedMixedDesignator &&
7108 !isa<DesignatedInitExpr>(InitArgList[0])) {
7109 DiagnosedMixedDesignator = true;
7110 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7111 << DIE->getSourceRange();
7112 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7113 << InitArgList[0]->getSourceRange();
7114 }
7115 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7116 isa<DesignatedInitExpr>(InitArgList[0])) {
7117 DiagnosedMixedDesignator = true;
7118 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7119 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7120 << DIE->getSourceRange();
7121 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7122 << InitArgList[I]->getSourceRange();
7123 }
7124 }
7125
7126 if (FirstDesignator.isValid()) {
7127 // Only diagnose designated initiaization as a C++20 extension if we didn't
7128 // already diagnose use of (non-C++20) C99 designator syntax.
7129 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7130 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7131 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7132 ? diag::warn_cxx17_compat_designated_init
7133 : diag::ext_cxx_designated_init);
7134 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7135 Diag(FirstDesignator, diag::ext_designated_init);
7136 }
7137 }
7138
7139 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7140}
7141
7142ExprResult
7143Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7144 SourceLocation RBraceLoc) {
7145 // Semantic analysis for initializers is done by ActOnDeclarator() and
7146 // CheckInitializer() - it requires knowledge of the object being initialized.
7147
7148 // Immediately handle non-overload placeholders. Overloads can be
7149 // resolved contextually, but everything else here can't.
7150 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7151 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7152 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7153
7154 // Ignore failures; dropping the entire initializer list because
7155 // of one failure would be terrible for indexing/etc.
7156 if (result.isInvalid()) continue;
7157
7158 InitArgList[I] = result.get();
7159 }
7160 }
7161
7162 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7163 RBraceLoc);
7164 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7165 return E;
7166}
7167
7168/// Do an explicit extend of the given block pointer if we're in ARC.
7169void Sema::maybeExtendBlockObject(ExprResult &E) {
7170 assert(E.get()->getType()->isBlockPointerType())(static_cast<void> (0));
7171 assert(E.get()->isPRValue())(static_cast<void> (0));
7172
7173 // Only do this in an r-value context.
7174 if (!getLangOpts().ObjCAutoRefCount) return;
7175
7176 E = ImplicitCastExpr::Create(
7177 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7178 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7179 Cleanup.setExprNeedsCleanups(true);
7180}
7181
7182/// Prepare a conversion of the given expression to an ObjC object
7183/// pointer type.
7184CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7185 QualType type = E.get()->getType();
7186 if (type->isObjCObjectPointerType()) {
7187 return CK_BitCast;
7188 } else if (type->isBlockPointerType()) {
7189 maybeExtendBlockObject(E);
7190 return CK_BlockPointerToObjCPointerCast;
7191 } else {
7192 assert(type->isPointerType())(static_cast<void> (0));
7193 return CK_CPointerToObjCPointerCast;
7194 }
7195}
7196
7197/// Prepares for a scalar cast, performing all the necessary stages
7198/// except the final cast and returning the kind required.
7199CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7200 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7201 // Also, callers should have filtered out the invalid cases with
7202 // pointers. Everything else should be possible.
7203
7204 QualType SrcTy = Src.get()->getType();
7205 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7206 return CK_NoOp;
7207
7208 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7209 case Type::STK_MemberPointer:
7210 llvm_unreachable("member pointer type in C")__builtin_unreachable();
7211
7212 case Type::STK_CPointer:
7213 case Type::STK_BlockPointer:
7214 case Type::STK_ObjCObjectPointer:
7215 switch (DestTy->getScalarTypeKind()) {
7216 case Type::STK_CPointer: {
7217 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7218 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7219 if (SrcAS != DestAS)
7220 return CK_AddressSpaceConversion;
7221 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7222 return CK_NoOp;
7223 return CK_BitCast;
7224 }
7225 case Type::STK_BlockPointer:
7226 return (SrcKind == Type::STK_BlockPointer
7227 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7228 case Type::STK_ObjCObjectPointer:
7229 if (SrcKind == Type::STK_ObjCObjectPointer)
7230 return CK_BitCast;
7231 if (SrcKind == Type::STK_CPointer)
7232 return CK_CPointerToObjCPointerCast;
7233 maybeExtendBlockObject(Src);
7234 return CK_BlockPointerToObjCPointerCast;
7235 case Type::STK_Bool:
7236 return CK_PointerToBoolean;
7237 case Type::STK_Integral:
7238 return CK_PointerToIntegral;
7239 case Type::STK_Floating:
7240 case Type::STK_FloatingComplex:
7241 case Type::STK_IntegralComplex:
7242 case Type::STK_MemberPointer:
7243 case Type::STK_FixedPoint:
7244 llvm_unreachable("illegal cast from pointer")__builtin_unreachable();
7245 }
7246 llvm_unreachable("Should have returned before this")__builtin_unreachable();
7247
7248 case Type::STK_FixedPoint:
7249 switch (DestTy->getScalarTypeKind()) {
7250 case Type::STK_FixedPoint:
7251 return CK_FixedPointCast;
7252 case Type::STK_Bool:
7253 return CK_FixedPointToBoolean;
7254 case Type::STK_Integral:
7255 return CK_FixedPointToIntegral;
7256 case Type::STK_Floating:
7257 return CK_FixedPointToFloating;
7258 case Type::STK_IntegralComplex:
7259 case Type::STK_FloatingComplex:
7260 Diag(Src.get()->getExprLoc(),
7261 diag::err_unimplemented_conversion_with_fixed_point_type)
7262 << DestTy;
7263 return CK_IntegralCast;
7264 case Type::STK_CPointer:
7265 case Type::STK_ObjCObjectPointer:
7266 case Type::STK_BlockPointer:
7267 case Type::STK_MemberPointer:
7268 llvm_unreachable("illegal cast to pointer type")__builtin_unreachable();
7269 }
7270 llvm_unreachable("Should have returned before this")__builtin_unreachable();
7271
7272 case Type::STK_Bool: // casting from bool is like casting from an integer
7273 case Type::STK_Integral:
7274 switch (DestTy->getScalarTypeKind()) {
7275 case Type::STK_CPointer:
7276 case Type::STK_ObjCObjectPointer:
7277 case Type::STK_BlockPointer:
7278 if (Src.get()->isNullPointerConstant(Context,
7279 Expr::NPC_ValueDependentIsNull))
7280 return CK_NullToPointer;
7281 return CK_IntegralToPointer;
7282 case Type::STK_Bool:
7283 return CK_IntegralToBoolean;
7284 case Type::STK_Integral:
7285 return CK_IntegralCast;
7286 case Type::STK_Floating:
7287 return CK_IntegralToFloating;
7288 case Type::STK_IntegralComplex:
7289 Src = ImpCastExprToType(Src.get(),
7290 DestTy->castAs<ComplexType>()->getElementType(),
7291 CK_IntegralCast);
7292 return CK_IntegralRealToComplex;
7293 case Type::STK_FloatingComplex:
7294 Src = ImpCastExprToType(Src.get(),
7295 DestTy->castAs<ComplexType>()->getElementType(),
7296 CK_IntegralToFloating);
7297 return CK_FloatingRealToComplex;
7298 case Type::STK_MemberPointer:
7299 llvm_unreachable("member pointer type in C")__builtin_unreachable();
7300 case Type::STK_FixedPoint:
7301 return CK_IntegralToFixedPoint;
7302 }
7303 llvm_unreachable("Should have returned before this")__builtin_unreachable();
7304
7305 case Type::STK_Floating:
7306 switch (DestTy->getScalarTypeKind()) {
7307 case Type::STK_Floating:
7308 return CK_FloatingCast;
7309 case Type::STK_Bool:
7310 return CK_FloatingToBoolean;
7311 case Type::STK_Integral:
7312 return CK_FloatingToIntegral;
7313 case Type::STK_FloatingComplex:
7314 Src = ImpCastExprToType(Src.get(),
7315 DestTy->castAs<ComplexType>()->getElementType(),
7316 CK_FloatingCast);
7317 return CK_FloatingRealToComplex;
7318 case Type::STK_IntegralComplex:
7319 Src = ImpCastExprToType(Src.get(),
7320 DestTy->castAs<ComplexType>()->getElementType(),
7321 CK_FloatingToIntegral);
7322 return CK_IntegralRealToComplex;
7323 case Type::STK_CPointer:
7324 case Type::STK_ObjCObjectPointer:
7325 case Type::STK_BlockPointer:
7326 llvm_unreachable("valid float->pointer cast?")__builtin_unreachable();
7327 case Type::STK_MemberPointer:
7328 llvm_unreachable("member pointer type in C")__builtin_unreachable();
7329 case Type::STK_FixedPoint:
7330 return CK_FloatingToFixedPoint;
7331 }
7332 llvm_unreachable("Should have returned before this")__builtin_unreachable();
7333
7334 case Type::STK_FloatingComplex:
7335 switch (DestTy->getScalarTypeKind()) {
7336 case Type::STK_FloatingComplex:
7337 return CK_FloatingComplexCast;
7338 case Type::STK_IntegralComplex:
7339 return CK_FloatingComplexToIntegralComplex;
7340 case Type::STK_Floating: {
7341 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7342 if (Context.hasSameType(ET, DestTy))
7343 return CK_FloatingComplexToReal;
7344 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7345 return CK_FloatingCast;
7346 }
7347 case Type::STK_Bool:
7348 return CK_FloatingComplexToBoolean;
7349 case Type::STK_Integral:
7350 Src = ImpCastExprToType(Src.get(),
7351 SrcTy->castAs<ComplexType>()->getElementType(),
7352 CK_FloatingComplexToReal);
7353 return CK_FloatingToIntegral;
7354 case Type::STK_CPointer:
7355 case Type::STK_ObjCObjectPointer:
7356 case Type::STK_BlockPointer:
7357 llvm_unreachable("valid complex float->pointer cast?")__builtin_unreachable();
7358 case Type::STK_MemberPointer:
7359 llvm_unreachable("member pointer type in C")__builtin_unreachable();
7360 case Type::STK_FixedPoint:
7361 Diag(Src.get()->getExprLoc(),
7362 diag::err_unimplemented_conversion_with_fixed_point_type)
7363 << SrcTy;
7364 return CK_IntegralCast;
7365 }
7366 llvm_unreachable("Should have returned before this")__builtin_unreachable();
7367
7368 case Type::STK_IntegralComplex:
7369 switch (DestTy->getScalarTypeKind()) {
7370 case Type::STK_FloatingComplex:
7371 return CK_IntegralComplexToFloatingComplex;
7372 case Type::STK_IntegralComplex:
7373 return CK_IntegralComplexCast;
7374 case Type::STK_Integral: {
7375 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7376 if (Context.hasSameType(ET, DestTy))
7377 return CK_IntegralComplexToReal;
7378 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7379 return CK_IntegralCast;
7380 }
7381 case Type::STK_Bool:
7382 return CK_IntegralComplexToBoolean;
7383 case Type::STK_Floating:
7384 Src = ImpCastExprToType(Src.get(),
7385 SrcTy->castAs<ComplexType>()->getElementType(),
7386 CK_IntegralComplexToReal);
7387 return CK_IntegralToFloating;
7388 case Type::STK_CPointer:
7389 case Type::STK_ObjCObjectPointer:
7390 case Type::STK_BlockPointer:
7391 llvm_unreachable("valid complex int->pointer cast?")__builtin_unreachable();
7392 case Type::STK_MemberPointer:
7393 llvm_unreachable("member pointer type in C")__builtin_unreachable();
7394 case Type::STK_FixedPoint:
7395 Diag(Src.get()->getExprLoc(),
7396 diag::err_unimplemented_conversion_with_fixed_point_type)
7397 << SrcTy;
7398 return CK_IntegralCast;
7399 }
7400 llvm_unreachable("Should have returned before this")__builtin_unreachable();
7401 }
7402
7403 llvm_unreachable("Unhandled scalar cast")__builtin_unreachable();
7404}
7405
7406static bool breakDownVectorType(QualType type, uint64_t &len,
7407 QualType &eltType) {
7408 // Vectors are simple.
7409 if (const VectorType *vecType = type->getAs<VectorType>()) {
7410 len = vecType->getNumElements();
7411 eltType = vecType->getElementType();
7412 assert(eltType->isScalarType())(static_cast<void> (0));
7413 return true;
7414 }
7415
7416 // We allow lax conversion to and from non-vector types, but only if
7417 // they're real types (i.e. non-complex, non-pointer scalar types).
7418 if (!type->isRealType()) return false;
7419
7420 len = 1;
7421 eltType = type;
7422 return true;
7423}
7424
7425/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7426/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7427/// allowed?
7428///
7429/// This will also return false if the two given types do not make sense from
7430/// the perspective of SVE bitcasts.
7431bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7432 assert(srcTy->isVectorType() || destTy->isVectorType())(static_cast<void> (0));
7433
7434 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7435 if (!FirstType->isSizelessBuiltinType())
7436 return false;
7437
7438 const auto *VecTy = SecondType->getAs<VectorType>();
7439 return VecTy &&
7440 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7441 };
7442
7443 return ValidScalableConversion(srcTy, destTy) ||
7444 ValidScalableConversion(destTy, srcTy);
7445}
7446
7447/// Are the two types matrix types and do they have the same dimensions i.e.
7448/// do they have the same number of rows and the same number of columns?
7449bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7450 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7451 return false;
7452
7453 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7454 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7455
7456 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7457 matSrcType->getNumColumns() == matDestType->getNumColumns();
7458}
7459
7460bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7461 assert(DestTy->isVectorType() || SrcTy->isVectorType())(static_cast<void> (0));
7462
7463 uint64_t SrcLen, DestLen;
7464 QualType SrcEltTy, DestEltTy;
7465 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7466 return false;
7467 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7468 return false;
7469
7470 // ASTContext::getTypeSize will return the size rounded up to a
7471 // power of 2, so instead of using that, we need to use the raw
7472 // element size multiplied by the element count.
7473 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7474 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7475
7476 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7477}
7478
7479/// Are the two types lax-compatible vector types? That is, given
7480/// that one of them is a vector, do they have equal storage sizes,
7481/// where the storage size is the number of elements times the element
7482/// size?
7483///
7484/// This will also return false if either of the types is neither a
7485/// vector nor a real type.
7486bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7487 assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast<void> (0));
7488
7489 // Disallow lax conversions between scalars and ExtVectors (these
7490 // conversions are allowed for other vector types because common headers
7491 // depend on them). Most scalar OP ExtVector cases are handled by the
7492 // splat path anyway, which does what we want (convert, not bitcast).
7493 // What this rules out for ExtVectors is crazy things like char4*float.
7494 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7495 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7496
7497 return areVectorTypesSameSize(srcTy, destTy);
7498}
7499
7500/// Is this a legal conversion between two types, one of which is
7501/// known to be a vector type?
7502bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7503 assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast<void> (0));
7504
7505 switch (Context.getLangOpts().getLaxVectorConversions()) {
7506 case LangOptions::LaxVectorConversionKind::None:
7507 return false;
7508
7509 case LangOptions::LaxVectorConversionKind::Integer:
7510 if (!srcTy->isIntegralOrEnumerationType()) {
7511 auto *Vec = srcTy->getAs<VectorType>();
7512 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7513 return false;
7514 }
7515 if (!destTy->isIntegralOrEnumerationType()) {
7516 auto *Vec = destTy->getAs<VectorType>();
7517 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7518 return false;
7519 }
7520 // OK, integer (vector) -> integer (vector) bitcast.
7521 break;
7522
7523 case LangOptions::LaxVectorConversionKind::All:
7524 break;
7525 }
7526
7527 return areLaxCompatibleVectorTypes(srcTy, destTy);
7528}
7529
7530bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7531 CastKind &Kind) {
7532 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7533 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7534 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7535 << DestTy << SrcTy << R;
7536 }
7537 } else if (SrcTy->isMatrixType()) {
7538 return Diag(R.getBegin(),
7539 diag::err_invalid_conversion_between_matrix_and_type)
7540 << SrcTy << DestTy << R;
7541 } else if (DestTy->isMatrixType()) {
7542 return Diag(R.getBegin(),
7543 diag::err_invalid_conversion_between_matrix_and_type)
7544 << DestTy << SrcTy << R;
7545 }
7546
7547 Kind = CK_MatrixCast;
7548 return false;
7549}
7550
7551bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7552 CastKind &Kind) {
7553 assert(VectorTy->isVectorType() && "Not a vector type!")(static_cast<void> (0));
7554
7555 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7556 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7557 return Diag(R.getBegin(),
7558 Ty->isVectorType() ?
7559 diag::err_invalid_conversion_between_vectors :
7560 diag::err_invalid_conversion_between_vector_and_integer)
7561 << VectorTy << Ty << R;
7562 } else
7563 return Diag(R.getBegin(),
7564 diag::err_invalid_conversion_between_vector_and_scalar)
7565 << VectorTy << Ty << R;
7566
7567 Kind = CK_BitCast;
7568 return false;
7569}
7570
7571ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7572 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7573
7574 if (DestElemTy == SplattedExpr->getType())
7575 return SplattedExpr;
7576
7577 assert(DestElemTy->isFloatingType() ||(static_cast<void> (0))
7578 DestElemTy->isIntegralOrEnumerationType())(static_cast<void> (0));
7579
7580 CastKind CK;
7581 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7582 // OpenCL requires that we convert `true` boolean expressions to -1, but
7583 // only when splatting vectors.
7584 if (DestElemTy->isFloatingType()) {
7585 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7586 // in two steps: boolean to signed integral, then to floating.
7587 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7588 CK_BooleanToSignedIntegral);
7589 SplattedExpr = CastExprRes.get();
7590 CK = CK_IntegralToFloating;
7591 } else {
7592 CK = CK_BooleanToSignedIntegral;
7593 }
7594 } else {
7595 ExprResult CastExprRes = SplattedExpr;
7596 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7597 if (CastExprRes.isInvalid())
7598 return ExprError();
7599 SplattedExpr = CastExprRes.get();
7600 }
7601 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7602}
7603
7604ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7605 Expr *CastExpr, CastKind &Kind) {
7606 assert(DestTy->isExtVectorType() && "Not an extended vector type!")(static_cast<void> (0));
7607
7608 QualType SrcTy = CastExpr->getType();
7609
7610 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7611 // an ExtVectorType.
7612 // In OpenCL, casts between vectors of different types are not allowed.
7613 // (See OpenCL 6.2).
7614 if (SrcTy->isVectorType()) {
7615 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7616 (getLangOpts().OpenCL &&
7617 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7618 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7619 << DestTy << SrcTy << R;
7620 return ExprError();
7621 }
7622 Kind = CK_BitCast;
7623 return CastExpr;
7624 }
7625
7626 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7627 // conversion will take place first from scalar to elt type, and then
7628 // splat from elt type to vector.
7629 if (SrcTy->isPointerType())
7630 return Diag(R.getBegin(),
7631 diag::err_invalid_conversion_between_vector_and_scalar)
7632 << DestTy << SrcTy << R;
7633
7634 Kind = CK_VectorSplat;
7635 return prepareVectorSplat(DestTy, CastExpr);
7636}
7637
7638ExprResult
7639Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7640 Declarator &D, ParsedType &Ty,
7641 SourceLocation RParenLoc, Expr *CastExpr) {
7642 assert(!D.isInvalidType() && (CastExpr != nullptr) &&(static_cast<void> (0))
7643 "ActOnCastExpr(): missing type or expr")(static_cast<void> (0));
7644
7645 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7646 if (D.isInvalidType())
7647 return ExprError();
7648
7649 if (getLangOpts().CPlusPlus) {
7650 // Check that there are no default arguments (C++ only).
7651 CheckExtraCXXDefaultArguments(D);
7652 } else {
7653 // Make sure any TypoExprs have been dealt with.
7654 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7655 if (!Res.isUsable())
7656 return ExprError();
7657 CastExpr = Res.get();
7658 }
7659
7660 checkUnusedDeclAttributes(D);
7661
7662 QualType castType = castTInfo->getType();
7663 Ty = CreateParsedType(castType, castTInfo);
7664
7665 bool isVectorLiteral = false;
7666
7667 // Check for an altivec or OpenCL literal,
7668 // i.e. all the elements are integer constants.
7669 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7670 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7671 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7672 && castType->isVectorType() && (PE || PLE)) {
7673 if (PLE && PLE->getNumExprs() == 0) {
7674 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7675 return ExprError();
7676 }
7677 if (PE || PLE->getNumExprs() == 1) {
7678 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7679 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7680 isVectorLiteral = true;
7681 }
7682 else
7683 isVectorLiteral = true;
7684 }
7685
7686 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7687 // then handle it as such.
7688 if (isVectorLiteral)
7689 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7690
7691 // If the Expr being casted is a ParenListExpr, handle it specially.
7692 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7693 // sequence of BinOp comma operators.
7694 if (isa<ParenListExpr>(CastExpr)) {
7695 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7696 if (Result.isInvalid()) return ExprError();
7697 CastExpr = Result.get();
7698 }
7699
7700 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7701 !getSourceManager().isInSystemMacro(LParenLoc))
7702 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7703
7704 CheckTollFreeBridgeCast(castType, CastExpr);
7705
7706 CheckObjCBridgeRelatedCast(castType, CastExpr);
7707
7708 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7709
7710 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7711}
7712
7713ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7714 SourceLocation RParenLoc, Expr *E,
7715 TypeSourceInfo *TInfo) {
7716 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(static_cast<void> (0))
7717 "Expected paren or paren list expression")(static_cast<void> (0));
7718
7719 Expr **exprs;
7720 unsigned numExprs;
7721 Expr *subExpr;
7722 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7723 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7724 LiteralLParenLoc = PE->getLParenLoc();
7725 LiteralRParenLoc = PE->getRParenLoc();
7726 exprs = PE->getExprs();
7727 numExprs = PE->getNumExprs();
7728 } else { // isa<ParenExpr> by assertion at function entrance
7729 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7730 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7731 subExpr = cast<ParenExpr>(E)->getSubExpr();
7732 exprs = &subExpr;
7733 numExprs = 1;
7734 }
7735
7736 QualType Ty = TInfo->getType();
7737 assert(Ty->isVectorType() && "Expected vector type")(static_cast<void> (0));
7738
7739 SmallVector<Expr *, 8> initExprs;
7740 const VectorType *VTy = Ty->castAs<VectorType>();
7741 unsigned numElems = VTy->getNumElements();
7742
7743 // '(...)' form of vector initialization in AltiVec: the number of
7744 // initializers must be one or must match the size of the vector.
7745 // If a single value is specified in the initializer then it will be
7746 // replicated to all the components of the vector
7747 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
7748 VTy->getElementType()))
7749 return ExprError();
7750 if (ShouldSplatAltivecScalarInCast(VTy)) {
7751 // The number of initializers must be one or must match the size of the
7752 // vector. If a single value is specified in the initializer then it will
7753 // be replicated to all the components of the vector
7754 if (numExprs == 1) {
7755 QualType ElemTy = VTy->getElementType();
7756 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7757 if (Literal.isInvalid())
7758 return ExprError();
7759 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7760 PrepareScalarCast(Literal, ElemTy));
7761 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7762 }
7763 else if (numExprs < numElems) {
7764 Diag(E->getExprLoc(),
7765 diag::err_incorrect_number_of_vector_initializers);
7766 return ExprError();
7767 }
7768 else
7769 initExprs.append(exprs, exprs + numExprs);
7770 }
7771 else {
7772 // For OpenCL, when the number of initializers is a single value,
7773 // it will be replicated to all components of the vector.
7774 if (getLangOpts().OpenCL &&
7775 VTy->getVectorKind() == VectorType::GenericVector &&
7776 numExprs == 1) {
7777 QualType ElemTy = VTy->getElementType();
7778 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7779 if (Literal.isInvalid())
7780 return ExprError();
7781 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7782 PrepareScalarCast(Literal, ElemTy));
7783 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7784 }
7785
7786 initExprs.append(exprs, exprs + numExprs);
7787 }
7788 // FIXME: This means that pretty-printing the final AST will produce curly
7789 // braces instead of the original commas.
7790 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7791 initExprs, LiteralRParenLoc);
7792 initE->setType(Ty);
7793 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7794}
7795
7796/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7797/// the ParenListExpr into a sequence of comma binary operators.
7798ExprResult
7799Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7800 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7801 if (!E)
7802 return OrigExpr;
7803
7804 ExprResult Result(E->getExpr(0));
7805
7806 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7807 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7808 E->getExpr(i));
7809
7810 if (Result.isInvalid()) return ExprError();
7811
7812 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7813}
7814
7815ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7816 SourceLocation R,
7817 MultiExprArg Val) {
7818 return ParenListExpr::Create(Context, L, Val, R);
7819}
7820
7821/// Emit a specialized diagnostic when one expression is a null pointer
7822/// constant and the other is not a pointer. Returns true if a diagnostic is
7823/// emitted.
7824bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7825 SourceLocation QuestionLoc) {
7826 Expr *NullExpr = LHSExpr;
7827 Expr *NonPointerExpr = RHSExpr;
7828 Expr::NullPointerConstantKind NullKind =
7829 NullExpr->isNullPointerConstant(Context,
7830 Expr::NPC_ValueDependentIsNotNull);
7831
7832 if (NullKind == Expr::NPCK_NotNull) {
7833 NullExpr = RHSExpr;
7834 NonPointerExpr = LHSExpr;
7835 NullKind =
7836 NullExpr->isNullPointerConstant(Context,
7837 Expr::NPC_ValueDependentIsNotNull);
7838 }
7839
7840 if (NullKind == Expr::NPCK_NotNull)
7841 return false;
7842
7843 if (NullKind == Expr::NPCK_ZeroExpression)
7844 return false;
7845
7846 if (NullKind == Expr::NPCK_ZeroLiteral) {
7847 // In this case, check to make sure that we got here from a "NULL"
7848 // string in the source code.
7849 NullExpr = NullExpr->IgnoreParenImpCasts();
7850 SourceLocation loc = NullExpr->getExprLoc();
7851 if (!findMacroSpelling(loc, "NULL"))
7852 return false;
7853 }
7854
7855 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7856 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7857 << NonPointerExpr->getType() << DiagType
7858 << NonPointerExpr->getSourceRange();
7859 return true;
7860}
7861
7862/// Return false if the condition expression is valid, true otherwise.
7863static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7864 QualType CondTy = Cond->getType();
7865
7866 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7867 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7868 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7869 << CondTy << Cond->getSourceRange();
7870 return true;
7871 }
7872
7873 // C99 6.5.15p2
7874 if (CondTy->isScalarType()) return false;
7875
7876 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7877 << CondTy << Cond->getSourceRange();
7878 return true;
7879}
7880
7881/// Handle when one or both operands are void type.
7882static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7883 ExprResult &RHS) {
7884 Expr *LHSExpr = LHS.get();
7885 Expr *RHSExpr = RHS.get();
7886
7887 if (!LHSExpr->getType()->isVoidType())
7888 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7889 << RHSExpr->getSourceRange();
7890 if (!RHSExpr->getType()->isVoidType())
7891 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7892 << LHSExpr->getSourceRange();
7893 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7894 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7895 return S.Context.VoidTy;
7896}
7897
7898/// Return false if the NullExpr can be promoted to PointerTy,
7899/// true otherwise.
7900static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7901 QualType PointerTy) {
7902 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7903 !NullExpr.get()->isNullPointerConstant(S.Context,
7904 Expr::NPC_ValueDependentIsNull))
7905 return true;
7906
7907 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7908 return false;
7909}
7910
7911/// Checks compatibility between two pointers and return the resulting
7912/// type.
7913static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7914 ExprResult &RHS,
7915 SourceLocation Loc) {
7916 QualType LHSTy = LHS.get()->getType();
7917 QualType RHSTy = RHS.get()->getType();
7918
7919 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7920 // Two identical pointers types are always compatible.
7921 return LHSTy;
7922 }
7923
7924 QualType lhptee, rhptee;
7925
7926 // Get the pointee types.
7927 bool IsBlockPointer = false;
7928 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7929 lhptee = LHSBTy->getPointeeType();
7930 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7931 IsBlockPointer = true;
7932 } else {
7933 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7934 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7935 }
7936
7937 // C99 6.5.15p6: If both operands are pointers to compatible types or to
7938 // differently qualified versions of compatible types, the result type is
7939 // a pointer to an appropriately qualified version of the composite
7940 // type.
7941
7942 // Only CVR-qualifiers exist in the standard, and the differently-qualified
7943 // clause doesn't make sense for our extensions. E.g. address space 2 should
7944 // be incompatible with address space 3: they may live on different devices or
7945 // anything.
7946 Qualifiers lhQual = lhptee.getQualifiers();
7947 Qualifiers rhQual = rhptee.getQualifiers();
7948
7949 LangAS ResultAddrSpace = LangAS::Default;
7950 LangAS LAddrSpace = lhQual.getAddressSpace();
7951 LangAS RAddrSpace = rhQual.getAddressSpace();
7952
7953 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7954 // spaces is disallowed.
7955 if (lhQual.isAddressSpaceSupersetOf(rhQual))
7956 ResultAddrSpace = LAddrSpace;
7957 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7958 ResultAddrSpace = RAddrSpace;
7959 else {
7960 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7961 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7962 << RHS.get()->getSourceRange();
7963 return QualType();
7964 }
7965
7966 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7967 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7968 lhQual.removeCVRQualifiers();
7969 rhQual.removeCVRQualifiers();
7970
7971 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7972 // (C99 6.7.3) for address spaces. We assume that the check should behave in
7973 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7974 // qual types are compatible iff
7975 // * corresponded types are compatible
7976 // * CVR qualifiers are equal
7977 // * address spaces are equal
7978 // Thus for conditional operator we merge CVR and address space unqualified
7979 // pointees and if there is a composite type we return a pointer to it with
7980 // merged qualifiers.
7981 LHSCastKind =
7982 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7983 RHSCastKind =
7984 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7985 lhQual.removeAddressSpace();
7986 rhQual.removeAddressSpace();
7987
7988 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7989 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7990
7991 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7992
7993 if (CompositeTy.isNull()) {
7994 // In this situation, we assume void* type. No especially good
7995 // reason, but this is what gcc does, and we do have to pick
7996 // to get a consistent AST.
7997 QualType incompatTy;
7998 incompatTy = S.Context.getPointerType(
7999 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8000 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8001 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8002
8003 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8004 // for casts between types with incompatible address space qualifiers.
8005 // For the following code the compiler produces casts between global and
8006 // local address spaces of the corresponded innermost pointees:
8007 // local int *global *a;
8008 // global int *global *b;
8009 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8010 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8011 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8012 << RHS.get()->getSourceRange();
8013
8014 return incompatTy;
8015 }
8016
8017 // The pointer types are compatible.
8018 // In case of OpenCL ResultTy should have the address space qualifier
8019 // which is a superset of address spaces of both the 2nd and the 3rd
8020 // operands of the conditional operator.
8021 QualType ResultTy = [&, ResultAddrSpace]() {
8022 if (S.getLangOpts().OpenCL) {
8023 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8024 CompositeQuals.setAddressSpace(ResultAddrSpace);
8025 return S.Context
8026 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8027 .withCVRQualifiers(MergedCVRQual);
8028 }
8029 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8030 }();
8031 if (IsBlockPointer)
8032 ResultTy = S.Context.getBlockPointerType(ResultTy);
8033 else
8034 ResultTy = S.Context.getPointerType(ResultTy);
8035
8036 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8037 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8038 return ResultTy;
8039}
8040
8041/// Return the resulting type when the operands are both block pointers.
8042static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8043 ExprResult &LHS,
8044 ExprResult &RHS,
8045 SourceLocation Loc) {
8046 QualType LHSTy = LHS.get()->getType();
8047 QualType RHSTy = RHS.get()->getType();
8048
8049 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8050 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8051 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8052 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8053 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8054 return destType;
8055 }
8056 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8057 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8058 << RHS.get()->getSourceRange();
8059 return QualType();
8060 }
8061
8062 // We have 2 block pointer types.
8063 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8064}
8065
8066/// Return the resulting type when the operands are both pointers.
8067static QualType
8068checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8069 ExprResult &RHS,
8070 SourceLocation Loc) {
8071 // get the pointer types
8072 QualType LHSTy = LHS.get()->getType();
8073 QualType RHSTy = RHS.get()->getType();
8074
8075 // get the "pointed to" types
8076 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8077 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8078
8079 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8080 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8081 // Figure out necessary qualifiers (C99 6.5.15p6)
8082 QualType destPointee
8083 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8084 QualType destType = S.Context.getPointerType(destPointee);
8085 // Add qualifiers if necessary.
8086 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8087 // Promote to void*.
8088 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8089 return destType;
8090 }
8091 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8092 QualType destPointee
8093 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8094 QualType destType = S.Context.getPointerType(destPointee);
8095 // Add qualifiers if necessary.
8096 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8097 // Promote to void*.
8098 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8099 return destType;
8100 }
8101
8102 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8103}
8104
8105/// Return false if the first expression is not an integer and the second
8106/// expression is not a pointer, true otherwise.
8107static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8108 Expr* PointerExpr, SourceLocation Loc,
8109 bool IsIntFirstExpr) {
8110 if (!PointerExpr->getType()->isPointerType() ||
8111 !Int.get()->getType()->isIntegerType())
8112 return false;
8113
8114 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8115 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8116
8117 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8118 << Expr1->getType() << Expr2->getType()
8119 << Expr1->getSourceRange() << Expr2->getSourceRange();
8120 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8121 CK_IntegralToPointer);
8122 return true;
8123}
8124
8125/// Simple conversion between integer and floating point types.
8126///
8127/// Used when handling the OpenCL conditional operator where the
8128/// condition is a vector while the other operands are scalar.
8129///
8130/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8131/// types are either integer or floating type. Between the two
8132/// operands, the type with the higher rank is defined as the "result
8133/// type". The other operand needs to be promoted to the same type. No
8134/// other type promotion is allowed. We cannot use
8135/// UsualArithmeticConversions() for this purpose, since it always
8136/// promotes promotable types.
8137static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8138 ExprResult &RHS,
8139 SourceLocation QuestionLoc) {
8140 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8141 if (LHS.isInvalid())
8142 return QualType();
8143 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8144 if (RHS.isInvalid())
8145 return QualType();
8146
8147 // For conversion purposes, we ignore any qualifiers.
8148 // For example, "const float" and "float" are equivalent.
8149 QualType LHSType =
8150 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8151 QualType RHSType =
8152 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8153
8154 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8155 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8156 << LHSType << LHS.get()->getSourceRange();
8157 return QualType();
8158 }
8159
8160 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8161 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8162 << RHSType << RHS.get()->getSourceRange();
8163 return QualType();
8164 }
8165
8166 // If both types are identical, no conversion is needed.
8167 if (LHSType == RHSType)
8168 return LHSType;
8169
8170 // Now handle "real" floating types (i.e. float, double, long double).
8171 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8172 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8173 /*IsCompAssign = */ false);
8174
8175 // Finally, we have two differing integer types.
8176 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8177 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8178}
8179
8180/// Convert scalar operands to a vector that matches the
8181/// condition in length.
8182///
8183/// Used when handling the OpenCL conditional operator where the
8184/// condition is a vector while the other operands are scalar.
8185///
8186/// We first compute the "result type" for the scalar operands
8187/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8188/// into a vector of that type where the length matches the condition
8189/// vector type. s6.11.6 requires that the element types of the result
8190/// and the condition must have the same number of bits.
8191static QualType
8192OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8193 QualType CondTy, SourceLocation QuestionLoc) {
8194 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8195 if (ResTy.isNull()) return QualType();
8196
8197 const VectorType *CV = CondTy->getAs<VectorType>();
8198 assert(CV)(static_cast<void> (0));
8199
8200 // Determine the vector result type
8201 unsigned NumElements = CV->getNumElements();
8202 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8203
8204 // Ensure that all types have the same number of bits
8205 if (S.Context.getTypeSize(CV->getElementType())
8206 != S.Context.getTypeSize(ResTy)) {
8207 // Since VectorTy is created internally, it does not pretty print
8208 // with an OpenCL name. Instead, we just print a description.
8209 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8210 SmallString<64> Str;
8211 llvm::raw_svector_ostream OS(Str);
8212 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8213 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8214 << CondTy << OS.str();
8215 return QualType();
8216 }
8217
8218 // Convert operands to the vector result type
8219 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8220 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8221
8222 return VectorTy;
8223}
8224
8225/// Return false if this is a valid OpenCL condition vector
8226static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8227 SourceLocation QuestionLoc) {
8228 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8229 // integral type.
8230 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8231 assert(CondTy)(static_cast<void> (0));
8232 QualType EleTy = CondTy->getElementType();
8233 if (EleTy->isIntegerType()) return false;
8234
8235 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8236 << Cond->getType() << Cond->getSourceRange();
8237 return true;
8238}
8239
8240/// Return false if the vector condition type and the vector
8241/// result type are compatible.
8242///
8243/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8244/// number of elements, and their element types have the same number
8245/// of bits.
8246static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8247 SourceLocation QuestionLoc) {
8248 const VectorType *CV = CondTy->getAs<VectorType>();
8249 const VectorType *RV = VecResTy->getAs<VectorType>();
8250 assert(CV && RV)(static_cast<void> (0));
8251
8252 if (CV->getNumElements() != RV->getNumElements()) {
8253 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8254 << CondTy << VecResTy;
8255 return true;
8256 }
8257
8258 QualType CVE = CV->getElementType();
8259 QualType RVE = RV->getElementType();
8260
8261 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8262 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8263 << CondTy << VecResTy;
8264 return true;
8265 }
8266
8267 return false;
8268}
8269
8270/// Return the resulting type for the conditional operator in
8271/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8272/// s6.3.i) when the condition is a vector type.
8273static QualType
8274OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8275 ExprResult &LHS, ExprResult &RHS,
8276 SourceLocation QuestionLoc) {
8277 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8278 if (Cond.isInvalid())
8279 return QualType();
8280 QualType CondTy = Cond.get()->getType();
8281
8282 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8283 return QualType();
8284
8285 // If either operand is a vector then find the vector type of the
8286 // result as specified in OpenCL v1.1 s6.3.i.
8287 if (LHS.get()->getType()->isVectorType() ||
8288 RHS.get()->getType()->isVectorType()) {
8289 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8290 /*isCompAssign*/false,
8291 /*AllowBothBool*/true,
8292 /*AllowBoolConversions*/false);
8293 if (VecResTy.isNull()) return QualType();
8294 // The result type must match the condition type as specified in
8295 // OpenCL v1.1 s6.11.6.
8296 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8297 return QualType();
8298 return VecResTy;
8299 }
8300
8301 // Both operands are scalar.
8302 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8303}
8304
8305/// Return true if the Expr is block type
8306static bool checkBlockType(Sema &S, const Expr *E) {
8307 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8308 QualType Ty = CE->getCallee()->getType();
8309 if (Ty->isBlockPointerType()) {
8310 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8311 return true;
8312 }
8313 }
8314 return false;
8315}
8316
8317/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8318/// In that case, LHS = cond.
8319/// C99 6.5.15
8320QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8321 ExprResult &RHS, ExprValueKind &VK,
8322 ExprObjectKind &OK,
8323 SourceLocation QuestionLoc) {
8324
8325 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8326 if (!LHSResult.isUsable()) return QualType();
8327 LHS = LHSResult;
8328
8329 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8330 if (!RHSResult.isUsable()) return QualType();
8331 RHS = RHSResult;
8332
8333 // C++ is sufficiently different to merit its own checker.
8334 if (getLangOpts().CPlusPlus)
8335 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8336
8337 VK = VK_PRValue;
8338 OK = OK_Ordinary;
8339
8340 if (Context.isDependenceAllowed() &&
8341 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8342 RHS.get()->isTypeDependent())) {
8343 assert(!getLangOpts().CPlusPlus)(static_cast<void> (0));
8344 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||(static_cast<void> (0))
8345 RHS.get()->containsErrors()) &&(static_cast<void> (0))
8346 "should only occur in error-recovery path.")(static_cast<void> (0));
8347 return Context.DependentTy;
8348 }
8349
8350 // The OpenCL operator with a vector condition is sufficiently
8351 // different to merit its own checker.
8352 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8353 Cond.get()->getType()->isExtVectorType())
8354 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8355
8356 // First, check the condition.
8357 Cond = UsualUnaryConversions(Cond.get());
8358 if (Cond.isInvalid())
8359 return QualType();
8360 if (checkCondition(*this, Cond.get(), QuestionLoc))
8361 return QualType();
8362
8363 // Now check the two expressions.
8364 if (LHS.get()->getType()->isVectorType() ||
8365 RHS.get()->getType()->isVectorType())
8366 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8367 /*AllowBothBool*/true,
8368 /*AllowBoolConversions*/false);
8369
8370 QualType ResTy =
8371 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8372 if (LHS.isInvalid() || RHS.isInvalid())
8373 return QualType();
8374
8375 QualType LHSTy = LHS.get()->getType();
8376 QualType RHSTy = RHS.get()->getType();
8377
8378 // Diagnose attempts to convert between __float128 and long double where
8379 // such conversions currently can't be handled.
8380 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8381 Diag(QuestionLoc,
8382 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8383 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8384 return QualType();
8385 }
8386
8387 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8388 // selection operator (?:).
8389 if (getLangOpts().OpenCL &&
8390 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8391 return QualType();
8392 }
8393
8394 // If both operands have arithmetic type, do the usual arithmetic conversions
8395 // to find a common type: C99 6.5.15p3,5.
8396 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8397 // Disallow invalid arithmetic conversions, such as those between ExtInts of
8398 // different sizes, or between ExtInts and other types.
8399 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8400 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8401 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8402 << RHS.get()->getSourceRange();
8403 return QualType();
8404 }
8405
8406 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8407 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8408
8409 return ResTy;
8410 }
8411
8412 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8413 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8414 return LHSTy;
8415 }
8416
8417 // If both operands are the same structure or union type, the result is that
8418 // type.
8419 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8420 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8421 if (LHSRT->getDecl() == RHSRT->getDecl())
8422 // "If both the operands have structure or union type, the result has
8423 // that type." This implies that CV qualifiers are dropped.
8424 return LHSTy.getUnqualifiedType();
8425 // FIXME: Type of conditional expression must be complete in C mode.
8426 }
8427
8428 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8429 // The following || allows only one side to be void (a GCC-ism).
8430 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8431 return checkConditionalVoidType(*this, LHS, RHS);
8432 }
8433
8434 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8435 // the type of the other operand."
8436 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8437 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8438
8439 // All objective-c pointer type analysis is done here.
8440 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8441 QuestionLoc);
8442 if (LHS.isInvalid() || RHS.isInvalid())
8443 return QualType();
8444 if (!compositeType.isNull())
8445 return compositeType;
8446
8447
8448 // Handle block pointer types.
8449 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8450 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8451 QuestionLoc);
8452
8453 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8454 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8455 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8456 QuestionLoc);
8457
8458 // GCC compatibility: soften pointer/integer mismatch. Note that
8459 // null pointers have been filtered out by this point.
8460 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8461 /*IsIntFirstExpr=*/true))
8462 return RHSTy;
8463 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8464 /*IsIntFirstExpr=*/false))
8465 return LHSTy;
8466
8467 // Allow ?: operations in which both operands have the same
8468 // built-in sizeless type.
8469 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8470 return LHSTy;
8471
8472 // Emit a better diagnostic if one of the expressions is a null pointer
8473 // constant and the other is not a pointer type. In this case, the user most
8474 // likely forgot to take the address of the other expression.
8475 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8476 return QualType();
8477
8478 // Otherwise, the operands are not compatible.
8479 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8480 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8481 << RHS.get()->getSourceRange();
8482 return QualType();
8483}
8484
8485/// FindCompositeObjCPointerType - Helper method to find composite type of
8486/// two objective-c pointer types of the two input expressions.
8487QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8488 SourceLocation QuestionLoc) {
8489 QualType LHSTy = LHS.get()->getType();
8490 QualType RHSTy = RHS.get()->getType();
8491
8492 // Handle things like Class and struct objc_class*. Here we case the result
8493 // to the pseudo-builtin, because that will be implicitly cast back to the
8494 // redefinition type if an attempt is made to access its fields.
8495 if (LHSTy->isObjCClassType() &&
8496 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8497 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8498 return LHSTy;
8499 }
8500 if (RHSTy->isObjCClassType() &&
8501 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8502 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8503 return RHSTy;
8504 }
8505 // And the same for struct objc_object* / id
8506 if (LHSTy->isObjCIdType() &&
8507 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8508 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8509 return LHSTy;
8510 }
8511 if (RHSTy->isObjCIdType() &&
8512 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8513 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8514 return RHSTy;
8515 }
8516 // And the same for struct objc_selector* / SEL
8517 if (Context.isObjCSelType(LHSTy) &&
8518 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8519 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8520 return LHSTy;
8521 }
8522 if (Context.isObjCSelType(RHSTy) &&
8523 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8524 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8525 return RHSTy;
8526 }
8527 // Check constraints for Objective-C object pointers types.
8528 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8529
8530 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8531 // Two identical object pointer types are always compatible.
8532 return LHSTy;
8533 }
8534 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8535 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8536 QualType compositeType = LHSTy;
8537
8538 // If both operands are interfaces and either operand can be
8539 // assigned to the other, use that type as the composite
8540 // type. This allows
8541 // xxx ? (A*) a : (B*) b
8542 // where B is a subclass of A.
8543 //
8544 // Additionally, as for assignment, if either type is 'id'
8545 // allow silent coercion. Finally, if the types are
8546 // incompatible then make sure to use 'id' as the composite
8547 // type so the result is acceptable for sending messages to.
8548
8549 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8550 // It could return the composite type.
8551 if (!(compositeType =
8552 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8553 // Nothing more to do.
8554 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8555 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8556 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8557 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8558 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8559 RHSOPT->isObjCQualifiedIdType()) &&
8560 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8561 true)) {
8562 // Need to handle "id<xx>" explicitly.
8563 // GCC allows qualified id and any Objective-C type to devolve to
8564 // id. Currently localizing to here until clear this should be
8565 // part of ObjCQualifiedIdTypesAreCompatible.
8566 compositeType = Context.getObjCIdType();
8567 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8568 compositeType = Context.getObjCIdType();
8569 } else {
8570 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8571 << LHSTy << RHSTy
8572 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8573 QualType incompatTy = Context.getObjCIdType();
8574 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8575 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8576 return incompatTy;
8577 }
8578 // The object pointer types are compatible.
8579 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8580 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8581 return compositeType;
8582 }
8583 // Check Objective-C object pointer types and 'void *'
8584 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8585 if (getLangOpts().ObjCAutoRefCount) {
8586 // ARC forbids the implicit conversion of object pointers to 'void *',
8587 // so these types are not compatible.
8588 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8589 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8590 LHS = RHS = true;
8591 return QualType();
8592 }
8593 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8594 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8595 QualType destPointee
8596 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8597 QualType destType = Context.getPointerType(destPointee);
8598 // Add qualifiers if necessary.
8599 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8600 // Promote to void*.
8601 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8602 return destType;
8603 }
8604 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8605 if (getLangOpts().ObjCAutoRefCount) {
8606 // ARC forbids the implicit conversion of object pointers to 'void *',
8607 // so these types are not compatible.
8608 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8609 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8610 LHS = RHS = true;
8611 return QualType();
8612 }
8613 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8614 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8615 QualType destPointee
8616 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8617 QualType destType = Context.getPointerType(destPointee);
8618 // Add qualifiers if necessary.
8619 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8620 // Promote to void*.
8621 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8622 return destType;
8623 }
8624 return QualType();
8625}
8626
8627/// SuggestParentheses - Emit a note with a fixit hint that wraps
8628/// ParenRange in parentheses.
8629static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8630 const PartialDiagnostic &Note,
8631 SourceRange ParenRange) {
8632 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8633 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8634 EndLoc.isValid()) {
8635 Self.Diag(Loc, Note)
8636 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8637 << FixItHint::CreateInsertion(EndLoc, ")");
8638 } else {
8639 // We can't display the parentheses, so just show the bare note.
8640 Self.Diag(Loc, Note) << ParenRange;
8641 }
8642}
8643
8644static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8645 return BinaryOperator::isAdditiveOp(Opc) ||
8646 BinaryOperator::isMultiplicativeOp(Opc) ||
8647 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8648 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8649 // not any of the logical operators. Bitwise-xor is commonly used as a
8650 // logical-xor because there is no logical-xor operator. The logical
8651 // operators, including uses of xor, have a high false positive rate for
8652 // precedence warnings.
8653}
8654
8655/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8656/// expression, either using a built-in or overloaded operator,
8657/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8658/// expression.
8659static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8660 Expr **RHSExprs) {
8661 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8662 E = E->IgnoreImpCasts();
8663 E = E->IgnoreConversionOperatorSingleStep();
8664 E = E->IgnoreImpCasts();
8665 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8666 E = MTE->getSubExpr();
8667 E = E->IgnoreImpCasts();
8668 }
8669
8670 // Built-in binary operator.
8671 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8672 if (IsArithmeticOp(OP->getOpcode())) {
8673 *Opcode = OP->getOpcode();
8674 *RHSExprs = OP->getRHS();
8675 return true;
8676 }
8677 }
8678
8679 // Overloaded operator.
8680 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8681 if (Call->getNumArgs() != 2)
8682 return false;
8683
8684 // Make sure this is really a binary operator that is safe to pass into
8685 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8686 OverloadedOperatorKind OO = Call->getOperator();
8687 if (OO < OO_Plus || OO > OO_Arrow ||
8688 OO == OO_PlusPlus || OO == OO_MinusMinus)
8689 return false;
8690
8691 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8692 if (IsArithmeticOp(OpKind)) {
8693 *Opcode = OpKind;
8694 *RHSExprs = Call->getArg(1);
8695 return true;
8696 }
8697 }
8698
8699 return false;
8700}
8701
8702/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8703/// or is a logical expression such as (x==y) which has int type, but is
8704/// commonly interpreted as boolean.
8705static bool ExprLooksBoolean(Expr *E) {
8706 E = E->IgnoreParenImpCasts();
8707
8708 if (E->getType()->isBooleanType())
8709 return true;
8710 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8711 return OP->isComparisonOp() || OP->isLogicalOp();
8712 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8713 return OP->getOpcode() == UO_LNot;
8714 if (E->getType()->isPointerType())
8715 return true;
8716 // FIXME: What about overloaded operator calls returning "unspecified boolean
8717 // type"s (commonly pointer-to-members)?
8718
8719 return false;
8720}
8721
8722/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8723/// and binary operator are mixed in a way that suggests the programmer assumed
8724/// the conditional operator has higher precedence, for example:
8725/// "int x = a + someBinaryCondition ? 1 : 2".
8726static void DiagnoseConditionalPrecedence(Sema &Self,
8727 SourceLocation OpLoc,
8728 Expr *Condition,
8729 Expr *LHSExpr,
8730 Expr *RHSExpr) {
8731 BinaryOperatorKind CondOpcode;
8732 Expr *CondRHS;
8733
8734 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8735 return;
8736 if (!ExprLooksBoolean(CondRHS))
8737 return;
8738
8739 // The condition is an arithmetic binary expression, with a right-
8740 // hand side that looks boolean, so warn.
8741
8742 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8743 ? diag::warn_precedence_bitwise_conditional
8744 : diag::warn_precedence_conditional;
8745
8746 Self.Diag(OpLoc, DiagID)
8747 << Condition->getSourceRange()
8748 << BinaryOperator::getOpcodeStr(CondOpcode);
8749
8750 SuggestParentheses(
8751 Self, OpLoc,
8752 Self.PDiag(diag::note_precedence_silence)
8753 << BinaryOperator::getOpcodeStr(CondOpcode),
8754 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8755
8756 SuggestParentheses(Self, OpLoc,
8757 Self.PDiag(diag::note_precedence_conditional_first),
8758 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8759}
8760
8761/// Compute the nullability of a conditional expression.
8762static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8763 QualType LHSTy, QualType RHSTy,
8764 ASTContext &Ctx) {
8765 if (!ResTy->isAnyPointerType())
8766 return ResTy;
8767
8768 auto GetNullability = [&Ctx](QualType Ty) {
8769 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8770 if (Kind) {
8771 // For our purposes, treat _Nullable_result as _Nullable.
8772 if (*Kind == NullabilityKind::NullableResult)
8773 return NullabilityKind::Nullable;
8774 return *Kind;
8775 }
8776 return NullabilityKind::Unspecified;
8777 };
8778
8779 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8780 NullabilityKind MergedKind;
8781
8782 // Compute nullability of a binary conditional expression.
8783 if (IsBin) {
8784 if (LHSKind == NullabilityKind::NonNull)
8785 MergedKind = NullabilityKind::NonNull;
8786 else
8787 MergedKind = RHSKind;
8788 // Compute nullability of a normal conditional expression.
8789 } else {
8790 if (LHSKind == NullabilityKind::Nullable ||
8791 RHSKind == NullabilityKind::Nullable)
8792 MergedKind = NullabilityKind::Nullable;
8793 else if (LHSKind == NullabilityKind::NonNull)
8794 MergedKind = RHSKind;
8795 else if (RHSKind == NullabilityKind::NonNull)
8796 MergedKind = LHSKind;
8797 else
8798 MergedKind = NullabilityKind::Unspecified;
8799 }
8800
8801 // Return if ResTy already has the correct nullability.
8802 if (GetNullability(ResTy) == MergedKind)
8803 return ResTy;
8804
8805 // Strip all nullability from ResTy.
8806 while (ResTy->getNullability(Ctx))
8807 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8808
8809 // Create a new AttributedType with the new nullability kind.
8810 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8811 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8812}
8813
8814/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
8815/// in the case of a the GNU conditional expr extension.
8816ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8817 SourceLocation ColonLoc,
8818 Expr *CondExpr, Expr *LHSExpr,
8819 Expr *RHSExpr) {
8820 if (!Context.isDependenceAllowed()) {
8821 // C cannot handle TypoExpr nodes in the condition because it
8822 // doesn't handle dependent types properly, so make sure any TypoExprs have
8823 // been dealt with before checking the operands.
8824 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8825 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8826 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8827
8828 if (!CondResult.isUsable())
8829 return ExprError();
8830
8831 if (LHSExpr) {
8832 if (!LHSResult.isUsable())
8833 return ExprError();
8834 }
8835
8836 if (!RHSResult.isUsable())
8837 return ExprError();
8838
8839 CondExpr = CondResult.get();
8840 LHSExpr = LHSResult.get();
8841 RHSExpr = RHSResult.get();
8842 }
8843
8844 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8845 // was the condition.
8846 OpaqueValueExpr *opaqueValue = nullptr;
8847 Expr *commonExpr = nullptr;
8848 if (!LHSExpr) {
8849 commonExpr = CondExpr;
8850 // Lower out placeholder types first. This is important so that we don't
8851 // try to capture a placeholder. This happens in few cases in C++; such
8852 // as Objective-C++'s dictionary subscripting syntax.
8853 if (commonExpr->hasPlaceholderType()) {
8854 ExprResult result = CheckPlaceholderExpr(commonExpr);
8855 if (!result.isUsable()) return ExprError();
8856 commonExpr = result.get();
8857 }
8858 // We usually want to apply unary conversions *before* saving, except
8859 // in the special case of a C++ l-value conditional.
8860 if (!(getLangOpts().CPlusPlus
8861 && !commonExpr->isTypeDependent()
8862 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8863 && commonExpr->isGLValue()
8864 && commonExpr->isOrdinaryOrBitFieldObject()
8865 && RHSExpr->isOrdinaryOrBitFieldObject()
8866 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8867 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8868 if (commonRes.isInvalid())
8869 return ExprError();
8870 commonExpr = commonRes.get();
8871 }
8872
8873 // If the common expression is a class or array prvalue, materialize it
8874 // so that we can safely refer to it multiple times.
8875 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8876 commonExpr->getType()->isArrayType())) {
8877 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8878 if (MatExpr.isInvalid())
8879 return ExprError();
8880 commonExpr = MatExpr.get();
8881 }
8882
8883 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8884 commonExpr->getType(),
8885 commonExpr->getValueKind(),
8886 commonExpr->getObjectKind(),
8887 commonExpr);
8888 LHSExpr = CondExpr = opaqueValue;
8889 }
8890
8891 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8892 ExprValueKind VK = VK_PRValue;
8893 ExprObjectKind OK = OK_Ordinary;
8894 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8895 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8896 VK, OK, QuestionLoc);
8897 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8898 RHS.isInvalid())
8899 return ExprError();
8900
8901 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8902 RHS.get());
8903
8904 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8905
8906 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8907 Context);
8908
8909 if (!commonExpr)
8910 return new (Context)
8911 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8912 RHS.get(), result, VK, OK);
8913
8914 return new (Context) BinaryConditionalOperator(
8915 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8916 ColonLoc, result, VK, OK);
8917}
8918
8919// Check if we have a conversion between incompatible cmse function pointer
8920// types, that is, a conversion between a function pointer with the
8921// cmse_nonsecure_call attribute and one without.
8922static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8923 QualType ToType) {
8924 if (const auto *ToFn =
8925 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8926 if (const auto *FromFn =
8927 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8928 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8929 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8930
8931 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8932 }
8933 }
8934 return false;
8935}
8936
8937// checkPointerTypesForAssignment - This is a very tricky routine (despite
8938// being closely modeled after the C99 spec:-). The odd characteristic of this
8939// routine is it effectively iqnores the qualifiers on the top level pointee.
8940// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8941// FIXME: add a couple examples in this comment.
8942static Sema::AssignConvertType
8943checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8944 assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast<void> (0));
8945 assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast<void> (0));
8946
8947 // get the "pointed to" type (ignoring qualifiers at the top level)
8948 const Type *lhptee, *rhptee;
8949 Qualifiers lhq, rhq;
8950 std::tie(lhptee, lhq) =
8951 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8952 std::tie(rhptee, rhq) =
8953 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8954
8955 Sema::AssignConvertType ConvTy = Sema::Compatible;
8956
8957 // C99 6.5.16.1p1: This following citation is common to constraints
8958 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8959 // qualifiers of the type *pointed to* by the right;
8960
8961 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8962 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8963 lhq.compatiblyIncludesObjCLifetime(rhq)) {
8964 // Ignore lifetime for further calculation.
8965 lhq.removeObjCLifetime();
8966 rhq.removeObjCLifetime();
8967 }
8968
8969 if (!lhq.compatiblyIncludes(rhq)) {
8970 // Treat address-space mismatches as fatal.
8971 if (!lhq.isAddressSpaceSupersetOf(rhq))
8972 return Sema::IncompatiblePointerDiscardsQualifiers;
8973
8974 // It's okay to add or remove GC or lifetime qualifiers when converting to
8975 // and from void*.
8976 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8977 .compatiblyIncludes(
8978 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8979 && (lhptee->isVoidType() || rhptee->isVoidType()))
8980 ; // keep old
8981
8982 // Treat lifetime mismatches as fatal.
8983 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8984 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8985
8986 // For GCC/MS compatibility, other qualifier mismatches are treated
8987 // as still compatible in C.
8988 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8989 }
8990
8991 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8992 // incomplete type and the other is a pointer to a qualified or unqualified
8993 // version of void...
8994 if (lhptee->isVoidType()) {
8995 if (rhptee->isIncompleteOrObjectType())
8996 return ConvTy;
8997
8998 // As an extension, we allow cast to/from void* to function pointer.
8999 assert(rhptee->isFunctionType())(static_cast<void> (0));
9000 return Sema::FunctionVoidPointer;
9001 }
9002
9003 if (rhptee->isVoidType()) {
9004 if (lhptee->isIncompleteOrObjectType())
9005 return ConvTy;
9006
9007 // As an extension, we allow cast to/from void* to function pointer.
9008 assert(lhptee->isFunctionType())(static_cast<void> (0));
9009 return Sema::FunctionVoidPointer;
9010 }
9011
9012 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9013 // unqualified versions of compatible types, ...
9014 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9015 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9016 // Check if the pointee types are compatible ignoring the sign.
9017 // We explicitly check for char so that we catch "char" vs
9018 // "unsigned char" on systems where "char" is unsigned.
9019 if (lhptee->isCharType())
9020 ltrans = S.Context.UnsignedCharTy;
9021 else if (lhptee->hasSignedIntegerRepresentation())
9022 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9023
9024 if (rhptee->isCharType())
9025 rtrans = S.Context.UnsignedCharTy;
9026 else if (rhptee->hasSignedIntegerRepresentation())
9027 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9028
9029 if (ltrans == rtrans) {
9030 // Types are compatible ignoring the sign. Qualifier incompatibility
9031 // takes priority over sign incompatibility because the sign
9032 // warning can be disabled.
9033 if (ConvTy != Sema::Compatible)
9034 return ConvTy;
9035
9036 return Sema::IncompatiblePointerSign;
9037 }
9038
9039 // If we are a multi-level pointer, it's possible that our issue is simply
9040 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9041 // the eventual target type is the same and the pointers have the same
9042 // level of indirection, this must be the issue.
9043 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9044 do {
9045 std::tie(lhptee, lhq) =
9046 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9047 std::tie(rhptee, rhq) =
9048 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9049
9050 // Inconsistent address spaces at this point is invalid, even if the
9051 // address spaces would be compatible.
9052 // FIXME: This doesn't catch address space mismatches for pointers of
9053 // different nesting levels, like:
9054 // __local int *** a;
9055 // int ** b = a;
9056 // It's not clear how to actually determine when such pointers are
9057 // invalidly incompatible.
9058 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9059 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9060
9061 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9062
9063 if (lhptee == rhptee)
9064 return Sema::IncompatibleNestedPointerQualifiers;
9065 }
9066
9067 // General pointer incompatibility takes priority over qualifiers.
9068 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9069 return Sema::IncompatibleFunctionPointer;
9070 return Sema::IncompatiblePointer;
9071 }
9072 if (!S.getLangOpts().CPlusPlus &&
9073 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9074 return Sema::IncompatibleFunctionPointer;
9075 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9076 return Sema::IncompatibleFunctionPointer;
9077 return ConvTy;
9078}
9079
9080/// checkBlockPointerTypesForAssignment - This routine determines whether two
9081/// block pointer types are compatible or whether a block and normal pointer
9082/// are compatible. It is more restrict than comparing two function pointer
9083// types.
9084static Sema::AssignConvertType
9085checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9086 QualType RHSType) {
9087 assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast<void> (0));
9088 assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast<void> (0));
9089
9090 QualType lhptee, rhptee;
9091
9092 // get the "pointed to" type (ignoring qualifiers at the top level)
9093 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9094 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9095
9096 // In C++, the types have to match exactly.
9097 if (S.getLangOpts().CPlusPlus)
9098 return Sema::IncompatibleBlockPointer;
9099
9100 Sema::AssignConvertType ConvTy = Sema::Compatible;
9101
9102 // For blocks we enforce that qualifiers are identical.
9103 Qualifiers LQuals = lhptee.getLocalQualifiers();
9104 Qualifiers RQuals = rhptee.getLocalQualifiers();
9105 if (S.getLangOpts().OpenCL) {
9106 LQuals.removeAddressSpace();
9107 RQuals.removeAddressSpace();
9108 }
9109 if (LQuals != RQuals)
9110 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9111
9112 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9113 // assignment.
9114 // The current behavior is similar to C++ lambdas. A block might be
9115 // assigned to a variable iff its return type and parameters are compatible
9116 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9117 // an assignment. Presumably it should behave in way that a function pointer
9118 // assignment does in C, so for each parameter and return type:
9119 // * CVR and address space of LHS should be a superset of CVR and address
9120 // space of RHS.
9121 // * unqualified types should be compatible.
9122 if (S.getLangOpts().OpenCL) {
9123 if (!S.Context.typesAreBlockPointerCompatible(
9124 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9125 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9126 return Sema::IncompatibleBlockPointer;
9127 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9128 return Sema::IncompatibleBlockPointer;
9129
9130 return ConvTy;
9131}
9132
9133/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9134/// for assignment compatibility.
9135static Sema::AssignConvertType
9136checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9137 QualType RHSType) {
9138 assert(LHSType.isCanonical() && "LHS was not canonicalized!")(static_cast<void> (0));
9139 assert(RHSType.isCanonical() && "RHS was not canonicalized!")(static_cast<void> (0));
9140
9141 if (LHSType->isObjCBuiltinType()) {
9142 // Class is not compatible with ObjC object pointers.
9143 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9144 !RHSType->isObjCQualifiedClassType())
9145 return Sema::IncompatiblePointer;
9146 return Sema::Compatible;
9147 }
9148 if (RHSType->isObjCBuiltinType()) {
9149 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9150 !LHSType->isObjCQualifiedClassType())
9151 return Sema::IncompatiblePointer;
9152 return Sema::Compatible;
9153 }
9154 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9155 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9156
9157 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9158 // make an exception for id<P>
9159 !LHSType->isObjCQualifiedIdType())
9160 return Sema::CompatiblePointerDiscardsQualifiers;
9161
9162 if (S.Context.typesAreCompatible(LHSType, RHSType))
9163 return Sema::Compatible;
9164 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9165 return Sema::IncompatibleObjCQualifiedId;
9166 return Sema::IncompatiblePointer;
9167}
9168
9169Sema::AssignConvertType
9170Sema::CheckAssignmentConstraints(SourceLocation Loc,
9171 QualType LHSType, QualType RHSType) {
9172 // Fake up an opaque expression. We don't actually care about what
9173 // cast operations are required, so if CheckAssignmentConstraints
9174 // adds casts to this they'll be wasted, but fortunately that doesn't
9175 // usually happen on valid code.
9176 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9177 ExprResult RHSPtr = &RHSExpr;
9178 CastKind K;
9179
9180 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9181}
9182
9183/// This helper function returns true if QT is a vector type that has element
9184/// type ElementType.
9185static bool isVector(QualType QT, QualType ElementType) {
9186 if (const VectorType *VT = QT->getAs<VectorType>())
9187 return VT->getElementType().getCanonicalType() == ElementType;
9188 return false;
9189}
9190
9191/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9192/// has code to accommodate several GCC extensions when type checking
9193/// pointers. Here are some objectionable examples that GCC considers warnings:
9194///
9195/// int a, *pint;
9196/// short *pshort;
9197/// struct foo *pfoo;
9198///
9199/// pint = pshort; // warning: assignment from incompatible pointer type
9200/// a = pint; // warning: assignment makes integer from pointer without a cast
9201/// pint = a; // warning: assignment makes pointer from integer without a cast
9202/// pint = pfoo; // warning: assignment from incompatible pointer type
9203///
9204/// As a result, the code for dealing with pointers is more complex than the
9205/// C99 spec dictates.
9206///
9207/// Sets 'Kind' for any result kind except Incompatible.
9208Sema::AssignConvertType
9209Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9210 CastKind &Kind, bool ConvertRHS) {
9211 QualType RHSType = RHS.get()->getType();
9212 QualType OrigLHSType = LHSType;
9213
9214 // Get canonical types. We're not formatting these types, just comparing
9215 // them.
9216 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9217 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9218
9219 // Common case: no conversion required.
9220 if (LHSType == RHSType) {
9221 Kind = CK_NoOp;
9222 return Compatible;
9223 }
9224
9225 // If we have an atomic type, try a non-atomic assignment, then just add an
9226 // atomic qualification step.
9227 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9228 Sema::AssignConvertType result =
9229 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9230 if (result != Compatible)
9231 return result;
9232 if (Kind != CK_NoOp && ConvertRHS)
9233 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9234 Kind = CK_NonAtomicToAtomic;
9235 return Compatible;
9236 }
9237
9238 // If the left-hand side is a reference type, then we are in a
9239 // (rare!) case where we've allowed the use of references in C,
9240 // e.g., as a parameter type in a built-in function. In this case,
9241 // just make sure that the type referenced is compatible with the
9242 // right-hand side type. The caller is responsible for adjusting
9243 // LHSType so that the resulting expression does not have reference
9244 // type.
9245 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9246 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9247 Kind = CK_LValueBitCast;
9248 return Compatible;
9249 }
9250 return Incompatible;
9251 }
9252
9253 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9254 // to the same ExtVector type.
9255 if (LHSType->isExtVectorType()) {
9256 if (RHSType->isExtVectorType())
9257 return Incompatible;
9258 if (RHSType->isArithmeticType()) {
9259 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9260 if (ConvertRHS)
9261 RHS = prepareVectorSplat(LHSType, RHS.get());
9262 Kind = CK_VectorSplat;
9263 return Compatible;
9264 }
9265 }
9266
9267 // Conversions to or from vector type.
9268 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9269 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9270 // Allow assignments of an AltiVec vector type to an equivalent GCC
9271 // vector type and vice versa
9272 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9273 Kind = CK_BitCast;
9274 return Compatible;
9275 }
9276
9277 // If we are allowing lax vector conversions, and LHS and RHS are both
9278 // vectors, the total size only needs to be the same. This is a bitcast;
9279 // no bits are changed but the result type is different.
9280 if (isLaxVectorConversion(RHSType, LHSType)) {
9281 Kind = CK_BitCast;
9282 return IncompatibleVectors;
9283 }
9284 }
9285
9286 // When the RHS comes from another lax conversion (e.g. binops between
9287 // scalars and vectors) the result is canonicalized as a vector. When the
9288 // LHS is also a vector, the lax is allowed by the condition above. Handle
9289 // the case where LHS is a scalar.
9290 if (LHSType->isScalarType()) {
9291 const VectorType *VecType = RHSType->getAs<VectorType>();
9292 if (VecType && VecType->getNumElements() == 1 &&
9293 isLaxVectorConversion(RHSType, LHSType)) {
9294 ExprResult *VecExpr = &RHS;
9295 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9296 Kind = CK_BitCast;
9297 return Compatible;
9298 }
9299 }
9300
9301 // Allow assignments between fixed-length and sizeless SVE vectors.
9302 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9303 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9304 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9305 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9306 Kind = CK_BitCast;
9307 return Compatible;
9308 }
9309
9310 return Incompatible;
9311 }
9312
9313 // Diagnose attempts to convert between __float128 and long double where
9314 // such conversions currently can't be handled.
9315 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9316 return Incompatible;
9317
9318 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9319 // discards the imaginary part.
9320 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9321 !LHSType->getAs<ComplexType>())
9322 return Incompatible;
9323
9324 // Arithmetic conversions.
9325 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9326 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9327 if (ConvertRHS)
9328 Kind = PrepareScalarCast(RHS, LHSType);
9329 return Compatible;
9330 }
9331
9332 // Conversions to normal pointers.
9333 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9334 // U* -> T*
9335 if (isa<PointerType>(RHSType)) {
9336 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9337 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9338 if (AddrSpaceL != AddrSpaceR)
9339 Kind = CK_AddressSpaceConversion;
9340 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9341 Kind = CK_NoOp;
9342 else
9343 Kind = CK_BitCast;
9344 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9345 }
9346
9347 // int -> T*
9348 if (RHSType->isIntegerType()) {
9349 Kind = CK_IntegralToPointer; // FIXME: null?
9350 return IntToPointer;
9351 }
9352
9353 // C pointers are not compatible with ObjC object pointers,
9354 // with two exceptions:
9355 if (isa<ObjCObjectPointerType>(RHSType)) {
9356 // - conversions to void*
9357 if (LHSPointer->getPointeeType()->isVoidType()) {
9358 Kind = CK_BitCast;
9359 return Compatible;
9360 }
9361
9362 // - conversions from 'Class' to the redefinition type
9363 if (RHSType->isObjCClassType() &&
9364 Context.hasSameType(LHSType,
9365 Context.getObjCClassRedefinitionType())) {
9366 Kind = CK_BitCast;
9367 return Compatible;
9368 }
9369
9370 Kind = CK_BitCast;
9371 return IncompatiblePointer;
9372 }
9373
9374 // U^ -> void*
9375 if (RHSType->getAs<BlockPointerType>()) {
9376 if (LHSPointer->getPointeeType()->isVoidType()) {
9377 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9378 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9379 ->getPointeeType()
9380 .getAddressSpace();
9381 Kind =
9382 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9383 return Compatible;
9384 }
9385 }
9386
9387 return Incompatible;
9388 }
9389
9390 // Conversions to block pointers.
9391 if (isa<BlockPointerType>(LHSType)) {
9392 // U^ -> T^
9393 if (RHSType->isBlockPointerType()) {
9394 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9395 ->getPointeeType()
9396 .getAddressSpace();
9397 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9398 ->getPointeeType()
9399 .getAddressSpace();
9400 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9401 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9402 }
9403
9404 // int or null -> T^
9405 if (RHSType->isIntegerType()) {
9406 Kind = CK_IntegralToPointer; // FIXME: null
9407 return IntToBlockPointer;
9408 }
9409
9410 // id -> T^
9411 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9412 Kind = CK_AnyPointerToBlockPointerCast;
9413 return Compatible;
9414 }
9415
9416 // void* -> T^
9417 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9418 if (RHSPT->getPointeeType()->isVoidType()) {
9419 Kind = CK_AnyPointerToBlockPointerCast;
9420 return Compatible;
9421 }
9422
9423 return Incompatible;
9424 }
9425
9426 // Conversions to Objective-C pointers.
9427 if (isa<ObjCObjectPointerType>(LHSType)) {
9428 // A* -> B*
9429 if (RHSType->isObjCObjectPointerType()) {
9430 Kind = CK_BitCast;
9431 Sema::AssignConvertType result =
9432 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9433 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9434 result == Compatible &&
9435 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9436 result = IncompatibleObjCWeakRef;
9437 return result;
9438 }
9439
9440 // int or null -> A*
9441 if (RHSType->isIntegerType()) {
9442 Kind = CK_IntegralToPointer; // FIXME: null
9443 return IntToPointer;
9444 }
9445
9446 // In general, C pointers are not compatible with ObjC object pointers,
9447 // with two exceptions:
9448 if (isa<PointerType>(RHSType)) {
9449 Kind = CK_CPointerToObjCPointerCast;
9450
9451 // - conversions from 'void*'
9452 if (RHSType->isVoidPointerType()) {
9453 return Compatible;
9454 }
9455
9456 // - conversions to 'Class' from its redefinition type
9457 if (LHSType->isObjCClassType() &&
9458 Context.hasSameType(RHSType,
9459 Context.getObjCClassRedefinitionType())) {
9460 return Compatible;
9461 }
9462
9463 return IncompatiblePointer;
9464 }
9465
9466 // Only under strict condition T^ is compatible with an Objective-C pointer.
9467 if (RHSType->isBlockPointerType() &&
9468 LHSType->isBlockCompatibleObjCPointerType(Context)) {
9469 if (ConvertRHS)
9470 maybeExtendBlockObject(RHS);
9471 Kind = CK_BlockPointerToObjCPointerCast;
9472 return Compatible;
9473 }
9474
9475 return Incompatible;
9476 }
9477
9478 // Conversions from pointers that are not covered by the above.
9479 if (isa<PointerType>(RHSType)) {
9480 // T* -> _Bool
9481 if (LHSType == Context.BoolTy) {
9482 Kind = CK_PointerToBoolean;
9483 return Compatible;
9484 }
9485
9486 // T* -> int
9487 if (LHSType->isIntegerType()) {
9488 Kind = CK_PointerToIntegral;
9489 return PointerToInt;
9490 }
9491
9492 return Incompatible;
9493 }
9494
9495 // Conversions from Objective-C pointers that are not covered by the above.
9496 if (isa<ObjCObjectPointerType>(RHSType)) {
9497 // T* -> _Bool
9498 if (LHSType == Context.BoolTy) {
9499 Kind = CK_PointerToBoolean;
9500 return Compatible;
9501 }
9502
9503 // T* -> int
9504 if (LHSType->isIntegerType()) {
9505 Kind = CK_PointerToIntegral;
9506 return PointerToInt;
9507 }
9508
9509 return Incompatible;
9510 }
9511
9512 // struct A -> struct B
9513 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9514 if (Context.typesAreCompatible(LHSType, RHSType)) {
9515 Kind = CK_NoOp;
9516 return Compatible;
9517 }
9518 }
9519
9520 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9521 Kind = CK_IntToOCLSampler;
9522 return Compatible;
9523 }
9524
9525 return Incompatible;
9526}
9527
9528/// Constructs a transparent union from an expression that is
9529/// used to initialize the transparent union.
9530static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9531 ExprResult &EResult, QualType UnionType,
9532 FieldDecl *Field) {
9533 // Build an initializer list that designates the appropriate member
9534 // of the transparent union.
9535 Expr *E = EResult.get();
9536 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9537 E, SourceLocation());
9538 Initializer->setType(UnionType);
9539 Initializer->setInitializedFieldInUnion(Field);
9540
9541 // Build a compound literal constructing a value of the transparent
9542 // union type from this initializer list.
9543 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9544 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9545 VK_PRValue, Initializer, false);
9546}
9547
9548Sema::AssignConvertType
9549Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9550 ExprResult &RHS) {
9551 QualType RHSType = RHS.get()->getType();
9552
9553 // If the ArgType is a Union type, we want to handle a potential
9554 // transparent_union GCC extension.
9555 const RecordType *UT = ArgType->getAsUnionType();
9556 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9557 return Incompatible;
9558
9559 // The field to initialize within the transparent union.
9560 RecordDecl *UD = UT->getDecl();
9561 FieldDecl *InitField = nullptr;
9562 // It's compatible if the expression matches any of the fields.
9563 for (auto *it : UD->fields()) {
9564 if (it->getType()->isPointerType()) {
9565 // If the transparent union contains a pointer type, we allow:
9566 // 1) void pointer
9567 // 2) null pointer constant
9568 if (RHSType->isPointerType())
9569 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9570 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9571 InitField = it;
9572 break;
9573 }
9574
9575 if (RHS.get()->isNullPointerConstant(Context,
9576 Expr::NPC_ValueDependentIsNull)) {
9577 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9578 CK_NullToPointer);
9579 InitField = it;
9580 break;
9581 }
9582 }
9583
9584 CastKind Kind;
9585 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9586 == Compatible) {
9587 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9588 InitField = it;
9589 break;
9590 }
9591 }
9592
9593 if (!InitField)
9594 return Incompatible;
9595
9596 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9597 return Compatible;
9598}
9599
9600Sema::AssignConvertType
9601Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9602 bool Diagnose,
9603 bool DiagnoseCFAudited,
9604 bool ConvertRHS) {
9605 // We need to be able to tell the caller whether we diagnosed a problem, if
9606 // they ask us to issue diagnostics.
9607 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(static_cast<void> (0));
9608
9609 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9610 // we can't avoid *all* modifications at the moment, so we need some somewhere
9611 // to put the updated value.
9612 ExprResult LocalRHS = CallerRHS;
9613 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9614
9615 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9616 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9617 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9618 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9619 Diag(RHS.get()->getExprLoc(),
9620 diag::warn_noderef_to_dereferenceable_pointer)
9621 << RHS.get()->getSourceRange();
9622 }
9623 }
9624 }
9625
9626 if (getLangOpts().CPlusPlus) {
9627 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9628 // C++ 5.17p3: If the left operand is not of class type, the
9629 // expression is implicitly converted (C++ 4) to the
9630 // cv-unqualified type of the left operand.
9631 QualType RHSType = RHS.get()->getType();
9632 if (Diagnose) {
9633 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9634 AA_Assigning);
9635 } else {
9636 ImplicitConversionSequence ICS =
9637 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9638 /*SuppressUserConversions=*/false,
9639 AllowedExplicit::None,
9640 /*InOverloadResolution=*/false,
9641 /*CStyle=*/false,
9642 /*AllowObjCWritebackConversion=*/false);
9643 if (ICS.isFailure())
9644 return Incompatible;
9645 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9646 ICS, AA_Assigning);
9647 }
9648 if (RHS.isInvalid())
9649 return Incompatible;
9650 Sema::AssignConvertType result = Compatible;
9651 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9652 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9653 result = IncompatibleObjCWeakRef;
9654 return result;
9655 }
9656
9657 // FIXME: Currently, we fall through and treat C++ classes like C
9658 // structures.
9659 // FIXME: We also fall through for atomics; not sure what should
9660 // happen there, though.
9661 } else if (RHS.get()->getType() == Context.OverloadTy) {
9662 // As a set of extensions to C, we support overloading on functions. These
9663 // functions need to be resolved here.
9664 DeclAccessPair DAP;
9665 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9666 RHS.get(), LHSType, /*Complain=*/false, DAP))
9667 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9668 else
9669 return Incompatible;
9670 }
9671
9672 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9673 // a null pointer constant.
9674 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9675 LHSType->isBlockPointerType()) &&
9676 RHS.get()->isNullPointerConstant(Context,
9677 Expr::NPC_ValueDependentIsNull)) {
9678 if (Diagnose || ConvertRHS) {
9679 CastKind Kind;
9680 CXXCastPath Path;
9681 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9682 /*IgnoreBaseAccess=*/false, Diagnose);
9683 if (ConvertRHS)
9684 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9685 }
9686 return Compatible;
9687 }
9688
9689 // OpenCL queue_t type assignment.
9690 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9691 Context, Expr::NPC_ValueDependentIsNull)) {
9692 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9693 return Compatible;
9694 }
9695
9696 // This check seems unnatural, however it is necessary to ensure the proper
9697 // conversion of functions/arrays. If the conversion were done for all
9698 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9699 // expressions that suppress this implicit conversion (&, sizeof).
9700 //
9701 // Suppress this for references: C++ 8.5.3p5.
9702 if (!LHSType->isReferenceType()) {
9703 // FIXME: We potentially allocate here even if ConvertRHS is false.
9704 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9705 if (RHS.isInvalid())
9706 return Incompatible;
9707 }
9708 CastKind Kind;
9709 Sema::AssignConvertType result =
9710 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9711
9712 // C99 6.5.16.1p2: The value of the right operand is converted to the
9713 // type of the assignment expression.
9714 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9715 // so that we can use references in built-in functions even in C.
9716 // The getNonReferenceType() call makes sure that the resulting expression
9717 // does not have reference type.
9718 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9719 QualType Ty = LHSType.getNonLValueExprType(Context);
9720 Expr *E = RHS.get();
9721
9722 // Check for various Objective-C errors. If we are not reporting
9723 // diagnostics and just checking for errors, e.g., during overload
9724 // resolution, return Incompatible to indicate the failure.
9725 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9726 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9727 Diagnose, DiagnoseCFAudited) != ACR_okay) {
9728 if (!Diagnose)
9729 return Incompatible;
9730 }
9731 if (getLangOpts().ObjC &&
9732 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9733 E->getType(), E, Diagnose) ||
9734 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9735 if (!Diagnose)
9736 return Incompatible;
9737 // Replace the expression with a corrected version and continue so we
9738 // can find further errors.
9739 RHS = E;
9740 return Compatible;
9741 }
9742
9743 if (ConvertRHS)
9744 RHS = ImpCastExprToType(E, Ty, Kind);
9745 }
9746
9747 return result;
9748}
9749
9750namespace {
9751/// The original operand to an operator, prior to the application of the usual
9752/// arithmetic conversions and converting the arguments of a builtin operator
9753/// candidate.
9754struct OriginalOperand {
9755 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9756 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9757 Op = MTE->getSubExpr();
9758 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9759 Op = BTE->getSubExpr();
9760 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9761 Orig = ICE->getSubExprAsWritten();
9762 Conversion = ICE->getConversionFunction();
9763 }
9764 }
9765
9766 QualType getType() const { return Orig->getType(); }
9767
9768 Expr *Orig;
9769 NamedDecl *Conversion;
9770};
9771}
9772
9773QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9774 ExprResult &RHS) {
9775 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9776
9777 Diag(Loc, diag::err_typecheck_invalid_operands)
9778 << OrigLHS.getType() << OrigRHS.getType()
9779 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9780
9781 // If a user-defined conversion was applied to either of the operands prior
9782 // to applying the built-in operator rules, tell the user about it.
9783 if (OrigLHS.Conversion) {
9784 Diag(OrigLHS.Conversion->getLocation(),
9785 diag::note_typecheck_invalid_operands_converted)
9786 << 0 << LHS.get()->getType();
9787 }
9788 if (OrigRHS.Conversion) {
9789 Diag(OrigRHS.Conversion->getLocation(),
9790 diag::note_typecheck_invalid_operands_converted)
9791 << 1 << RHS.get()->getType();
9792 }
9793
9794 return QualType();
9795}
9796
9797// Diagnose cases where a scalar was implicitly converted to a vector and
9798// diagnose the underlying types. Otherwise, diagnose the error
9799// as invalid vector logical operands for non-C++ cases.
9800QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9801 ExprResult &RHS) {
9802 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9803 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9804
9805 bool LHSNatVec = LHSType->isVectorType();
9806 bool RHSNatVec = RHSType->isVectorType();
9807
9808 if (!(LHSNatVec && RHSNatVec)) {
9809 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9810 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9811 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9812 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9813 << Vector->getSourceRange();
9814 return QualType();
9815 }
9816
9817 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9818 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9819 << RHS.get()->getSourceRange();
9820
9821 return QualType();
9822}
9823
9824/// Try to convert a value of non-vector type to a vector type by converting
9825/// the type to the element type of the vector and then performing a splat.
9826/// If the language is OpenCL, we only use conversions that promote scalar
9827/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9828/// for float->int.
9829///
9830/// OpenCL V2.0 6.2.6.p2:
9831/// An error shall occur if any scalar operand type has greater rank
9832/// than the type of the vector element.
9833///
9834/// \param scalar - if non-null, actually perform the conversions
9835/// \return true if the operation fails (but without diagnosing the failure)
9836static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9837 QualType scalarTy,
9838 QualType vectorEltTy,
9839 QualType vectorTy,
9840 unsigned &DiagID) {
9841 // The conversion to apply to the scalar before splatting it,
9842 // if necessary.
9843 CastKind scalarCast = CK_NoOp;
9844
9845 if (vectorEltTy->isIntegralType(S.Context)) {
9846 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9847 (scalarTy->isIntegerType() &&
9848 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9849 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9850 return true;
9851 }
9852 if (!scalarTy->isIntegralType(S.Context))
9853 return true;
9854 scalarCast = CK_IntegralCast;
9855 } else if (vectorEltTy->isRealFloatingType()) {
9856 if (scalarTy->isRealFloatingType()) {
9857 if (S.getLangOpts().OpenCL &&
9858 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9859 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9860 return true;
9861 }
9862 scalarCast = CK_FloatingCast;
9863 }
9864 else if (scalarTy->isIntegralType(S.Context))
9865 scalarCast = CK_IntegralToFloating;
9866 else
9867 return true;
9868 } else {
9869 return true;
9870 }
9871
9872 // Adjust scalar if desired.
9873 if (scalar) {
9874 if (scalarCast != CK_NoOp)
9875 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9876 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9877 }
9878 return false;
9879}
9880
9881/// Convert vector E to a vector with the same number of elements but different
9882/// element type.
9883static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9884 const auto *VecTy = E->getType()->getAs<VectorType>();
9885 assert(VecTy && "Expression E must be a vector")(static_cast<void> (0));
9886 QualType NewVecTy = S.Context.getVectorType(ElementType,
9887 VecTy->getNumElements(),
9888 VecTy->getVectorKind());
9889
9890 // Look through the implicit cast. Return the subexpression if its type is
9891 // NewVecTy.
9892 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9893 if (ICE->getSubExpr()->getType() == NewVecTy)
9894 return ICE->getSubExpr();
9895
9896 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9897 return S.ImpCastExprToType(E, NewVecTy, Cast);
9898}
9899
9900/// Test if a (constant) integer Int can be casted to another integer type
9901/// IntTy without losing precision.
9902static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9903 QualType OtherIntTy) {
9904 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9905
9906 // Reject cases where the value of the Int is unknown as that would
9907 // possibly cause truncation, but accept cases where the scalar can be
9908 // demoted without loss of precision.
9909 Expr::EvalResult EVResult;
9910 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9911 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9912 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9913 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9914
9915 if (CstInt) {
9916 // If the scalar is constant and is of a higher order and has more active
9917 // bits that the vector element type, reject it.
9918 llvm::APSInt Result = EVResult.Val.getInt();
9919 unsigned NumBits = IntSigned
9920 ? (Result.isNegative() ? Result.getMinSignedBits()
9921 : Result.getActiveBits())
9922 : Result.getActiveBits();
9923 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9924 return true;
9925
9926 // If the signedness of the scalar type and the vector element type
9927 // differs and the number of bits is greater than that of the vector
9928 // element reject it.
9929 return (IntSigned != OtherIntSigned &&
9930 NumBits > S.Context.getIntWidth(OtherIntTy));
9931 }
9932
9933 // Reject cases where the value of the scalar is not constant and it's
9934 // order is greater than that of the vector element type.
9935 return (Order < 0);
9936}
9937
9938/// Test if a (constant) integer Int can be casted to floating point type
9939/// FloatTy without losing precision.
9940static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9941 QualType FloatTy) {
9942 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9943
9944 // Determine if the integer constant can be expressed as a floating point
9945 // number of the appropriate type.
9946 Expr::EvalResult EVResult;
9947 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9948
9949 uint64_t Bits = 0;
9950 if (CstInt) {
9951 // Reject constants that would be truncated if they were converted to
9952 // the floating point type. Test by simple to/from conversion.
9953 // FIXME: Ideally the conversion to an APFloat and from an APFloat
9954 // could be avoided if there was a convertFromAPInt method
9955 // which could signal back if implicit truncation occurred.
9956 llvm::APSInt Result = EVResult.Val.getInt();
9957 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9958 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9959 llvm::APFloat::rmTowardZero);
9960 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9961 !IntTy->hasSignedIntegerRepresentation());
9962 bool Ignored = false;
9963 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9964 &Ignored);
9965 if (Result != ConvertBack)
9966 return true;
9967 } else {
9968 // Reject types that cannot be fully encoded into the mantissa of
9969 // the float.
9970 Bits = S.Context.getTypeSize(IntTy);
9971 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9972 S.Context.getFloatTypeSemantics(FloatTy));
9973 if (Bits > FloatPrec)
9974 return true;
9975 }
9976
9977 return false;
9978}
9979
9980/// Attempt to convert and splat Scalar into a vector whose types matches
9981/// Vector following GCC conversion rules. The rule is that implicit
9982/// conversion can occur when Scalar can be casted to match Vector's element
9983/// type without causing truncation of Scalar.
9984static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9985 ExprResult *Vector) {
9986 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9987 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9988 const VectorType *VT = VectorTy->getAs<VectorType>();
9989
9990 assert(!isa<ExtVectorType>(VT) &&(static_cast<void> (0))
9991 "ExtVectorTypes should not be handled here!")(static_cast<void> (0));
9992
9993 QualType VectorEltTy = VT->getElementType();
9994
9995 // Reject cases where the vector element type or the scalar element type are
9996 // not integral or floating point types.
9997 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9998 return true;
9999
10000 // The conversion to apply to the scalar before splatting it,
10001 // if necessary.
10002 CastKind ScalarCast = CK_NoOp;
10003
10004 // Accept cases where the vector elements are integers and the scalar is
10005 // an integer.
10006 // FIXME: Notionally if the scalar was a floating point value with a precise
10007 // integral representation, we could cast it to an appropriate integer
10008 // type and then perform the rest of the checks here. GCC will perform
10009 // this conversion in some cases as determined by the input language.
10010 // We should accept it on a language independent basis.
10011 if (VectorEltTy->isIntegralType(S.Context) &&
10012 ScalarTy->isIntegralType(S.Context) &&
10013 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10014
10015 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10016 return true;
10017
10018 ScalarCast = CK_IntegralCast;
10019 } else if (VectorEltTy->isIntegralType(S.Context) &&
10020 ScalarTy->isRealFloatingType()) {
10021 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10022 ScalarCast = CK_FloatingToIntegral;
10023 else
10024 return true;
10025 } else if (VectorEltTy->isRealFloatingType()) {
10026 if (ScalarTy->isRealFloatingType()) {
10027
10028 // Reject cases where the scalar type is not a constant and has a higher
10029 // Order than the vector element type.
10030 llvm::APFloat Result(0.0);
10031
10032 // Determine whether this is a constant scalar. In the event that the
10033 // value is dependent (and thus cannot be evaluated by the constant
10034 // evaluator), skip the evaluation. This will then diagnose once the
10035 // expression is instantiated.
10036 bool CstScalar = Scalar->get()->isValueDependent() ||
10037 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10038 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10039 if (!CstScalar && Order < 0)
10040 return true;
10041
10042 // If the scalar cannot be safely casted to the vector element type,
10043 // reject it.
10044 if (CstScalar) {
10045 bool Truncated = false;
10046 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10047 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10048 if (Truncated)
10049 return true;
10050 }
10051
10052 ScalarCast = CK_FloatingCast;
10053 } else if (ScalarTy->isIntegralType(S.Context)) {
10054 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10055 return true;
10056
10057 ScalarCast = CK_IntegralToFloating;
10058 } else
10059 return true;
10060 } else if (ScalarTy->isEnumeralType())
10061 return true;
10062
10063 // Adjust scalar if desired.
10064 if (Scalar) {
10065 if (ScalarCast != CK_NoOp)
10066 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10067 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10068 }
10069 return false;
10070}
10071
10072QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10073 SourceLocation Loc, bool IsCompAssign,
10074 bool AllowBothBool,
10075 bool AllowBoolConversions) {
10076 if (!IsCompAssign) {
10077 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10078 if (LHS.isInvalid())
10079 return QualType();
10080 }
10081 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10082 if (RHS.isInvalid())
10083 return QualType();
10084
10085 // For conversion purposes, we ignore any qualifiers.
10086 // For example, "const float" and "float" are equivalent.
10087 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10088 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10089
10090 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10091 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10092 assert(LHSVecType || RHSVecType)(static_cast<void> (0));
10093
10094 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10095 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10096 return InvalidOperands(Loc, LHS, RHS);
10097
10098 // AltiVec-style "vector bool op vector bool" combinations are allowed
10099 // for some operators but not others.
10100 if (!AllowBothBool &&
10101 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10102 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10103 return InvalidOperands(Loc, LHS, RHS);
10104
10105 // If the vector types are identical, return.
10106 if (Context.hasSameType(LHSType, RHSType))
10107 return LHSType;
10108
10109 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10110 if (LHSVecType && RHSVecType &&
10111 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10112 if (isa<ExtVectorType>(LHSVecType)) {
10113 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10114 return LHSType;
10115 }
10116
10117 if (!IsCompAssign)
10118 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10119 return RHSType;
10120 }
10121
10122 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10123 // can be mixed, with the result being the non-bool type. The non-bool
10124 // operand must have integer element type.
10125 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10126 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10127 (Context.getTypeSize(LHSVecType->getElementType()) ==
10128 Context.getTypeSize(RHSVecType->getElementType()))) {
10129 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10130 LHSVecType->getElementType()->isIntegerType() &&
10131 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10132 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10133 return LHSType;
10134 }
10135 if (!IsCompAssign &&
10136 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10137 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10138 RHSVecType->getElementType()->isIntegerType()) {
10139 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10140 return RHSType;
10141 }
10142 }
10143
10144 // Expressions containing fixed-length and sizeless SVE vectors are invalid
10145 // since the ambiguity can affect the ABI.
10146 auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10147 const VectorType *VecType = SecondType->getAs<VectorType>();
10148 return FirstType->isSizelessBuiltinType() && VecType &&
10149 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10150 VecType->getVectorKind() ==
10151 VectorType::SveFixedLengthPredicateVector);
10152 };
10153
10154 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10155 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10156 return QualType();
10157 }
10158
10159 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10160 // since the ambiguity can affect the ABI.
10161 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10162 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10163 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10164
10165 if (FirstVecType && SecondVecType)
10166 return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10167 (SecondVecType->getVectorKind() ==
10168 VectorType::SveFixedLengthDataVector ||
10169 SecondVecType->getVectorKind() ==
10170 VectorType::SveFixedLengthPredicateVector);
10171
10172 return FirstType->isSizelessBuiltinType() && SecondVecType &&
10173 SecondVecType->getVectorKind() == VectorType::GenericVector;
10174 };
10175
10176 if (IsSveGnuConversion(LHSType, RHSType) ||
10177 IsSveGnuConversion(RHSType, LHSType)) {
10178 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10179 return QualType();
10180 }
10181
10182 // If there's a vector type and a scalar, try to convert the scalar to
10183 // the vector element type and splat.
10184 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10185 if (!RHSVecType) {
10186 if (isa<ExtVectorType>(LHSVecType)) {
10187 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10188 LHSVecType->getElementType(), LHSType,
10189 DiagID))
10190 return LHSType;
10191 } else {
10192 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10193 return LHSType;
10194 }
10195 }
10196 if (!LHSVecType) {
10197 if (isa<ExtVectorType>(RHSVecType)) {
10198 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10199 LHSType, RHSVecType->getElementType(),
10200 RHSType, DiagID))
10201 return RHSType;
10202 } else {
10203 if (LHS.get()->isLValue() ||
10204 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10205 return RHSType;
10206 }
10207 }
10208
10209 // FIXME: The code below also handles conversion between vectors and
10210 // non-scalars, we should break this down into fine grained specific checks
10211 // and emit proper diagnostics.
10212 QualType VecType = LHSVecType ? LHSType : RHSType;
10213 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10214 QualType OtherType = LHSVecType ? RHSType : LHSType;
10215 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10216 if (isLaxVectorConversion(OtherType, VecType)) {
10217 // If we're allowing lax vector conversions, only the total (data) size
10218 // needs to be the same. For non compound assignment, if one of the types is
10219 // scalar, the result is always the vector type.
10220 if (!IsCompAssign) {
10221 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10222 return VecType;
10223 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10224 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10225 // type. Note that this is already done by non-compound assignments in
10226 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10227 // <1 x T> -> T. The result is also a vector type.
10228 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10229 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10230 ExprResult *RHSExpr = &RHS;
10231 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10232 return VecType;
10233 }
10234 }
10235
10236 // Okay, the expression is invalid.
10237
10238 // If there's a non-vector, non-real operand, diagnose that.
10239 if ((!RHSVecType && !RHSType->isRealType()) ||
10240 (!LHSVecType && !LHSType->isRealType())) {
10241 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10242 << LHSType << RHSType
10243 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10244 return QualType();
10245 }
10246
10247 // OpenCL V1.1 6.2.6.p1:
10248 // If the operands are of more than one vector type, then an error shall
10249 // occur. Implicit conversions between vector types are not permitted, per
10250 // section 6.2.1.
10251 if (getLangOpts().OpenCL &&
10252 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10253 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10254 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10255 << RHSType;
10256 return QualType();
10257 }
10258
10259
10260 // If there is a vector type that is not a ExtVector and a scalar, we reach
10261 // this point if scalar could not be converted to the vector's element type
10262 // without truncation.
10263 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10264 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10265 QualType Scalar = LHSVecType ? RHSType : LHSType;
10266 QualType Vector = LHSVecType ? LHSType : RHSType;
10267 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10268 Diag(Loc,
10269 diag::err_typecheck_vector_not_convertable_implict_truncation)
10270 << ScalarOrVector << Scalar << Vector;
10271
10272 return QualType();
10273 }
10274
10275 // Otherwise, use the generic diagnostic.
10276 Diag(Loc, DiagID)
10277 << LHSType << RHSType
10278 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10279 return QualType();
10280}
10281
10282// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10283// expression. These are mainly cases where the null pointer is used as an
10284// integer instead of a pointer.
10285static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10286 SourceLocation Loc, bool IsCompare) {
10287 // The canonical way to check for a GNU null is with isNullPointerConstant,
10288 // but we use a bit of a hack here for speed; this is a relatively
10289 // hot path, and isNullPointerConstant is slow.
10290 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10291 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10292
10293 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10294
10295 // Avoid analyzing cases where the result will either be invalid (and
10296 // diagnosed as such) or entirely valid and not something to warn about.
10297 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10298 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10299 return;
10300
10301 // Comparison operations would not make sense with a null pointer no matter
10302 // what the other expression is.
10303 if (!IsCompare) {
10304 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10305 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10306 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10307 return;
10308 }
10309
10310 // The rest of the operations only make sense with a null pointer
10311 // if the other expression is a pointer.
10312 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10313 NonNullType->canDecayToPointerType())
10314 return;
10315
10316 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10317 << LHSNull /* LHS is NULL */ << NonNullType
10318 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10319}
10320
10321static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10322 SourceLocation Loc) {
10323 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10324 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10325 if (!LUE || !RUE)
10326 return;
10327 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10328 RUE->getKind() != UETT_SizeOf)
10329 return;
10330
10331 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10332 QualType LHSTy = LHSArg->getType();
10333 QualType RHSTy;
10334
10335 if (RUE->isArgumentType())
10336 RHSTy = RUE->getArgumentType().getNonReferenceType();
10337 else
10338 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10339
10340 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10341 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10342 return;
10343
10344 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10345 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10346 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10347 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10348 << LHSArgDecl;
10349 }
10350 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10351 QualType ArrayElemTy = ArrayTy->getElementType();
10352 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10353 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10354 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10355 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10356 return;
10357 S.Diag(Loc, diag::warn_division_sizeof_array)
10358 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10359 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10360 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10361 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10362 << LHSArgDecl;
10363 }
10364
10365 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10366 }
10367}
10368
10369static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10370 ExprResult &RHS,
10371 SourceLocation Loc, bool IsDiv) {
10372 // Check for division/remainder by zero.
10373 Expr::EvalResult RHSValue;
10374 if (!RHS.get()->isValueDependent() &&
10375 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10376 RHSValue.Val.getInt() == 0)
10377 S.DiagRuntimeBehavior(Loc, RHS.get(),
10378 S.PDiag(diag::warn_remainder_division_by_zero)
10379 << IsDiv << RHS.get()->getSourceRange());
10380}
10381
10382QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10383 SourceLocation Loc,
10384 bool IsCompAssign, bool IsDiv) {
10385 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10386
10387 QualType LHSTy = LHS.get()->getType();
10388 QualType RHSTy = RHS.get()->getType();
10389 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10390 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10391 /*AllowBothBool*/getLangOpts().AltiVec,
10392 /*AllowBoolConversions*/false);
10393 if (!IsDiv &&
10394 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10395 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10396 // For division, only matrix-by-scalar is supported. Other combinations with
10397 // matrix types are invalid.
10398 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10399 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10400
10401 QualType compType = UsualArithmeticConversions(
10402 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10403 if (LHS.isInvalid() || RHS.isInvalid())
10404 return QualType();
10405
10406
10407 if (compType.isNull() || !compType->isArithmeticType())
10408 return InvalidOperands(Loc, LHS, RHS);
10409 if (IsDiv) {
10410 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10411 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10412 }
10413 return compType;
10414}
10415
10416QualType Sema::CheckRemainderOperands(
10417 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10418 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10419
10420 if (LHS.get()->getType()->isVectorType() ||
10421 RHS.get()->getType()->isVectorType()) {
10422 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10423 RHS.get()->getType()->hasIntegerRepresentation())
10424 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10425 /*AllowBothBool*/getLangOpts().AltiVec,
10426 /*AllowBoolConversions*/false);
10427 return InvalidOperands(Loc, LHS, RHS);
10428 }
10429
10430 QualType compType = UsualArithmeticConversions(
10431 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10432 if (LHS.isInvalid() || RHS.isInvalid())
10433 return QualType();
10434
10435 if (compType.isNull() || !compType->isIntegerType())
10436 return InvalidOperands(Loc, LHS, RHS);
10437 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10438 return compType;
10439}
10440
10441/// Diagnose invalid arithmetic on two void pointers.
10442static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10443 Expr *LHSExpr, Expr *RHSExpr) {
10444 S.Diag(Loc, S.getLangOpts().CPlusPlus
10445 ? diag::err_typecheck_pointer_arith_void_type
10446 : diag::ext_gnu_void_ptr)
10447 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10448 << RHSExpr->getSourceRange();
10449}
10450
10451/// Diagnose invalid arithmetic on a void pointer.
10452static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10453 Expr *Pointer) {
10454 S.Diag(Loc, S.getLangOpts().CPlusPlus
10455 ? diag::err_typecheck_pointer_arith_void_type
10456 : diag::ext_gnu_void_ptr)
10457 << 0 /* one pointer */ << Pointer->getSourceRange();
10458}
10459
10460/// Diagnose invalid arithmetic on a null pointer.
10461///
10462/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10463/// idiom, which we recognize as a GNU extension.
10464///
10465static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10466 Expr *Pointer, bool IsGNUIdiom) {
10467 if (IsGNUIdiom)
10468 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10469 << Pointer->getSourceRange();
10470 else
10471 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10472 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10473}
10474
10475/// Diagnose invalid subraction on a null pointer.
10476///
10477static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10478 Expr *Pointer, bool BothNull) {
10479 // Null - null is valid in C++ [expr.add]p7
10480 if (BothNull && S.getLangOpts().CPlusPlus)
10481 return;
10482
10483 // Is this s a macro from a system header?
10484 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10485 return;
10486
10487 S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10488 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10489}
10490
10491/// Diagnose invalid arithmetic on two function pointers.
10492static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10493 Expr *LHS, Expr *RHS) {
10494 assert(LHS->getType()->isAnyPointerType())(static_cast<void> (0));
10495 assert(RHS->getType()->isAnyPointerType())(static_cast<void> (0));
10496 S.Diag(Loc, S.getLangOpts().CPlusPlus
10497 ? diag::err_typecheck_pointer_arith_function_type
10498 : diag::ext_gnu_ptr_func_arith)
10499 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10500 // We only show the second type if it differs from the first.
10501 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10502 RHS->getType())
10503 << RHS->getType()->getPointeeType()
10504 << LHS->getSourceRange() << RHS->getSourceRange();
10505}
10506
10507/// Diagnose invalid arithmetic on a function pointer.
10508static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10509 Expr *Pointer) {
10510 assert(Pointer->getType()->isAnyPointerType())(static_cast<void> (0));
10511 S.Diag(Loc, S.getLangOpts().CPlusPlus
10512 ? diag::err_typecheck_pointer_arith_function_type
10513 : diag::ext_gnu_ptr_func_arith)
10514 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10515 << 0 /* one pointer, so only one type */
10516 << Pointer->getSourceRange();
10517}
10518
10519/// Emit error if Operand is incomplete pointer type
10520///
10521/// \returns True if pointer has incomplete type
10522static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10523 Expr *Operand) {
10524 QualType ResType = Operand->getType();
10525 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10526 ResType = ResAtomicType->getValueType();
10527
10528 assert(ResType->isAnyPointerType() && !ResType->isDependentType())(static_cast<void> (0));
10529 QualType PointeeTy = ResType->getPointeeType();
10530 return S.RequireCompleteSizedType(
10531 Loc, PointeeTy,
10532 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10533 Operand->getSourceRange());
10534}
10535
10536/// Check the validity of an arithmetic pointer operand.
10537///
10538/// If the operand has pointer type, this code will check for pointer types
10539/// which are invalid in arithmetic operations. These will be diagnosed
10540/// appropriately, including whether or not the use is supported as an
10541/// extension.
10542///
10543/// \returns True when the operand is valid to use (even if as an extension).
10544static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10545 Expr *Operand) {
10546 QualType ResType = Operand->getType();
10547 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10548 ResType = ResAtomicType->getValueType();
10549
10550 if (!ResType->isAnyPointerType()) return true;
10551
10552 QualType PointeeTy = ResType->getPointeeType();
10553 if (PointeeTy->isVoidType()) {
10554 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10555 return !S.getLangOpts().CPlusPlus;
10556 }
10557 if (PointeeTy->isFunctionType()) {
10558 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10559 return !S.getLangOpts().CPlusPlus;
10560 }
10561
10562 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10563
10564 return true;
10565}
10566
10567/// Check the validity of a binary arithmetic operation w.r.t. pointer
10568/// operands.
10569///
10570/// This routine will diagnose any invalid arithmetic on pointer operands much
10571/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10572/// for emitting a single diagnostic even for operations where both LHS and RHS
10573/// are (potentially problematic) pointers.
10574///
10575/// \returns True when the operand is valid to use (even if as an extension).
10576static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10577 Expr *LHSExpr, Expr *RHSExpr) {
10578 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10579 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10580 if (!isLHSPointer && !isRHSPointer) return true;
10581
10582 QualType LHSPointeeTy, RHSPointeeTy;
10583 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10584 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10585
10586 // if both are pointers check if operation is valid wrt address spaces
10587 if (isLHSPointer && isRHSPointer) {
10588 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10589 S.Diag(Loc,
10590 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10591 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10592 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10593 return false;
10594 }
10595 }
10596
10597 // Check for arithmetic on pointers to incomplete types.
10598 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10599 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10600 if (isLHSVoidPtr || isRHSVoidPtr) {
10601 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10602 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10603 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10604
10605 return !S.getLangOpts().CPlusPlus;
10606 }
10607
10608 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10609 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10610 if (isLHSFuncPtr || isRHSFuncPtr) {
10611 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10612 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10613 RHSExpr);
10614 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10615
10616 return !S.getLangOpts().CPlusPlus;
10617 }
10618
10619 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10620 return false;
10621 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10622 return false;
10623
10624 return true;
10625}
10626
10627/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10628/// literal.
10629static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10630 Expr *LHSExpr, Expr *RHSExpr) {
10631 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10632 Expr* IndexExpr = RHSExpr;
10633 if (!StrExpr) {
10634 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10635 IndexExpr = LHSExpr;
10636 }
10637
10638 bool IsStringPlusInt = StrExpr &&
10639 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10640 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10641 return;
10642
10643 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10644 Self.Diag(OpLoc, diag::warn_string_plus_int)
10645 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10646
10647 // Only print a fixit for "str" + int, not for int + "str".
10648 if (IndexExpr == RHSExpr) {
10649 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10650 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10651 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10652 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10653 << FixItHint::CreateInsertion(EndLoc, "]");
10654 } else
10655 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10656}
10657
10658/// Emit a warning when adding a char literal to a string.
10659static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10660 Expr *LHSExpr, Expr *RHSExpr) {
10661 const Expr *StringRefExpr = LHSExpr;
10662 const CharacterLiteral *CharExpr =
10663 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10664
10665 if (!CharExpr) {
10666 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10667 StringRefExpr = RHSExpr;
10668 }
10669
10670 if (!CharExpr || !StringRefExpr)
10671 return;
10672
10673 const QualType StringType = StringRefExpr->getType();
10674
10675 // Return if not a PointerType.
10676 if (!StringType->isAnyPointerType())
10677 return;
10678
10679 // Return if not a CharacterType.
10680 if (!StringType->getPointeeType()->isAnyCharacterType())
10681 return;
10682
10683 ASTContext &Ctx = Self.getASTContext();
10684 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10685
10686 const QualType CharType = CharExpr->getType();
10687 if (!CharType->isAnyCharacterType() &&
10688 CharType->isIntegerType() &&
10689 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10690 Self.Diag(OpLoc, diag::warn_string_plus_char)
10691 << DiagRange << Ctx.CharTy;
10692 } else {
10693 Self.Diag(OpLoc, diag::warn_string_plus_char)
10694 << DiagRange << CharExpr->getType();
10695 }
10696
10697 // Only print a fixit for str + char, not for char + str.
10698 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10699 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10700 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10701 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10702 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10703 << FixItHint::CreateInsertion(EndLoc, "]");
10704 } else {
10705 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10706 }
10707}
10708
10709/// Emit error when two pointers are incompatible.
10710static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10711 Expr *LHSExpr, Expr *RHSExpr) {
10712 assert(LHSExpr->getType()->isAnyPointerType())(static_cast<void> (0));
10713 assert(RHSExpr->getType()->isAnyPointerType())(static_cast<void> (0));
10714 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10715 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10716 << RHSExpr->getSourceRange();
10717}
10718
10719// C99 6.5.6
10720QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10721 SourceLocation Loc, BinaryOperatorKind Opc,
10722 QualType* CompLHSTy) {
10723 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10724
10725 if (LHS.get()->getType()->isVectorType() ||
10726 RHS.get()->getType()->isVectorType()) {
10727 QualType compType = CheckVectorOperands(
10728 LHS, RHS, Loc, CompLHSTy,
10729 /*AllowBothBool*/getLangOpts().AltiVec,
10730 /*AllowBoolConversions*/getLangOpts().ZVector);
10731 if (CompLHSTy) *CompLHSTy = compType;
10732 return compType;
10733 }
10734
10735 if (LHS.get()->getType()->isConstantMatrixType() ||
10736 RHS.get()->getType()->isConstantMatrixType()) {
10737 QualType compType =
10738 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10739 if (CompLHSTy)
10740 *CompLHSTy = compType;
10741 return compType;
10742 }
10743
10744 QualType compType = UsualArithmeticConversions(
10745 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10746 if (LHS.isInvalid() || RHS.isInvalid())
10747 return QualType();
10748
10749 // Diagnose "string literal" '+' int and string '+' "char literal".
10750 if (Opc == BO_Add) {
10751 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10752 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10753 }
10754
10755 // handle the common case first (both operands are arithmetic).
10756 if (!compType.isNull() && compType->isArithmeticType()) {
10757 if (CompLHSTy) *CompLHSTy = compType;
10758 return compType;
10759 }
10760
10761 // Type-checking. Ultimately the pointer's going to be in PExp;
10762 // note that we bias towards the LHS being the pointer.
10763 Expr *PExp = LHS.get(), *IExp = RHS.get();
10764
10765 bool isObjCPointer;
10766 if (PExp->getType()->isPointerType()) {
10767 isObjCPointer = false;
10768 } else if (PExp->getType()->isObjCObjectPointerType()) {
10769 isObjCPointer = true;
10770 } else {
10771 std::swap(PExp, IExp);
10772 if (PExp->getType()->isPointerType()) {
10773 isObjCPointer = false;
10774 } else if (PExp->getType()->isObjCObjectPointerType()) {
10775 isObjCPointer = true;
10776 } else {
10777 return InvalidOperands(Loc, LHS, RHS);
10778 }
10779 }
10780 assert(PExp->getType()->isAnyPointerType())(static_cast<void> (0));
10781
10782 if (!IExp->getType()->isIntegerType())
10783 return InvalidOperands(Loc, LHS, RHS);
10784
10785 // Adding to a null pointer results in undefined behavior.
10786 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10787 Context, Expr::NPC_ValueDependentIsNotNull)) {
10788 // In C++ adding zero to a null pointer is defined.
10789 Expr::EvalResult KnownVal;
10790 if (!getLangOpts().CPlusPlus ||
10791 (!IExp->isValueDependent() &&
10792 (!IExp->EvaluateAsInt(KnownVal, Context) ||
10793 KnownVal.Val.getInt() != 0))) {
10794 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10795 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10796 Context, BO_Add, PExp, IExp);
10797 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10798 }
10799 }
10800
10801 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10802 return QualType();
10803
10804 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10805 return QualType();
10806
10807 // Check array bounds for pointer arithemtic
10808 CheckArrayAccess(PExp, IExp);
10809
10810 if (CompLHSTy) {
10811 QualType LHSTy = Context.isPromotableBitField(LHS.get());
10812 if (LHSTy.isNull()) {
10813 LHSTy = LHS.get()->getType();
10814 if (LHSTy->isPromotableIntegerType())
10815 LHSTy = Context.getPromotedIntegerType(LHSTy);
10816 }
10817 *CompLHSTy = LHSTy;
10818 }
10819
10820 return PExp->getType();
10821}
10822
10823// C99 6.5.6
10824QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10825 SourceLocation Loc,
10826 QualType* CompLHSTy) {
10827 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10828
10829 if (LHS.get()->getType()->isVectorType() ||
10830 RHS.get()->getType()->isVectorType()) {
10831 QualType compType = CheckVectorOperands(
10832 LHS, RHS, Loc, CompLHSTy,
10833 /*AllowBothBool*/getLangOpts().AltiVec,
10834 /*AllowBoolConversions*/getLangOpts().ZVector);
10835 if (CompLHSTy) *CompLHSTy = compType;
10836 return compType;
10837 }
10838
10839 if (LHS.get()->getType()->isConstantMatrixType() ||
10840 RHS.get()->getType()->isConstantMatrixType()) {
10841 QualType compType =
10842 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10843 if (CompLHSTy)
10844 *CompLHSTy = compType;
10845 return compType;
10846 }
10847
10848 QualType compType = UsualArithmeticConversions(
10849 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10850 if (LHS.isInvalid() || RHS.isInvalid())
10851 return QualType();
10852
10853 // Enforce type constraints: C99 6.5.6p3.
10854
10855 // Handle the common case first (both operands are arithmetic).
10856 if (!compType.isNull() && compType->isArithmeticType()) {
10857 if (CompLHSTy) *CompLHSTy = compType;
10858 return compType;
10859 }
10860
10861 // Either ptr - int or ptr - ptr.
10862 if (LHS.get()->getType()->isAnyPointerType()) {
10863 QualType lpointee = LHS.get()->getType()->getPointeeType();
10864
10865 // Diagnose bad cases where we step over interface counts.
10866 if (LHS.get()->getType()->isObjCObjectPointerType() &&
10867 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10868 return QualType();
10869
10870 // The result type of a pointer-int computation is the pointer type.
10871 if (RHS.get()->getType()->isIntegerType()) {
10872 // Subtracting from a null pointer should produce a warning.
10873 // The last argument to the diagnose call says this doesn't match the
10874 // GNU int-to-pointer idiom.
10875 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10876 Expr::NPC_ValueDependentIsNotNull)) {
10877 // In C++ adding zero to a null pointer is defined.
10878 Expr::EvalResult KnownVal;
10879 if (!getLangOpts().CPlusPlus ||
10880 (!RHS.get()->isValueDependent() &&
10881 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10882 KnownVal.Val.getInt() != 0))) {
10883 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10884 }
10885 }
10886
10887 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10888 return QualType();
10889
10890 // Check array bounds for pointer arithemtic
10891 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10892 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10893
10894 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10895 return LHS.get()->getType();
10896 }
10897
10898 // Handle pointer-pointer subtractions.
10899 if (const PointerType *RHSPTy
10900 = RHS.get()->getType()->getAs<PointerType>()) {
10901 QualType rpointee = RHSPTy->getPointeeType();
10902
10903 if (getLangOpts().CPlusPlus) {
10904 // Pointee types must be the same: C++ [expr.add]
10905 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10906 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10907 }
10908 } else {
10909 // Pointee types must be compatible C99 6.5.6p3
10910 if (!Context.typesAreCompatible(
10911 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10912 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10913 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10914 return QualType();
10915 }
10916 }
10917
10918 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10919 LHS.get(), RHS.get()))
10920 return QualType();
10921
10922 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
10923 Context, Expr::NPC_ValueDependentIsNotNull);
10924 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
10925 Context, Expr::NPC_ValueDependentIsNotNull);
10926
10927 // Subtracting nullptr or from nullptr is suspect
10928 if (LHSIsNullPtr)
10929 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
10930 if (RHSIsNullPtr)
10931 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
10932
10933 // The pointee type may have zero size. As an extension, a structure or
10934 // union may have zero size or an array may have zero length. In this
10935 // case subtraction does not make sense.
10936 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10937 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10938 if (ElementSize.isZero()) {
10939 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10940 << rpointee.getUnqualifiedType()
10941 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10942 }
10943 }
10944
10945 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10946 return Context.getPointerDiffType();
10947 }
10948 }
10949
10950 return InvalidOperands(Loc, LHS, RHS);
10951}
10952
10953static bool isScopedEnumerationType(QualType T) {
10954 if (const EnumType *ET = T->getAs<EnumType>())
10955 return ET->getDecl()->isScoped();
10956 return false;
10957}
10958
10959static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10960 SourceLocation Loc, BinaryOperatorKind Opc,
10961 QualType LHSType) {
10962 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10963 // so skip remaining warnings as we don't want to modify values within Sema.
10964 if (S.getLangOpts().OpenCL)
10965 return;
10966
10967 // Check right/shifter operand
10968 Expr::EvalResult RHSResult;
10969 if (RHS.get()->isValueDependent() ||
10970 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10971 return;
10972 llvm::APSInt Right = RHSResult.Val.getInt();
10973
10974 if (Right.isNegative()) {
10975 S.DiagRuntimeBehavior(Loc, RHS.get(),
10976 S.PDiag(diag::warn_shift_negative)
10977 << RHS.get()->getSourceRange());
10978 return;
10979 }
10980
10981 QualType LHSExprType = LHS.get()->getType();
10982 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10983 if (LHSExprType->isExtIntType())
10984 LeftSize = S.Context.getIntWidth(LHSExprType);
10985 else if (LHSExprType->isFixedPointType()) {
10986 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10987 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10988 }
10989 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10990 if (Right.uge(LeftBits)) {
10991 S.DiagRuntimeBehavior(Loc, RHS.get(),
10992 S.PDiag(diag::warn_shift_gt_typewidth)
10993 << RHS.get()->getSourceRange());
10994 return;
10995 }
10996
10997 // FIXME: We probably need to handle fixed point types specially here.
10998 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10999 return;
11000
11001 // When left shifting an ICE which is signed, we can check for overflow which
11002 // according to C++ standards prior to C++2a has undefined behavior
11003 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11004 // more than the maximum value representable in the result type, so never
11005 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11006 // expression is still probably a bug.)
11007 Expr::EvalResult LHSResult;
11008 if (LHS.get()->isValueDependent() ||
11009 LHSType->hasUnsignedIntegerRepresentation() ||
11010 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11011 return;
11012 llvm::APSInt Left = LHSResult.Val.getInt();
11013
11014 // If LHS does not have a signed type and non-negative value
11015 // then, the behavior is undefined before C++2a. Warn about it.
11016 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
11017 !S.getLangOpts().CPlusPlus20) {
11018 S.DiagRuntimeBehavior(Loc, LHS.get(),
11019 S.PDiag(diag::warn_shift_lhs_negative)
11020 << LHS.get()->getSourceRange());
11021 return;
11022 }
11023
11024 llvm::APInt ResultBits =
11025 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11026 if (LeftBits.uge(ResultBits))
11027 return;
11028 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11029 Result = Result.shl(Right);
11030
11031 // Print the bit representation of the signed integer as an unsigned
11032 // hexadecimal number.
11033 SmallString<40> HexResult;
11034 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11035
11036 // If we are only missing a sign bit, this is less likely to result in actual
11037 // bugs -- if the result is cast back to an unsigned type, it will have the
11038 // expected value. Thus we place this behind a different warning that can be
11039 // turned off separately if needed.
11040 if (LeftBits == ResultBits - 1) {
11041 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11042 << HexResult << LHSType
11043 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11044 return;
11045 }
11046
11047 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11048 << HexResult.str() << Result.getMinSignedBits() << LHSType
11049 << Left.getBitWidth() << LHS.get()->getSourceRange()
11050 << RHS.get()->getSourceRange();
11051}
11052
11053/// Return the resulting type when a vector is shifted
11054/// by a scalar or vector shift amount.
11055static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11056 SourceLocation Loc, bool IsCompAssign) {
11057 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11058 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11059 !LHS.get()->getType()->isVectorType()) {
11060 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11061 << RHS.get()->getType() << LHS.get()->getType()
11062 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11063 return QualType();
11064 }
11065
11066 if (!IsCompAssign) {
11067 LHS = S.UsualUnaryConversions(LHS.get());
11068 if (LHS.isInvalid()) return QualType();
11069 }
11070
11071 RHS = S.UsualUnaryConversions(RHS.get());
11072 if (RHS.isInvalid()) return QualType();
11073
11074 QualType LHSType = LHS.get()->getType();
11075 // Note that LHS might be a scalar because the routine calls not only in
11076 // OpenCL case.
11077 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11078 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11079
11080 // Note that RHS might not be a vector.
11081 QualType RHSType = RHS.get()->getType();
11082 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11083 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11084
11085 // The operands need to be integers.
11086 if (!LHSEleType->isIntegerType()) {
11087 S.Diag(Loc, diag::err_typecheck_expect_int)
11088 << LHS.get()->getType() << LHS.get()->getSourceRange();
11089 return QualType();
11090 }
11091
11092 if (!RHSEleType->isIntegerType()) {
11093 S.Diag(Loc, diag::err_typecheck_expect_int)
11094 << RHS.get()->getType() << RHS.get()->getSourceRange();
11095 return QualType();
11096 }
11097
11098 if (!LHSVecTy) {
11099 assert(RHSVecTy)(static_cast<void> (0));
11100 if (IsCompAssign)
11101 return RHSType;
11102 if (LHSEleType != RHSEleType) {
11103 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11104 LHSEleType = RHSEleType;
11105 }
11106 QualType VecTy =
11107 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11108 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11109 LHSType = VecTy;
11110 } else if (RHSVecTy) {
11111 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11112 // are applied component-wise. So if RHS is a vector, then ensure
11113 // that the number of elements is the same as LHS...
11114 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11115 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11116 << LHS.get()->getType() << RHS.get()->getType()
11117 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11118 return QualType();
11119 }
11120 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11121 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11122 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11123 if (LHSBT != RHSBT &&
11124 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11125 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11126 << LHS.get()->getType() << RHS.get()->getType()
11127 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11128 }
11129 }
11130 } else {
11131 // ...else expand RHS to match the number of elements in LHS.
11132 QualType VecTy =
11133 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11134 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11135 }
11136
11137 return LHSType;
11138}
11139
11140// C99 6.5.7
11141QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11142 SourceLocation Loc, BinaryOperatorKind Opc,
11143 bool IsCompAssign) {
11144 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11145
11146 // Vector shifts promote their scalar inputs to vector type.
11147 if (LHS.get()->getType()->isVectorType() ||
11148 RHS.get()->getType()->isVectorType()) {
11149 if (LangOpts.ZVector) {
11150 // The shift operators for the z vector extensions work basically
11151 // like general shifts, except that neither the LHS nor the RHS is
11152 // allowed to be a "vector bool".
11153 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11154 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11155 return InvalidOperands(Loc, LHS, RHS);
11156 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11157 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11158 return InvalidOperands(Loc, LHS, RHS);
11159 }
11160 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11161 }
11162
11163 // Shifts don't perform usual arithmetic conversions, they just do integer
11164 // promotions on each operand. C99 6.5.7p3
11165
11166 // For the LHS, do usual unary conversions, but then reset them away
11167 // if this is a compound assignment.
11168 ExprResult OldLHS = LHS;
11169 LHS = UsualUnaryConversions(LHS.get());
11170 if (LHS.isInvalid())
11171 return QualType();
11172 QualType LHSType = LHS.get()->getType();
11173 if (IsCompAssign) LHS = OldLHS;
11174
11175 // The RHS is simpler.
11176 RHS = UsualUnaryConversions(RHS.get());
11177 if (RHS.isInvalid())
11178 return QualType();
11179 QualType RHSType = RHS.get()->getType();
11180
11181 // C99 6.5.7p2: Each of the operands shall have integer type.
11182 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11183 if ((!LHSType->isFixedPointOrIntegerType() &&
11184 !LHSType->hasIntegerRepresentation()) ||
11185 !RHSType->hasIntegerRepresentation())
11186 return InvalidOperands(Loc, LHS, RHS);
11187
11188 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11189 // hasIntegerRepresentation() above instead of this.
11190 if (isScopedEnumerationType(LHSType) ||
11191 isScopedEnumerationType(RHSType)) {
11192 return InvalidOperands(Loc, LHS, RHS);
11193 }
11194 // Sanity-check shift operands
11195 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11196
11197 // "The type of the result is that of the promoted left operand."
11198 return LHSType;
11199}
11200
11201/// Diagnose bad pointer comparisons.
11202static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11203 ExprResult &LHS, ExprResult &RHS,
11204 bool IsError) {
11205 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11206 : diag::ext_typecheck_comparison_of_distinct_pointers)
11207 << LHS.get()->getType() << RHS.get()->getType()
11208 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11209}
11210
11211/// Returns false if the pointers are converted to a composite type,
11212/// true otherwise.
11213static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11214 ExprResult &LHS, ExprResult &RHS) {
11215 // C++ [expr.rel]p2:
11216 // [...] Pointer conversions (4.10) and qualification
11217 // conversions (4.4) are performed on pointer operands (or on
11218 // a pointer operand and a null pointer constant) to bring
11219 // them to their composite pointer type. [...]
11220 //
11221 // C++ [expr.eq]p1 uses the same notion for (in)equality
11222 // comparisons of pointers.
11223
11224 QualType LHSType = LHS.get()->getType();
11225 QualType RHSType = RHS.get()->getType();
11226 assert(LHSType->isPointerType() || RHSType->isPointerType() ||(static_cast<void> (0))
11227 LHSType->isMemberPointerType() || RHSType->isMemberPointerType())(static_cast<void> (0));
11228
11229 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11230 if (T.isNull()) {
11231 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11232 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11233 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11234 else
11235 S.InvalidOperands(Loc, LHS, RHS);
11236 return true;
11237 }
11238
11239 return false;
11240}
11241
11242static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11243 ExprResult &LHS,
11244 ExprResult &RHS,
11245 bool IsError) {
11246 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11247 : diag::ext_typecheck_comparison_of_fptr_to_void)
11248 << LHS.get()->getType() << RHS.get()->getType()
11249 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11250}
11251
11252static bool isObjCObjectLiteral(ExprResult &E) {
11253 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11254 case Stmt::ObjCArrayLiteralClass:
11255 case Stmt::ObjCDictionaryLiteralClass:
11256 case Stmt::ObjCStringLiteralClass:
11257 case Stmt::ObjCBoxedExprClass:
11258 return true;
11259 default:
11260 // Note that ObjCBoolLiteral is NOT an object literal!
11261 return false;
11262 }
11263}
11264
11265static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11266 const ObjCObjectPointerType *Type =
11267 LHS->getType()->getAs<ObjCObjectPointerType>();
11268
11269 // If this is not actually an Objective-C object, bail out.
11270 if (!Type)
11271 return false;
11272
11273 // Get the LHS object's interface type.
11274 QualType InterfaceType = Type->getPointeeType();
11275
11276 // If the RHS isn't an Objective-C object, bail out.
11277 if (!RHS->getType()->isObjCObjectPointerType())
11278 return false;
11279
11280 // Try to find the -isEqual: method.
11281 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11282 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11283 InterfaceType,
11284 /*IsInstance=*/true);
11285 if (!Method) {
11286 if (Type->isObjCIdType()) {
11287 // For 'id', just check the global pool.
11288 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11289 /*receiverId=*/true);
11290 } else {
11291 // Check protocols.
11292 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11293 /*IsInstance=*/true);
11294 }
11295 }
11296
11297 if (!Method)
11298 return false;
11299
11300 QualType T = Method->parameters()[0]->getType();
11301 if (!T->isObjCObjectPointerType())
11302 return false;
11303
11304 QualType R = Method->getReturnType();
11305 if (!R->isScalarType())
11306 return false;
11307
11308 return true;
11309}
11310
11311Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11312 FromE = FromE->IgnoreParenImpCasts();
11313 switch (FromE->getStmtClass()) {
11314 default:
11315 break;
11316 case Stmt::ObjCStringLiteralClass:
11317 // "string literal"
11318 return LK_String;
11319 case Stmt::ObjCArrayLiteralClass:
11320 // "array literal"
11321 return LK_Array;
11322 case Stmt::ObjCDictionaryLiteralClass:
11323 // "dictionary literal"
11324 return LK_Dictionary;
11325 case Stmt::BlockExprClass:
11326 return LK_Block;
11327 case Stmt::ObjCBoxedExprClass: {
11328 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11329 switch (Inner->getStmtClass()) {
11330 case Stmt::IntegerLiteralClass:
11331 case Stmt::FloatingLiteralClass:
11332 case Stmt::CharacterLiteralClass:
11333 case Stmt::ObjCBoolLiteralExprClass:
11334 case Stmt::CXXBoolLiteralExprClass:
11335 // "numeric literal"
11336 return LK_Numeric;
11337 case Stmt::ImplicitCastExprClass: {
11338 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11339 // Boolean literals can be represented by implicit casts.
11340 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11341 return LK_Numeric;
11342 break;
11343 }
11344 default:
11345 break;
11346 }
11347 return LK_Boxed;
11348 }
11349 }
11350 return LK_None;
11351}
11352
11353static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11354 ExprResult &LHS, ExprResult &RHS,
11355 BinaryOperator::Opcode Opc){
11356 Expr *Literal;
11357 Expr *Other;
11358 if (isObjCObjectLiteral(LHS)) {
11359 Literal = LHS.get();
11360 Other = RHS.get();
11361 } else {
11362 Literal = RHS.get();
11363 Other = LHS.get();
11364 }
11365
11366 // Don't warn on comparisons against nil.
11367 Other = Other->IgnoreParenCasts();
11368 if (Other->isNullPointerConstant(S.getASTContext(),
11369 Expr::NPC_ValueDependentIsNotNull))
11370 return;
11371
11372 // This should be kept in sync with warn_objc_literal_comparison.
11373 // LK_String should always be after the other literals, since it has its own
11374 // warning flag.
11375 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11376 assert(LiteralKind != Sema::LK_Block)(static_cast<void> (0));
11377 if (LiteralKind == Sema::LK_None) {
11378 llvm_unreachable("Unknown Objective-C object literal kind")__builtin_unreachable();
11379 }
11380
11381 if (LiteralKind == Sema::LK_String)
11382 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11383 << Literal->getSourceRange();
11384 else
11385 S.Diag(Loc, diag::warn_objc_literal_comparison)
11386 << LiteralKind << Literal->getSourceRange();
11387
11388 if (BinaryOperator::isEqualityOp(Opc) &&
11389 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11390 SourceLocation Start = LHS.get()->getBeginLoc();
11391 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11392 CharSourceRange OpRange =
11393 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11394
11395 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11396 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11397 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11398 << FixItHint::CreateInsertion(End, "]");
11399 }
11400}
11401
11402/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11403static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11404 ExprResult &RHS, SourceLocation Loc,
11405 BinaryOperatorKind Opc) {
11406 // Check that left hand side is !something.
11407 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11408 if (!UO || UO->getOpcode() != UO_LNot) return;
11409
11410 // Only check if the right hand side is non-bool arithmetic type.
11411 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11412
11413 // Make sure that the something in !something is not bool.
11414 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11415 if (SubExpr->isKnownToHaveBooleanValue()) return;
11416
11417 // Emit warning.
11418 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11419 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11420 << Loc << IsBitwiseOp;
11421
11422 // First note suggest !(x < y)
11423 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11424 SourceLocation FirstClose = RHS.get()->getEndLoc();
11425 FirstClose = S.getLocForEndOfToken(FirstClose);
11426 if (FirstClose.isInvalid())
11427 FirstOpen = SourceLocation();
11428 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11429 << IsBitwiseOp
11430 << FixItHint::CreateInsertion(FirstOpen, "(")
11431 << FixItHint::CreateInsertion(FirstClose, ")");
11432
11433 // Second note suggests (!x) < y
11434 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11435 SourceLocation SecondClose = LHS.get()->getEndLoc();
11436 SecondClose = S.getLocForEndOfToken(SecondClose);
11437 if (SecondClose.isInvalid())
11438 SecondOpen = SourceLocation();
11439 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11440 << FixItHint::CreateInsertion(SecondOpen, "(")
11441 << FixItHint::CreateInsertion(SecondClose, ")");
11442}
11443
11444// Returns true if E refers to a non-weak array.
11445static bool checkForArray(const Expr *E) {
11446 const ValueDecl *D = nullptr;
11447 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11448 D = DR->getDecl();
11449 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11450 if (Mem->isImplicitAccess())
11451 D = Mem->getMemberDecl();
11452 }
11453 if (!D)
11454 return false;
11455 return D->getType()->isArrayType() && !D->isWeak();
11456}
11457
11458/// Diagnose some forms of syntactically-obvious tautological comparison.
11459static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11460 Expr *LHS, Expr *RHS,
11461 BinaryOperatorKind Opc) {
11462 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11463 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11464
11465 QualType LHSType = LHS->getType();
11466 QualType RHSType = RHS->getType();
11467 if (LHSType->hasFloatingRepresentation() ||
11468 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11469 S.inTemplateInstantiation())
11470 return;
11471
11472 // Comparisons between two array types are ill-formed for operator<=>, so
11473 // we shouldn't emit any additional warnings about it.
11474 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11475 return;
11476
11477 // For non-floating point types, check for self-comparisons of the form
11478 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11479 // often indicate logic errors in the program.
11480 //
11481 // NOTE: Don't warn about comparison expressions resulting from macro
11482 // expansion. Also don't warn about comparisons which are only self
11483 // comparisons within a template instantiation. The warnings should catch
11484 // obvious cases in the definition of the template anyways. The idea is to
11485 // warn when the typed comparison operator will always evaluate to the same
11486 // result.
11487
11488 // Used for indexing into %select in warn_comparison_always
11489 enum {
11490 AlwaysConstant,
11491 AlwaysTrue,
11492 AlwaysFalse,
11493 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11494 };
11495
11496 // C++2a [depr.array.comp]:
11497 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11498 // operands of array type are deprecated.
11499 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11500 RHSStripped->getType()->isArrayType()) {
11501 S.Diag(Loc, diag::warn_depr_array_comparison)
11502 << LHS->getSourceRange() << RHS->getSourceRange()
11503 << LHSStripped->getType() << RHSStripped->getType();
11504 // Carry on to produce the tautological comparison warning, if this
11505 // expression is potentially-evaluated, we can resolve the array to a
11506 // non-weak declaration, and so on.
11507 }
11508
11509 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11510 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11511 unsigned Result;
11512 switch (Opc) {
11513 case BO_EQ:
11514 case BO_LE:
11515 case BO_GE:
11516 Result = AlwaysTrue;
11517 break;
11518 case BO_NE:
11519 case BO_LT:
11520 case BO_GT:
11521 Result = AlwaysFalse;
11522 break;
11523 case BO_Cmp:
11524 Result = AlwaysEqual;
11525 break;
11526 default:
11527 Result = AlwaysConstant;
11528 break;
11529 }
11530 S.DiagRuntimeBehavior(Loc, nullptr,
11531 S.PDiag(diag::warn_comparison_always)
11532 << 0 /*self-comparison*/
11533 << Result);
11534 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11535 // What is it always going to evaluate to?
11536 unsigned Result;
11537 switch (Opc) {
11538 case BO_EQ: // e.g. array1 == array2
11539 Result = AlwaysFalse;
11540 break;
11541 case BO_NE: // e.g. array1 != array2
11542 Result = AlwaysTrue;
11543 break;
11544 default: // e.g. array1 <= array2
11545 // The best we can say is 'a constant'
11546 Result = AlwaysConstant;
11547 break;
11548 }
11549 S.DiagRuntimeBehavior(Loc, nullptr,
11550 S.PDiag(diag::warn_comparison_always)
11551 << 1 /*array comparison*/
11552 << Result);
11553 }
11554 }
11555
11556 if (isa<CastExpr>(LHSStripped))
11557 LHSStripped = LHSStripped->IgnoreParenCasts();
11558 if (isa<CastExpr>(RHSStripped))
11559 RHSStripped = RHSStripped->IgnoreParenCasts();
11560
11561 // Warn about comparisons against a string constant (unless the other
11562 // operand is null); the user probably wants string comparison function.
11563 Expr *LiteralString = nullptr;
11564 Expr *LiteralStringStripped = nullptr;
11565 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11566 !RHSStripped->isNullPointerConstant(S.Context,
11567 Expr::NPC_ValueDependentIsNull)) {
11568 LiteralString = LHS;
11569 LiteralStringStripped = LHSStripped;
11570 } else if ((isa<StringLiteral>(RHSStripped) ||
11571 isa<ObjCEncodeExpr>(RHSStripped)) &&
11572 !LHSStripped->isNullPointerConstant(S.Context,
11573 Expr::NPC_ValueDependentIsNull)) {
11574 LiteralString = RHS;
11575 LiteralStringStripped = RHSStripped;
11576 }
11577
11578 if (LiteralString) {
11579 S.DiagRuntimeBehavior(Loc, nullptr,
11580 S.PDiag(diag::warn_stringcompare)
11581 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11582 << LiteralString->getSourceRange());
11583 }
11584}
11585
11586static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11587 switch (CK) {
11588 default: {
11589#ifndef NDEBUG1
11590 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11591 << "\n";
11592#endif
11593 llvm_unreachable("unhandled cast kind")__builtin_unreachable();
11594 }
11595 case CK_UserDefinedConversion:
11596 return ICK_Identity;
11597 case CK_LValueToRValue:
11598 return ICK_Lvalue_To_Rvalue;
11599 case CK_ArrayToPointerDecay:
11600 return ICK_Array_To_Pointer;
11601 case CK_FunctionToPointerDecay:
11602 return ICK_Function_To_Pointer;
11603 case CK_IntegralCast:
11604 return ICK_Integral_Conversion;
11605 case CK_FloatingCast:
11606 return ICK_Floating_Conversion;
11607 case CK_IntegralToFloating:
11608 case CK_FloatingToIntegral:
11609 return ICK_Floating_Integral;
11610 case CK_IntegralComplexCast:
11611 case CK_FloatingComplexCast:
11612 case CK_FloatingComplexToIntegralComplex:
11613 case CK_IntegralComplexToFloatingComplex:
11614 return ICK_Complex_Conversion;
11615 case CK_FloatingComplexToReal:
11616 case CK_FloatingRealToComplex:
11617 case CK_IntegralComplexToReal:
11618 case CK_IntegralRealToComplex:
11619 return ICK_Complex_Real;
11620 }
11621}
11622
11623static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11624 QualType FromType,
11625 SourceLocation Loc) {
11626 // Check for a narrowing implicit conversion.
11627 StandardConversionSequence SCS;
11628 SCS.setAsIdentityConversion();
11629 SCS.setToType(0, FromType);
11630 SCS.setToType(1, ToType);
11631 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11632 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11633
11634 APValue PreNarrowingValue;
11635 QualType PreNarrowingType;
11636 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11637 PreNarrowingType,
11638 /*IgnoreFloatToIntegralConversion*/ true)) {
11639 case NK_Dependent_Narrowing:
11640 // Implicit conversion to a narrower type, but the expression is
11641 // value-dependent so we can't tell whether it's actually narrowing.
11642 case NK_Not_Narrowing:
11643 return false;
11644
11645 case NK_Constant_Narrowing:
11646 // Implicit conversion to a narrower type, and the value is not a constant
11647 // expression.
11648 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11649 << /*Constant*/ 1
11650 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11651 return true;
11652
11653 case NK_Variable_Narrowing:
11654 // Implicit conversion to a narrower type, and the value is not a constant
11655 // expression.
11656 case NK_Type_Narrowing:
11657 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11658 << /*Constant*/ 0 << FromType << ToType;
11659 // TODO: It's not a constant expression, but what if the user intended it
11660 // to be? Can we produce notes to help them figure out why it isn't?
11661 return true;
11662 }
11663 llvm_unreachable("unhandled case in switch")__builtin_unreachable();
11664}
11665
11666static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11667 ExprResult &LHS,
11668 ExprResult &RHS,
11669 SourceLocation Loc) {
11670 QualType LHSType = LHS.get()->getType();
11671 QualType RHSType = RHS.get()->getType();
11672 // Dig out the original argument type and expression before implicit casts
11673 // were applied. These are the types/expressions we need to check the
11674 // [expr.spaceship] requirements against.
11675 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11676 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11677 QualType LHSStrippedType = LHSStripped.get()->getType();
11678 QualType RHSStrippedType = RHSStripped.get()->getType();
11679
11680 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11681 // other is not, the program is ill-formed.
11682 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
1
Taking false branch
11683 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11684 return QualType();
11685 }
11686
11687 // FIXME: Consider combining this with checkEnumArithmeticConversions.
11688 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11689 RHSStrippedType->isEnumeralType();
11690 if (NumEnumArgs
1.1
'NumEnumArgs' is not equal to 1
== 1) {
2
Taking false branch
11691 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11692 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11693 if (OtherTy->hasFloatingRepresentation()) {
11694 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11695 return QualType();
11696 }
11697 }
11698 if (NumEnumArgs
2.1
'NumEnumArgs' is not equal to 2
== 2) {
3
Taking false branch
11699 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11700 // type E, the operator yields the result of converting the operands
11701 // to the underlying type of E and applying <=> to the converted operands.
11702 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11703 S.InvalidOperands(Loc, LHS, RHS);
11704 return QualType();
11705 }
11706 QualType IntType =
11707 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11708 assert(IntType->isArithmeticType())(static_cast<void> (0));
11709
11710 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11711 // promote the boolean type, and all other promotable integer types, to
11712 // avoid this.
11713 if (IntType->isPromotableIntegerType())
11714 IntType = S.Context.getPromotedIntegerType(IntType);
11715
11716 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11717 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11718 LHSType = RHSType = IntType;
11719 }
11720
11721 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11722 // usual arithmetic conversions are applied to the operands.
11723 QualType Type =
11724 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
4
Calling 'Sema::UsualArithmeticConversions'
11725 if (LHS.isInvalid() || RHS.isInvalid())
11726 return QualType();
11727 if (Type.isNull())
11728 return S.InvalidOperands(Loc, LHS, RHS);
11729
11730 Optional<ComparisonCategoryType> CCT =
11731 getComparisonCategoryForBuiltinCmp(Type);
11732 if (!CCT)
11733 return S.InvalidOperands(Loc, LHS, RHS);
11734
11735 bool HasNarrowing = checkThreeWayNarrowingConversion(
11736 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11737 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11738 RHS.get()->getBeginLoc());
11739 if (HasNarrowing)
11740 return QualType();
11741
11742 assert(!Type.isNull() && "composite type for <=> has not been set")(static_cast<void> (0));
11743
11744 return S.CheckComparisonCategoryType(
11745 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11746}
11747
11748static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11749 ExprResult &RHS,
11750 SourceLocation Loc,
11751 BinaryOperatorKind Opc) {
11752 if (Opc == BO_Cmp)
11753 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11754
11755 // C99 6.5.8p3 / C99 6.5.9p4
11756 QualType Type =
11757 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11758 if (LHS.isInvalid() || RHS.isInvalid())
11759 return QualType();
11760 if (Type.isNull())
11761 return S.InvalidOperands(Loc, LHS, RHS);
11762 assert(Type->isArithmeticType() || Type->isEnumeralType())(static_cast<void> (0));
11763
11764 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11765 return S.InvalidOperands(Loc, LHS, RHS);
11766
11767 // Check for comparisons of floating point operands using != and ==.
11768 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11769 S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11770
11771 // The result of comparisons is 'bool' in C++, 'int' in C.
11772 return S.Context.getLogicalOperationType();
11773}
11774
11775void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11776 if (!NullE.get()->getType()->isAnyPointerType())
11777 return;
11778 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11779 if (!E.get()->getType()->isAnyPointerType() &&
11780 E.get()->isNullPointerConstant(Context,
11781 Expr::NPC_ValueDependentIsNotNull) ==
11782 Expr::NPCK_ZeroExpression) {
11783 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11784 if (CL->getValue() == 0)
11785 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11786 << NullValue
11787 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11788 NullValue ? "NULL" : "(void *)0");
11789 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11790 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11791 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11792 if (T == Context.CharTy)
11793 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11794 << NullValue
11795 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11796 NullValue ? "NULL" : "(void *)0");
11797 }
11798 }
11799}
11800
11801// C99 6.5.8, C++ [expr.rel]
11802QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11803 SourceLocation Loc,
11804 BinaryOperatorKind Opc) {
11805 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11806 bool IsThreeWay = Opc == BO_Cmp;
11807 bool IsOrdered = IsRelational || IsThreeWay;
11808 auto IsAnyPointerType = [](ExprResult E) {
11809 QualType Ty = E.get()->getType();
11810 return Ty->isPointerType() || Ty->isMemberPointerType();
11811 };
11812
11813 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11814 // type, array-to-pointer, ..., conversions are performed on both operands to
11815 // bring them to their composite type.
11816 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11817 // any type-related checks.
11818 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11819 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11820 if (LHS.isInvalid())
11821 return QualType();
11822 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11823 if (RHS.isInvalid())
11824 return QualType();
11825 } else {
11826 LHS = DefaultLvalueConversion(LHS.get());
11827 if (LHS.isInvalid())
11828 return QualType();
11829 RHS = DefaultLvalueConversion(RHS.get());
11830 if (RHS.isInvalid())
11831 return QualType();
11832 }
11833
11834 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11835 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11836 CheckPtrComparisonWithNullChar(LHS, RHS);
11837 CheckPtrComparisonWithNullChar(RHS, LHS);
11838 }
11839
11840 // Handle vector comparisons separately.
11841 if (LHS.get()->getType()->isVectorType() ||
11842 RHS.get()->getType()->isVectorType())
11843 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11844
11845 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11846 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11847
11848 QualType LHSType = LHS.get()->getType();
11849 QualType RHSType = RHS.get()->getType();
11850 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11851 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11852 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11853
11854 const Expr::NullPointerConstantKind LHSNullKind =
11855 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11856 const Expr::NullPointerConstantKind RHSNullKind =
11857 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11858 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11859 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11860
11861 auto computeResultTy = [&]() {
11862 if (Opc != BO_Cmp)
11863 return Context.getLogicalOperationType();
11864 assert(getLangOpts().CPlusPlus)(static_cast<void> (0));
11865 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))(static_cast<void> (0));
11866
11867 QualType CompositeTy = LHS.get()->getType();
11868 assert(!CompositeTy->isReferenceType())(static_cast<void> (0));
11869
11870 Optional<ComparisonCategoryType> CCT =
11871 getComparisonCategoryForBuiltinCmp(CompositeTy);
11872 if (!CCT)
11873 return InvalidOperands(Loc, LHS, RHS);
11874
11875 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11876 // P0946R0: Comparisons between a null pointer constant and an object
11877 // pointer result in std::strong_equality, which is ill-formed under
11878 // P1959R0.
11879 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11880 << (LHSIsNull ? LHS.get()->getSourceRange()
11881 : RHS.get()->getSourceRange());
11882 return QualType();
11883 }
11884
11885 return CheckComparisonCategoryType(
11886 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11887 };
11888
11889 if (!IsOrdered && LHSIsNull != RHSIsNull) {
11890 bool IsEquality = Opc == BO_EQ;
11891 if (RHSIsNull)
11892 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11893 RHS.get()->getSourceRange());
11894 else
11895 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11896 LHS.get()->getSourceRange());
11897 }
11898
11899 if (IsOrdered && LHSType->isFunctionPointerType() &&
11900 RHSType->isFunctionPointerType()) {
11901 // Valid unless a relational comparison of function pointers
11902 bool IsError = Opc == BO_Cmp;
11903 auto DiagID =
11904 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
11905 : getLangOpts().CPlusPlus
11906 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
11907 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
11908 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11909 << RHS.get()->getSourceRange();
11910 if (IsError)
11911 return QualType();
11912 }
11913
11914 if ((LHSType->isIntegerType() && !LHSIsNull) ||
11915 (RHSType->isIntegerType() && !RHSIsNull)) {
11916 // Skip normal pointer conversion checks in this case; we have better
11917 // diagnostics for this below.
11918 } else if (getLangOpts().CPlusPlus) {
11919 // Equality comparison of a function pointer to a void pointer is invalid,
11920 // but we allow it as an extension.
11921 // FIXME: If we really want to allow this, should it be part of composite
11922 // pointer type computation so it works in conditionals too?
11923 if (!IsOrdered &&
11924 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11925 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11926 // This is a gcc extension compatibility comparison.
11927 // In a SFINAE context, we treat this as a hard error to maintain
11928 // conformance with the C++ standard.
11929 diagnoseFunctionPointerToVoidComparison(
11930 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11931
11932 if (isSFINAEContext())
11933 return QualType();
11934
11935 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11936 return computeResultTy();
11937 }
11938
11939 // C++ [expr.eq]p2:
11940 // If at least one operand is a pointer [...] bring them to their
11941 // composite pointer type.
11942 // C++ [expr.spaceship]p6
11943 // If at least one of the operands is of pointer type, [...] bring them
11944 // to their composite pointer type.
11945 // C++ [expr.rel]p2:
11946 // If both operands are pointers, [...] bring them to their composite
11947 // pointer type.
11948 // For <=>, the only valid non-pointer types are arrays and functions, and
11949 // we already decayed those, so this is really the same as the relational
11950 // comparison rule.
11951 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11952 (IsOrdered ? 2 : 1) &&
11953 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11954 RHSType->isObjCObjectPointerType()))) {
11955 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11956 return QualType();
11957 return computeResultTy();
11958 }
11959 } else if (LHSType->isPointerType() &&
11960 RHSType->isPointerType()) { // C99 6.5.8p2
11961 // All of the following pointer-related warnings are GCC extensions, except
11962 // when handling null pointer constants.
11963 QualType LCanPointeeTy =
11964 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11965 QualType RCanPointeeTy =
11966 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11967
11968 // C99 6.5.9p2 and C99 6.5.8p2
11969 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11970 RCanPointeeTy.getUnqualifiedType())) {
11971 if (IsRelational) {
11972 // Pointers both need to point to complete or incomplete types
11973 if ((LCanPointeeTy->isIncompleteType() !=
11974 RCanPointeeTy->isIncompleteType()) &&
11975 !getLangOpts().C11) {
11976 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11977 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11978 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11979 << RCanPointeeTy->isIncompleteType();
11980 }
11981 }
11982 } else if (!IsRelational &&
11983 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11984 // Valid unless comparison between non-null pointer and function pointer
11985 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11986 && !LHSIsNull && !RHSIsNull)
11987 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11988 /*isError*/false);
11989 } else {
11990 // Invalid
11991 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11992 }
11993 if (LCanPointeeTy != RCanPointeeTy) {
11994 // Treat NULL constant as a special case in OpenCL.
11995 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11996 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11997 Diag(Loc,
11998 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11999 << LHSType << RHSType << 0 /* comparison */
12000 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12001 }
12002 }
12003 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12004 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12005 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12006 : CK_BitCast;
12007 if (LHSIsNull && !RHSIsNull)
12008 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12009 else
12010 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12011 }
12012 return computeResultTy();
12013 }
12014
12015 if (getLangOpts().CPlusPlus) {
12016 // C++ [expr.eq]p4:
12017 // Two operands of type std::nullptr_t or one operand of type
12018 // std::nullptr_t and the other a null pointer constant compare equal.
12019 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12020 if (LHSType->isNullPtrType()) {
12021 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12022 return computeResultTy();
12023 }
12024 if (RHSType->isNullPtrType()) {
12025 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12026 return computeResultTy();
12027 }
12028 }
12029
12030 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12031 // These aren't covered by the composite pointer type rules.
12032 if (!IsOrdered && RHSType->isNullPtrType() &&
12033 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12034 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12035 return computeResultTy();
12036 }
12037 if (!IsOrdered && LHSType->isNullPtrType() &&
12038 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12039 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12040 return computeResultTy();
12041 }
12042
12043 if (IsRelational &&
12044 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12045 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12046 // HACK: Relational comparison of nullptr_t against a pointer type is
12047 // invalid per DR583, but we allow it within std::less<> and friends,
12048 // since otherwise common uses of it break.
12049 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12050 // friends to have std::nullptr_t overload candidates.
12051 DeclContext *DC = CurContext;
12052 if (isa<FunctionDecl>(DC))
12053 DC = DC->getParent();
12054 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12055 if (CTSD->isInStdNamespace() &&
12056 llvm::StringSwitch<bool>(CTSD->getName())
12057 .Cases("less", "less_equal", "greater", "greater_equal", true)
12058 .Default(false)) {
12059 if (RHSType->isNullPtrType())
12060 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12061 else
12062 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12063 return computeResultTy();
12064 }
12065 }
12066 }
12067
12068 // C++ [expr.eq]p2:
12069 // If at least one operand is a pointer to member, [...] bring them to
12070 // their composite pointer type.
12071 if (!IsOrdered &&
12072 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12073 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12074 return QualType();
12075 else
12076 return computeResultTy();
12077 }
12078 }
12079
12080 // Handle block pointer types.
12081 if (!IsOrdered && LHSType->isBlockPointerType() &&
12082 RHSType->isBlockPointerType()) {
12083 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12084 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12085
12086 if (!LHSIsNull && !RHSIsNull &&
12087 !Context.typesAreCompatible(lpointee, rpointee)) {
12088 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12089 << LHSType << RHSType << LHS.get()->getSourceRange()
12090 << RHS.get()->getSourceRange();
12091 }
12092 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12093 return computeResultTy();
12094 }
12095
12096 // Allow block pointers to be compared with null pointer constants.
12097 if (!IsOrdered
12098 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12099 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12100 if (!LHSIsNull && !RHSIsNull) {
12101 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12102 ->getPointeeType()->isVoidType())
12103 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12104 ->getPointeeType()->isVoidType())))
12105 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12106 << LHSType << RHSType << LHS.get()->getSourceRange()
12107 << RHS.get()->getSourceRange();
12108 }
12109 if (LHSIsNull && !RHSIsNull)
12110 LHS = ImpCastExprToType(LHS.get(), RHSType,
12111 RHSType->isPointerType() ? CK_BitCast
12112 : CK_AnyPointerToBlockPointerCast);
12113 else
12114 RHS = ImpCastExprToType(RHS.get(), LHSType,
12115 LHSType->isPointerType() ? CK_BitCast
12116 : CK_AnyPointerToBlockPointerCast);
12117 return computeResultTy();
12118 }
12119
12120 if (LHSType->isObjCObjectPointerType() ||
12121 RHSType->isObjCObjectPointerType()) {
12122 const PointerType *LPT = LHSType->getAs<PointerType>();
12123 const PointerType *RPT = RHSType->getAs<PointerType>();
12124 if (LPT || RPT) {
12125 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12126 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12127
12128 if (!LPtrToVoid && !RPtrToVoid &&
12129 !Context.typesAreCompatible(LHSType, RHSType)) {
12130 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12131 /*isError*/false);
12132 }
12133 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12134 // the RHS, but we have test coverage for this behavior.
12135 // FIXME: Consider using convertPointersToCompositeType in C++.
12136 if (LHSIsNull && !RHSIsNull) {
12137 Expr *E = LHS.get();
12138 if (getLangOpts().ObjCAutoRefCount)
12139 CheckObjCConversion(SourceRange(), RHSType, E,
12140 CCK_ImplicitConversion);
12141 LHS = ImpCastExprToType(E, RHSType,
12142 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12143 }
12144 else {
12145 Expr *E = RHS.get();
12146 if (getLangOpts().ObjCAutoRefCount)
12147 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12148 /*Diagnose=*/true,
12149 /*DiagnoseCFAudited=*/false, Opc);
12150 RHS = ImpCastExprToType(E, LHSType,
12151 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12152 }
12153 return computeResultTy();
12154 }
12155 if (LHSType->isObjCObjectPointerType() &&
12156 RHSType->isObjCObjectPointerType()) {
12157 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12158 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12159 /*isError*/false);
12160 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12161 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12162
12163 if (LHSIsNull && !RHSIsNull)
12164 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12165 else
12166 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12167 return computeResultTy();
12168 }
12169
12170 if (!IsOrdered && LHSType->isBlockPointerType() &&
12171 RHSType->isBlockCompatibleObjCPointerType(Context)) {
12172 LHS = ImpCastExprToType(LHS.get(), RHSType,
12173 CK_BlockPointerToObjCPointerCast);
12174 return computeResultTy();
12175 } else if (!IsOrdered &&
12176 LHSType->isBlockCompatibleObjCPointerType(Context) &&
12177 RHSType->isBlockPointerType()) {
12178 RHS = ImpCastExprToType(RHS.get(), LHSType,
12179 CK_BlockPointerToObjCPointerCast);
12180 return computeResultTy();
12181 }
12182 }
12183 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12184 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12185 unsigned DiagID = 0;
12186 bool isError = false;
12187 if (LangOpts.DebuggerSupport) {
12188 // Under a debugger, allow the comparison of pointers to integers,
12189 // since users tend to want to compare addresses.
12190 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12191 (RHSIsNull && RHSType->isIntegerType())) {
12192 if (IsOrdered) {
12193 isError = getLangOpts().CPlusPlus;
12194 DiagID =
12195 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12196 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12197 }
12198 } else if (getLangOpts().CPlusPlus) {
12199 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12200 isError = true;
12201 } else if (IsOrdered)
12202 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12203 else
12204 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12205
12206 if (DiagID) {
12207 Diag(Loc, DiagID)
12208 << LHSType << RHSType << LHS.get()->getSourceRange()
12209 << RHS.get()->getSourceRange();
12210 if (isError)
12211 return QualType();
12212 }
12213
12214 if (LHSType->isIntegerType())
12215 LHS = ImpCastExprToType(LHS.get(), RHSType,
12216 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12217 else
12218 RHS = ImpCastExprToType(RHS.get(), LHSType,
12219 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12220 return computeResultTy();
12221 }
12222
12223 // Handle block pointers.
12224 if (!IsOrdered && RHSIsNull
12225 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12226 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12227 return computeResultTy();
12228 }
12229 if (!IsOrdered && LHSIsNull
12230 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12231 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12232 return computeResultTy();
12233 }
12234
12235 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12236 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12237 return computeResultTy();
12238 }
12239
12240 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12241 return computeResultTy();
12242 }
12243
12244 if (LHSIsNull && RHSType->isQueueT()) {
12245 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12246 return computeResultTy();
12247 }
12248
12249 if (LHSType->isQueueT() && RHSIsNull) {
12250 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12251 return computeResultTy();
12252 }
12253 }
12254
12255 return InvalidOperands(Loc, LHS, RHS);
12256}
12257
12258// Return a signed ext_vector_type that is of identical size and number of
12259// elements. For floating point vectors, return an integer type of identical
12260// size and number of elements. In the non ext_vector_type case, search from
12261// the largest type to the smallest type to avoid cases where long long == long,
12262// where long gets picked over long long.
12263QualType Sema::GetSignedVectorType(QualType V) {
12264 const VectorType *VTy = V->castAs<VectorType>();
12265 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12266
12267 if (isa<ExtVectorType>(VTy)) {
12268 if (TypeSize == Context.getTypeSize(Context.CharTy))
12269 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12270 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12271 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12272 else if (TypeSize == Context.getTypeSize(Context.IntTy))
12273 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12274 else if (TypeSize == Context.getTypeSize(Context.LongTy))
12275 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12276 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&(static_cast<void> (0))
12277 "Unhandled vector element size in vector compare")(static_cast<void> (0));
12278 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12279 }
12280
12281 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12282 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12283 VectorType::GenericVector);
12284 else if (TypeSize == Context.getTypeSize(Context.LongTy))
12285 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12286 VectorType::GenericVector);
12287 else if (TypeSize == Context.getTypeSize(Context.IntTy))
12288 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12289 VectorType::GenericVector);
12290 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12291 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12292 VectorType::GenericVector);
12293 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&(static_cast<void> (0))
12294 "Unhandled vector element size in vector compare")(static_cast<void> (0));
12295 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12296 VectorType::GenericVector);
12297}
12298
12299/// CheckVectorCompareOperands - vector comparisons are a clang extension that
12300/// operates on extended vector types. Instead of producing an IntTy result,
12301/// like a scalar comparison, a vector comparison produces a vector of integer
12302/// types.
12303QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12304 SourceLocation Loc,
12305 BinaryOperatorKind Opc) {
12306 if (Opc == BO_Cmp) {
12307 Diag(Loc, diag::err_three_way_vector_comparison);
12308 return QualType();
12309 }
12310
12311 // Check to make sure we're operating on vectors of the same type and width,
12312 // Allowing one side to be a scalar of element type.
12313 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12314 /*AllowBothBool*/true,
12315 /*AllowBoolConversions*/getLangOpts().ZVector);
12316 if (vType.isNull())
12317 return vType;
12318
12319 QualType LHSType = LHS.get()->getType();
12320
12321 // Determine the return type of a vector compare. By default clang will return
12322 // a scalar for all vector compares except vector bool and vector pixel.
12323 // With the gcc compiler we will always return a vector type and with the xl
12324 // compiler we will always return a scalar type. This switch allows choosing
12325 // which behavior is prefered.
12326 if (getLangOpts().AltiVec) {
12327 switch (getLangOpts().getAltivecSrcCompat()) {
12328 case LangOptions::AltivecSrcCompatKind::Mixed:
12329 // If AltiVec, the comparison results in a numeric type, i.e.
12330 // bool for C++, int for C
12331 if (vType->castAs<VectorType>()->getVectorKind() ==
12332 VectorType::AltiVecVector)
12333 return Context.getLogicalOperationType();
12334 else
12335 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12336 break;
12337 case LangOptions::AltivecSrcCompatKind::GCC:
12338 // For GCC we always return the vector type.
12339 break;
12340 case LangOptions::AltivecSrcCompatKind::XL:
12341 return Context.getLogicalOperationType();
12342 break;
12343 }
12344 }
12345
12346 // For non-floating point types, check for self-comparisons of the form
12347 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12348 // often indicate logic errors in the program.
12349 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12350
12351 // Check for comparisons of floating point operands using != and ==.
12352 if (BinaryOperator::isEqualityOp(Opc) &&
12353 LHSType->hasFloatingRepresentation()) {
12354 assert(RHS.get()->getType()->hasFloatingRepresentation())(static_cast<void> (0));
12355 CheckFloatComparison(Loc, LHS.get(), RHS.get());
12356 }
12357
12358 // Return a signed type for the vector.
12359 return GetSignedVectorType(vType);
12360}
12361
12362static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12363 const ExprResult &XorRHS,
12364 const SourceLocation Loc) {
12365 // Do not diagnose macros.
12366 if (Loc.isMacroID())
12367 return;
12368
12369 // Do not diagnose if both LHS and RHS are macros.
12370 if (XorLHS.get()->getExprLoc().isMacroID() &&
12371 XorRHS.get()->getExprLoc().isMacroID())
12372 return;
12373
12374 bool Negative = false;
12375 bool ExplicitPlus = false;
12376 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12377 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12378
12379 if (!LHSInt)
12380 return;
12381 if (!RHSInt) {
12382 // Check negative literals.
12383 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12384 UnaryOperatorKind Opc = UO->getOpcode();
12385 if (Opc != UO_Minus && Opc != UO_Plus)
12386 return;
12387 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12388 if (!RHSInt)
12389 return;
12390 Negative = (Opc == UO_Minus);
12391 ExplicitPlus = !Negative;
12392 } else {
12393 return;
12394 }
12395 }
12396
12397 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12398 llvm::APInt RightSideValue = RHSInt->getValue();
12399 if (LeftSideValue != 2 && LeftSideValue != 10)
12400 return;
12401
12402 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12403 return;
12404
12405 CharSourceRange ExprRange = CharSourceRange::getCharRange(
12406 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12407 llvm::StringRef ExprStr =
12408 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12409
12410 CharSourceRange XorRange =
12411 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12412 llvm::StringRef XorStr =
12413 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12414 // Do not diagnose if xor keyword/macro is used.
12415 if (XorStr == "xor")
12416 return;
12417
12418 std::string LHSStr = std::string(Lexer::getSourceText(
12419 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12420 S.getSourceManager(), S.getLangOpts()));
12421 std::string RHSStr = std::string(Lexer::getSourceText(
12422 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12423 S.getSourceManager(), S.getLangOpts()));
12424
12425 if (Negative) {
12426 RightSideValue = -RightSideValue;
12427 RHSStr = "-" + RHSStr;
12428 } else if (ExplicitPlus) {
12429 RHSStr = "+" + RHSStr;
12430 }
12431
12432 StringRef LHSStrRef = LHSStr;
12433 StringRef RHSStrRef = RHSStr;
12434 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12435 // literals.
12436 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12437 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12438 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12439 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12440 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12441 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12442 LHSStrRef.find('\'') != StringRef::npos ||
12443 RHSStrRef.find('\'') != StringRef::npos)
12444 return;
12445
12446 bool SuggestXor =
12447 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12448 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12449 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12450 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12451 std::string SuggestedExpr = "1 << " + RHSStr;
12452 bool Overflow = false;
12453 llvm::APInt One = (LeftSideValue - 1);
12454 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12455 if (Overflow) {
12456 if (RightSideIntValue < 64)
12457 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12458 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12459 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12460 else if (RightSideIntValue == 64)
12461 S.Diag(Loc, diag::warn_xor_used_as_pow)
12462 << ExprStr << toString(XorValue, 10, true);
12463 else
12464 return;
12465 } else {
12466 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12467 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12468 << toString(PowValue, 10, true)
12469 << FixItHint::CreateReplacement(
12470 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12471 }
12472
12473 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12474 << ("0x2 ^ " + RHSStr) << SuggestXor;
12475 } else if (LeftSideValue == 10) {
12476 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12477 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12478 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12479 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12480 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12481 << ("0xA ^ " + RHSStr) << SuggestXor;
12482 }
12483}
12484
12485QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12486 SourceLocation Loc) {
12487 // Ensure that either both operands are of the same vector type, or
12488 // one operand is of a vector type and the other is of its element type.
12489 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12490 /*AllowBothBool*/true,
12491 /*AllowBoolConversions*/false);
12492 if (vType.isNull())
12493 return InvalidOperands(Loc, LHS, RHS);
12494 if (getLangOpts().OpenCL &&
12495 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12496 vType->hasFloatingRepresentation())
12497 return InvalidOperands(Loc, LHS, RHS);
12498 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12499 // usage of the logical operators && and || with vectors in C. This
12500 // check could be notionally dropped.
12501 if (!getLangOpts().CPlusPlus &&
12502 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12503 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12504
12505 return GetSignedVectorType(LHS.get()->getType());
12506}
12507
12508QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12509 SourceLocation Loc,
12510 bool IsCompAssign) {
12511 if (!IsCompAssign) {
12512 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12513 if (LHS.isInvalid())
12514 return QualType();
12515 }
12516 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12517 if (RHS.isInvalid())
12518 return QualType();
12519
12520 // For conversion purposes, we ignore any qualifiers.
12521 // For example, "const float" and "float" are equivalent.
12522 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12523 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12524
12525 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12526 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12527 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast<void> (0));
12528
12529 if (Context.hasSameType(LHSType, RHSType))
12530 return LHSType;
12531
12532 // Type conversion may change LHS/RHS. Keep copies to the original results, in
12533 // case we have to return InvalidOperands.
12534 ExprResult OriginalLHS = LHS;
12535 ExprResult OriginalRHS = RHS;
12536 if (LHSMatType && !RHSMatType) {
12537 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12538 if (!RHS.isInvalid())
12539 return LHSType;
12540
12541 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12542 }
12543
12544 if (!LHSMatType && RHSMatType) {
12545 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12546 if (!LHS.isInvalid())
12547 return RHSType;
12548 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12549 }
12550
12551 return InvalidOperands(Loc, LHS, RHS);
12552}
12553
12554QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12555 SourceLocation Loc,
12556 bool IsCompAssign) {
12557 if (!IsCompAssign) {
12558 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12559 if (LHS.isInvalid())
12560 return QualType();
12561 }
12562 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12563 if (RHS.isInvalid())
12564 return QualType();
12565
12566 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12567 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12568 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast<void> (0));
12569
12570 if (LHSMatType && RHSMatType) {
12571 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12572 return InvalidOperands(Loc, LHS, RHS);
12573
12574 if (!Context.hasSameType(LHSMatType->getElementType(),
12575 RHSMatType->getElementType()))
12576 return InvalidOperands(Loc, LHS, RHS);
12577
12578 return Context.getConstantMatrixType(LHSMatType->getElementType(),
12579 LHSMatType->getNumRows(),
12580 RHSMatType->getNumColumns());
12581 }
12582 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12583}
12584
12585inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12586 SourceLocation Loc,
12587 BinaryOperatorKind Opc) {
12588 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12589
12590 bool IsCompAssign =
12591 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12592
12593 if (LHS.get()->getType()->isVectorType() ||
12594 RHS.get()->getType()->isVectorType()) {
12595 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12596 RHS.get()->getType()->hasIntegerRepresentation())
12597 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12598 /*AllowBothBool*/true,
12599 /*AllowBoolConversions*/getLangOpts().ZVector);
12600 return InvalidOperands(Loc, LHS, RHS);
12601 }
12602
12603 if (Opc == BO_And)
12604 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12605
12606 if (LHS.get()->getType()->hasFloatingRepresentation() ||
12607 RHS.get()->getType()->hasFloatingRepresentation())
12608 return InvalidOperands(Loc, LHS, RHS);
12609
12610 ExprResult LHSResult = LHS, RHSResult = RHS;
12611 QualType compType = UsualArithmeticConversions(
12612 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12613 if (LHSResult.isInvalid() || RHSResult.isInvalid())
12614 return QualType();
12615 LHS = LHSResult.get();
12616 RHS = RHSResult.get();
12617
12618 if (Opc == BO_Xor)
12619 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12620
12621 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12622 return compType;
12623 return InvalidOperands(Loc, LHS, RHS);
12624}
12625
12626// C99 6.5.[13,14]
12627inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12628 SourceLocation Loc,
12629 BinaryOperatorKind Opc) {
12630 // Check vector operands differently.
12631 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12632 return CheckVectorLogicalOperands(LHS, RHS, Loc);
12633
12634 bool EnumConstantInBoolContext = false;
12635 for (const ExprResult &HS : {LHS, RHS}) {
12636 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12637 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12638 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12639 EnumConstantInBoolContext = true;
12640 }
12641 }
12642
12643 if (EnumConstantInBoolContext)
12644 Diag(Loc, diag::warn_enum_constant_in_bool_context);
12645
12646 // Diagnose cases where the user write a logical and/or but probably meant a
12647 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
12648 // is a constant.
12649 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12650 !LHS.get()->getType()->isBooleanType() &&
12651 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12652 // Don't warn in macros or template instantiations.
12653 !Loc.isMacroID() && !inTemplateInstantiation()) {
12654 // If the RHS can be constant folded, and if it constant folds to something
12655 // that isn't 0 or 1 (which indicate a potential logical operation that
12656 // happened to fold to true/false) then warn.
12657 // Parens on the RHS are ignored.
12658 Expr::EvalResult EVResult;
12659 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12660 llvm::APSInt Result = EVResult.Val.getInt();
12661 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12662 !RHS.get()->getExprLoc().isMacroID()) ||
12663 (Result != 0 && Result != 1)) {
12664 Diag(Loc, diag::warn_logical_instead_of_bitwise)
12665 << RHS.get()->getSourceRange()
12666 << (Opc == BO_LAnd ? "&&" : "||");
12667 // Suggest replacing the logical operator with the bitwise version
12668 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12669 << (Opc == BO_LAnd ? "&" : "|")
12670 << FixItHint::CreateReplacement(SourceRange(
12671 Loc, getLocForEndOfToken(Loc)),
12672 Opc == BO_LAnd ? "&" : "|");
12673 if (Opc == BO_LAnd)
12674 // Suggest replacing "Foo() && kNonZero" with "Foo()"
12675 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12676 << FixItHint::CreateRemoval(
12677 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12678 RHS.get()->getEndLoc()));
12679 }
12680 }
12681 }
12682
12683 if (!Context.getLangOpts().CPlusPlus) {
12684 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12685 // not operate on the built-in scalar and vector float types.
12686 if (Context.getLangOpts().OpenCL &&
12687 Context.getLangOpts().OpenCLVersion < 120) {
12688 if (LHS.get()->getType()->isFloatingType() ||
12689 RHS.get()->getType()->isFloatingType())
12690 return InvalidOperands(Loc, LHS, RHS);
12691 }
12692
12693 LHS = UsualUnaryConversions(LHS.get());
12694 if (LHS.isInvalid())
12695 return QualType();
12696
12697 RHS = UsualUnaryConversions(RHS.get());
12698 if (RHS.isInvalid())
12699 return QualType();
12700
12701 if (!LHS.get()->getType()->isScalarType() ||
12702 !RHS.get()->getType()->isScalarType())
12703 return InvalidOperands(Loc, LHS, RHS);
12704
12705 return Context.IntTy;
12706 }
12707
12708 // The following is safe because we only use this method for
12709 // non-overloadable operands.
12710
12711 // C++ [expr.log.and]p1
12712 // C++ [expr.log.or]p1
12713 // The operands are both contextually converted to type bool.
12714 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12715 if (LHSRes.isInvalid())
12716 return InvalidOperands(Loc, LHS, RHS);
12717 LHS = LHSRes;
12718
12719 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12720 if (RHSRes.isInvalid())
12721 return InvalidOperands(Loc, LHS, RHS);
12722 RHS = RHSRes;
12723
12724 // C++ [expr.log.and]p2
12725 // C++ [expr.log.or]p2
12726 // The result is a bool.
12727 return Context.BoolTy;
12728}
12729
12730static bool IsReadonlyMessage(Expr *E, Sema &S) {
12731 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12732 if (!ME) return false;
12733 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12734 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12735 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12736 if (!Base) return false;
12737 return Base->getMethodDecl() != nullptr;
12738}
12739
12740/// Is the given expression (which must be 'const') a reference to a
12741/// variable which was originally non-const, but which has become
12742/// 'const' due to being captured within a block?
12743enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12744static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12745 assert(E->isLValue() && E->getType().isConstQualified())(static_cast<void> (0));
12746 E = E->IgnoreParens();
12747
12748 // Must be a reference to a declaration from an enclosing scope.
12749 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12750 if (!DRE) return NCCK_None;
12751 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12752
12753 // The declaration must be a variable which is not declared 'const'.
12754 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12755 if (!var) return NCCK_None;
12756 if (var->getType().isConstQualified()) return NCCK_None;
12757 assert(var->hasLocalStorage() && "capture added 'const' to non-local?")(static_cast<void> (0));
12758
12759 // Decide whether the first capture was for a block or a lambda.
12760 DeclContext *DC = S.CurContext, *Prev = nullptr;
12761 // Decide whether the first capture was for a block or a lambda.
12762 while (DC) {
12763 // For init-capture, it is possible that the variable belongs to the
12764 // template pattern of the current context.
12765 if (auto *FD = dyn_cast<FunctionDecl>(DC))
12766 if (var->isInitCapture() &&
12767 FD->getTemplateInstantiationPattern() == var->getDeclContext())
12768 break;
12769 if (DC == var->getDeclContext())
12770 break;
12771 Prev = DC;
12772 DC = DC->getParent();
12773 }
12774 // Unless we have an init-capture, we've gone one step too far.
12775 if (!var->isInitCapture())
12776 DC = Prev;
12777 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12778}
12779
12780static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12781 Ty = Ty.getNonReferenceType();
12782 if (IsDereference && Ty->isPointerType())
12783 Ty = Ty->getPointeeType();
12784 return !Ty.isConstQualified();
12785}
12786
12787// Update err_typecheck_assign_const and note_typecheck_assign_const
12788// when this enum is changed.
12789enum {
12790 ConstFunction,
12791 ConstVariable,
12792 ConstMember,
12793 ConstMethod,
12794 NestedConstMember,
12795 ConstUnknown, // Keep as last element
12796};
12797
12798/// Emit the "read-only variable not assignable" error and print notes to give
12799/// more information about why the variable is not assignable, such as pointing
12800/// to the declaration of a const variable, showing that a method is const, or
12801/// that the function is returning a const reference.
12802static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12803 SourceLocation Loc) {
12804 SourceRange ExprRange = E->getSourceRange();
12805
12806 // Only emit one error on the first const found. All other consts will emit
12807 // a note to the error.
12808 bool DiagnosticEmitted = false;
12809
12810 // Track if the current expression is the result of a dereference, and if the
12811 // next checked expression is the result of a dereference.
12812 bool IsDereference = false;
12813 bool NextIsDereference = false;
12814
12815 // Loop to process MemberExpr chains.
12816 while (true) {
12817 IsDereference = NextIsDereference;
12818
12819 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12820 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12821 NextIsDereference = ME->isArrow();
12822 const ValueDecl *VD = ME->getMemberDecl();
12823 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12824 // Mutable fields can be modified even if the class is const.
12825 if (Field->isMutable()) {
12826 assert(DiagnosticEmitted && "Expected diagnostic not emitted.")(static_cast<void> (0));
12827 break;
12828 }
12829
12830 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12831 if (!DiagnosticEmitted) {
12832 S.Diag(Loc, diag::err_typecheck_assign_const)
12833 << ExprRange << ConstMember << false /*static*/ << Field
12834 << Field->getType();
12835 DiagnosticEmitted = true;
12836 }
12837 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12838 << ConstMember << false /*static*/ << Field << Field->getType()
12839 << Field->getSourceRange();
12840 }
12841 E = ME->getBase();
12842 continue;
12843 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12844 if (VDecl->getType().isConstQualified()) {
12845 if (!DiagnosticEmitted) {
12846 S.Diag(Loc, diag::err_typecheck_assign_const)
12847 << ExprRange << ConstMember << true /*static*/ << VDecl
12848 << VDecl->getType();
12849 DiagnosticEmitted = true;
12850 }
12851 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12852 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12853 << VDecl->getSourceRange();
12854 }
12855 // Static fields do not inherit constness from parents.
12856 break;
12857 }
12858 break; // End MemberExpr
12859 } else if (const ArraySubscriptExpr *ASE =
12860 dyn_cast<ArraySubscriptExpr>(E)) {
12861 E = ASE->getBase()->IgnoreParenImpCasts();
12862 continue;
12863 } else if (const ExtVectorElementExpr *EVE =
12864 dyn_cast<ExtVectorElementExpr>(E)) {
12865 E = EVE->getBase()->IgnoreParenImpCasts();
12866 continue;
12867 }
12868 break;
12869 }
12870
12871 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12872 // Function calls
12873 const FunctionDecl *FD = CE->getDirectCallee();
12874 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12875 if (!DiagnosticEmitted) {
12876 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12877 << ConstFunction << FD;
12878 DiagnosticEmitted = true;
12879 }
12880 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12881 diag::note_typecheck_assign_const)
12882 << ConstFunction << FD << FD->getReturnType()
12883 << FD->getReturnTypeSourceRange();
12884 }
12885 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12886 // Point to variable declaration.
12887 if (const ValueDecl *VD = DRE->getDecl()) {
12888 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12889 if (!DiagnosticEmitted) {
12890 S.Diag(Loc, diag::err_typecheck_assign_const)
12891 << ExprRange << ConstVariable << VD << VD->getType();
12892 DiagnosticEmitted = true;
12893 }
12894 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12895 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12896 }
12897 }
12898 } else if (isa<CXXThisExpr>(E)) {
12899 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12900 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12901 if (MD->isConst()) {
12902 if (!DiagnosticEmitted) {
12903 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12904 << ConstMethod << MD;
12905 DiagnosticEmitted = true;
12906 }
12907 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12908 << ConstMethod << MD << MD->getSourceRange();
12909 }
12910 }
12911 }
12912 }
12913
12914 if (DiagnosticEmitted)
12915 return;
12916
12917 // Can't determine a more specific message, so display the generic error.
12918 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12919}
12920
12921enum OriginalExprKind {
12922 OEK_Variable,
12923 OEK_Member,
12924 OEK_LValue
12925};
12926
12927static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12928 const RecordType *Ty,
12929 SourceLocation Loc, SourceRange Range,
12930 OriginalExprKind OEK,
12931 bool &DiagnosticEmitted) {
12932 std::vector<const RecordType *> RecordTypeList;
12933 RecordTypeList.push_back(Ty);
12934 unsigned NextToCheckIndex = 0;
12935 // We walk the record hierarchy breadth-first to ensure that we print
12936 // diagnostics in field nesting order.
12937 while (RecordTypeList.size() > NextToCheckIndex) {
12938 bool IsNested = NextToCheckIndex > 0;
12939 for (const FieldDecl *Field :
12940 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12941 // First, check every field for constness.
12942 QualType FieldTy = Field->getType();
12943 if (FieldTy.isConstQualified()) {
12944 if (!DiagnosticEmitted) {
12945 S.Diag(Loc, diag::err_typecheck_assign_const)
12946 << Range << NestedConstMember << OEK << VD
12947 << IsNested << Field;
12948 DiagnosticEmitted = true;
12949 }
12950 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12951 << NestedConstMember << IsNested << Field
12952 << FieldTy << Field->getSourceRange();
12953 }
12954
12955 // Then we append it to the list to check next in order.
12956 FieldTy = FieldTy.getCanonicalType();
12957 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12958 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12959 RecordTypeList.push_back(FieldRecTy);
12960 }
12961 }
12962 ++NextToCheckIndex;
12963 }
12964}
12965
12966/// Emit an error for the case where a record we are trying to assign to has a
12967/// const-qualified field somewhere in its hierarchy.
12968static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12969 SourceLocation Loc) {
12970 QualType Ty = E->getType();
12971 assert(Ty->isRecordType() && "lvalue was not record?")(static_cast<void> (0));
12972 SourceRange Range = E->getSourceRange();
12973 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12974 bool DiagEmitted = false;
12975
12976 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12977 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12978 Range, OEK_Member, DiagEmitted);
12979 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12980 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12981 Range, OEK_Variable, DiagEmitted);
12982 else
12983 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12984 Range, OEK_LValue, DiagEmitted);
12985 if (!DiagEmitted)
12986 DiagnoseConstAssignment(S, E, Loc);
12987}
12988
12989/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
12990/// emit an error and return true. If so, return false.
12991static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12992 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast<void> (0));
12993
12994 S.CheckShadowingDeclModification(E, Loc);
12995
12996 SourceLocation OrigLoc = Loc;
12997 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12998 &Loc);
12999 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13000 IsLV = Expr::MLV_InvalidMessageExpression;
13001 if (IsLV == Expr::MLV_Valid)
13002 return false;
13003
13004 unsigned DiagID = 0;
13005 bool NeedType = false;
13006 switch (IsLV) { // C99 6.5.16p2
13007 case Expr::MLV_ConstQualified:
13008 // Use a specialized diagnostic when we're assigning to an object
13009 // from an enclosing function or block.
13010 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13011 if (NCCK == NCCK_Block)
13012 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13013 else
13014 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13015 break;
13016 }
13017
13018 // In ARC, use some specialized diagnostics for occasions where we
13019 // infer 'const'. These are always pseudo-strong variables.
13020 if (S.getLangOpts().ObjCAutoRefCount) {
13021 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13022 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13023 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13024
13025 // Use the normal diagnostic if it's pseudo-__strong but the
13026 // user actually wrote 'const'.
13027 if (var->isARCPseudoStrong() &&
13028 (!var->getTypeSourceInfo() ||
13029 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13030 // There are three pseudo-strong cases:
13031 // - self
13032 ObjCMethodDecl *method = S.getCurMethodDecl();
13033 if (method && var == method->getSelfDecl()) {
13034 DiagID = method->isClassMethod()
13035 ? diag::err_typecheck_arc_assign_self_class_method
13036 : diag::err_typecheck_arc_assign_self;
13037
13038 // - Objective-C externally_retained attribute.
13039 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13040 isa<ParmVarDecl>(var)) {
13041 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13042
13043 // - fast enumeration variables
13044 } else {
13045 DiagID = diag::err_typecheck_arr_assign_enumeration;
13046 }
13047
13048 SourceRange Assign;
13049 if (Loc != OrigLoc)
13050 Assign = SourceRange(OrigLoc, OrigLoc);
13051 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13052 // We need to preserve the AST regardless, so migration tool
13053 // can do its job.
13054 return false;
13055 }
13056 }
13057 }
13058
13059 // If none of the special cases above are triggered, then this is a
13060 // simple const assignment.
13061 if (DiagID == 0) {
13062 DiagnoseConstAssignment(S, E, Loc);
13063 return true;
13064 }
13065
13066 break;
13067 case Expr::MLV_ConstAddrSpace:
13068 DiagnoseConstAssignment(S, E, Loc);
13069 return true;
13070 case Expr::MLV_ConstQualifiedField:
13071 DiagnoseRecursiveConstFields(S, E, Loc);
13072 return true;
13073 case Expr::MLV_ArrayType:
13074 case Expr::MLV_ArrayTemporary:
13075 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13076 NeedType = true;
13077 break;
13078 case Expr::MLV_NotObjectType:
13079 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13080 NeedType = true;
13081 break;
13082 case Expr::MLV_LValueCast:
13083 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13084 break;
13085 case Expr::MLV_Valid:
13086 llvm_unreachable("did not take early return for MLV_Valid")__builtin_unreachable();
13087 case Expr::MLV_InvalidExpression:
13088 case Expr::MLV_MemberFunction:
13089 case Expr::MLV_ClassTemporary:
13090 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13091 break;
13092 case Expr::MLV_IncompleteType:
13093 case Expr::MLV_IncompleteVoidType:
13094 return S.RequireCompleteType(Loc, E->getType(),
13095 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13096 case Expr::MLV_DuplicateVectorComponents:
13097 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13098 break;
13099 case Expr::MLV_NoSetterProperty:
13100 llvm_unreachable("readonly properties should be processed differently")__builtin_unreachable();
13101 case Expr::MLV_InvalidMessageExpression:
13102 DiagID = diag::err_readonly_message_assignment;
13103 break;
13104 case Expr::MLV_SubObjCPropertySetting:
13105 DiagID = diag::err_no_subobject_property_setting;
13106 break;
13107 }
13108
13109 SourceRange Assign;
13110 if (Loc != OrigLoc)
13111 Assign = SourceRange(OrigLoc, OrigLoc);
13112 if (NeedType)
13113 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13114 else
13115 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13116 return true;
13117}
13118
13119static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13120 SourceLocation Loc,
13121 Sema &Sema) {
13122 if (Sema.inTemplateInstantiation())
13123 return;
13124 if (Sema.isUnevaluatedContext())
13125 return;
13126 if (Loc.isInvalid() || Loc.isMacroID())
13127 return;
13128 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13129 return;
13130
13131 // C / C++ fields
13132 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13133 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13134 if (ML && MR) {
13135 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13136 return;
13137 const ValueDecl *LHSDecl =
13138 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13139 const ValueDecl *RHSDecl =
13140 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13141 if (LHSDecl != RHSDecl)
13142 return;
13143 if (LHSDecl->getType().isVolatileQualified())
13144 return;
13145 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13146 if (RefTy->getPointeeType().isVolatileQualified())
13147 return;
13148
13149 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13150 }
13151
13152 // Objective-C instance variables
13153 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13154 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13155 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13156 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13157 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13158 if (RL && RR && RL->getDecl() == RR->getDecl())
13159 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13160 }
13161}
13162
13163// C99 6.5.16.1
13164QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13165 SourceLocation Loc,
13166 QualType CompoundType) {
13167 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast<void> (0));
13168
13169 // Verify that LHS is a modifiable lvalue, and emit error if not.
13170 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13171 return QualType();
13172
13173 QualType LHSType = LHSExpr->getType();
13174 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13175 CompoundType;
13176 // OpenCL v1.2 s6.1.1.1 p2:
13177 // The half data type can only be used to declare a pointer to a buffer that
13178 // contains half values
13179 if (getLangOpts().OpenCL &&
13180 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13181 LHSType->isHalfType()) {
13182 Diag(Loc, diag::err_opencl_half_load_store) << 1
13183 << LHSType.getUnqualifiedType();
13184 return QualType();
13185 }
13186
13187 AssignConvertType ConvTy;
13188 if (CompoundType.isNull()) {
13189 Expr *RHSCheck = RHS.get();
13190
13191 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13192
13193 QualType LHSTy(LHSType);
13194 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13195 if (RHS.isInvalid())
13196 return QualType();
13197 // Special case of NSObject attributes on c-style pointer types.
13198 if (ConvTy == IncompatiblePointer &&
13199 ((Context.isObjCNSObjectType(LHSType) &&
13200 RHSType->isObjCObjectPointerType()) ||
13201 (Context.isObjCNSObjectType(RHSType) &&
13202 LHSType->isObjCObjectPointerType())))
13203 ConvTy = Compatible;
13204
13205 if (ConvTy == Compatible &&
13206 LHSType->isObjCObjectType())
13207 Diag(Loc, diag::err_objc_object_assignment)
13208 << LHSType;
13209
13210 // If the RHS is a unary plus or minus, check to see if they = and + are
13211 // right next to each other. If so, the user may have typo'd "x =+ 4"
13212 // instead of "x += 4".
13213 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13214 RHSCheck = ICE->getSubExpr();
13215 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13216 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13217 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13218 // Only if the two operators are exactly adjacent.
13219 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13220 // And there is a space or other character before the subexpr of the
13221 // unary +/-. We don't want to warn on "x=-1".
13222 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13223 UO->getSubExpr()->getBeginLoc().isFileID()) {
13224 Diag(Loc, diag::warn_not_compound_assign)
13225 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13226 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13227 }
13228 }
13229
13230 if (ConvTy == Compatible) {
13231 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13232 // Warn about retain cycles where a block captures the LHS, but
13233 // not if the LHS is a simple variable into which the block is
13234 // being stored...unless that variable can be captured by reference!
13235 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13236 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13237 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13238 checkRetainCycles(LHSExpr, RHS.get());
13239 }
13240
13241 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13242 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13243 // It is safe to assign a weak reference into a strong variable.
13244 // Although this code can still have problems:
13245 // id x = self.weakProp;
13246 // id y = self.weakProp;
13247 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13248 // paths through the function. This should be revisited if
13249 // -Wrepeated-use-of-weak is made flow-sensitive.
13250 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13251 // variable, which will be valid for the current autorelease scope.
13252 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13253 RHS.get()->getBeginLoc()))
13254 getCurFunction()->markSafeWeakUse(RHS.get());
13255
13256 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13257 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13258 }
13259 }
13260 } else {
13261 // Compound assignment "x += y"
13262 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13263 }
13264
13265 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13266 RHS.get(), AA_Assigning))
13267 return QualType();
13268
13269 CheckForNullPointerDereference(*this, LHSExpr);
13270
13271 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13272 if (CompoundType.isNull()) {
13273 // C++2a [expr.ass]p5:
13274 // A simple-assignment whose left operand is of a volatile-qualified
13275 // type is deprecated unless the assignment is either a discarded-value
13276 // expression or an unevaluated operand
13277 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13278 } else {
13279 // C++2a [expr.ass]p6:
13280 // [Compound-assignment] expressions are deprecated if E1 has
13281 // volatile-qualified type
13282 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13283 }
13284 }
13285
13286 // C99 6.5.16p3: The type of an assignment expression is the type of the
13287 // left operand unless the left operand has qualified type, in which case
13288 // it is the unqualified version of the type of the left operand.
13289 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13290 // is converted to the type of the assignment expression (above).
13291 // C++ 5.17p1: the type of the assignment expression is that of its left
13292 // operand.
13293 return (getLangOpts().CPlusPlus
13294 ? LHSType : LHSType.getUnqualifiedType());
13295}
13296
13297// Only ignore explicit casts to void.
13298static bool IgnoreCommaOperand(const Expr *E) {
13299 E = E->IgnoreParens();
13300
13301 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13302 if (CE->getCastKind() == CK_ToVoid) {
13303 return true;
13304 }
13305
13306 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13307 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13308 CE->getSubExpr()->getType()->isDependentType()) {
13309 return true;
13310 }
13311 }
13312
13313 return false;
13314}
13315
13316// Look for instances where it is likely the comma operator is confused with
13317// another operator. There is an explicit list of acceptable expressions for
13318// the left hand side of the comma operator, otherwise emit a warning.
13319void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13320 // No warnings in macros
13321 if (Loc.isMacroID())
13322 return;
13323
13324 // Don't warn in template instantiations.
13325 if (inTemplateInstantiation())
13326 return;
13327
13328 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13329 // instead, skip more than needed, then call back into here with the
13330 // CommaVisitor in SemaStmt.cpp.
13331 // The listed locations are the initialization and increment portions
13332 // of a for loop. The additional checks are on the condition of
13333 // if statements, do/while loops, and for loops.
13334 // Differences in scope flags for C89 mode requires the extra logic.
13335 const unsigned ForIncrementFlags =
13336 getLangOpts().C99 || getLangOpts().CPlusPlus
13337 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13338 : Scope::ContinueScope | Scope::BreakScope;
13339 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13340 const unsigned ScopeFlags = getCurScope()->getFlags();
13341 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13342 (ScopeFlags & ForInitFlags) == ForInitFlags)
13343 return;
13344
13345 // If there are multiple comma operators used together, get the RHS of the
13346 // of the comma operator as the LHS.
13347 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13348 if (BO->getOpcode() != BO_Comma)
13349 break;
13350 LHS = BO->getRHS();
13351 }
13352
13353 // Only allow some expressions on LHS to not warn.
13354 if (IgnoreCommaOperand(LHS))
13355 return;
13356
13357 Diag(Loc, diag::warn_comma_operator);
13358 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13359 << LHS->getSourceRange()
13360 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13361 LangOpts.CPlusPlus ? "static_cast<void>("
13362 : "(void)(")
13363 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13364 ")");
13365}
13366
13367// C99 6.5.17
13368static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13369 SourceLocation Loc) {
13370 LHS = S.CheckPlaceholderExpr(LHS.get());
13371 RHS = S.CheckPlaceholderExpr(RHS.get());
13372 if (LHS.isInvalid() || RHS.isInvalid())
13373 return QualType();
13374
13375 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13376 // operands, but not unary promotions.
13377 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13378
13379 // So we treat the LHS as a ignored value, and in C++ we allow the
13380 // containing site to determine what should be done with the RHS.
13381 LHS = S.IgnoredValueConversions(LHS.get());
13382 if (LHS.isInvalid())
13383 return QualType();
13384
13385 S.DiagnoseUnusedExprResult(LHS.get());
13386
13387 if (!S.getLangOpts().CPlusPlus) {
13388 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13389 if (RHS.isInvalid())
13390 return QualType();
13391 if (!RHS.get()->getType()->isVoidType())
13392 S.RequireCompleteType(Loc, RHS.get()->getType(),
13393 diag::err_incomplete_type);
13394 }
13395
13396 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13397 S.DiagnoseCommaOperator(LHS.get(), Loc);
13398
13399 return RHS.get()->getType();
13400}
13401
13402/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13403/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13404static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13405 ExprValueKind &VK,
13406 ExprObjectKind &OK,
13407 SourceLocation OpLoc,
13408 bool IsInc, bool IsPrefix) {
13409 if (Op->isTypeDependent())
13410 return S.Context.DependentTy;
13411
13412 QualType ResType = Op->getType();
13413 // Atomic types can be used for increment / decrement where the non-atomic
13414 // versions can, so ignore the _Atomic() specifier for the purpose of
13415 // checking.
13416 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13417 ResType = ResAtomicType->getValueType();
13418
13419 assert(!ResType.isNull() && "no type for increment/decrement expression")(static_cast<void> (0));
13420
13421 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13422 // Decrement of bool is not allowed.
13423 if (!IsInc) {
13424 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13425 return QualType();
13426 }
13427 // Increment of bool sets it to true, but is deprecated.
13428 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13429 : diag::warn_increment_bool)
13430 << Op->getSourceRange();
13431 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13432 // Error on enum increments and decrements in C++ mode
13433 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13434 return QualType();
13435 } else if (ResType->isRealType()) {
13436 // OK!
13437 } else if (ResType->isPointerType()) {
13438 // C99 6.5.2.4p2, 6.5.6p2
13439 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13440 return QualType();
13441 } else if (ResType->isObjCObjectPointerType()) {
13442 // On modern runtimes, ObjC pointer arithmetic is forbidden.
13443 // Otherwise, we just need a complete type.
13444 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13445 checkArithmeticOnObjCPointer(S, OpLoc, Op))
13446 return QualType();
13447 } else if (ResType->isAnyComplexType()) {
13448 // C99 does not support ++/-- on complex types, we allow as an extension.
13449 S.Diag(OpLoc, diag::ext_integer_increment_complex)
13450 << ResType << Op->getSourceRange();
13451 } else if (ResType->isPlaceholderType()) {
13452 ExprResult PR = S.CheckPlaceholderExpr(Op);
13453 if (PR.isInvalid()) return QualType();
13454 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13455 IsInc, IsPrefix);
13456 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13457 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13458 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13459 (ResType->castAs<VectorType>()->getVectorKind() !=
13460 VectorType::AltiVecBool)) {
13461 // The z vector extensions allow ++ and -- for non-bool vectors.
13462 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13463 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13464 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13465 } else {
13466 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13467 << ResType << int(IsInc) << Op->getSourceRange();
13468 return QualType();
13469 }
13470 // At this point, we know we have a real, complex or pointer type.
13471 // Now make sure the operand is a modifiable lvalue.
13472 if (CheckForModifiableLvalue(Op, OpLoc, S))
13473 return QualType();
13474 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13475 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13476 // An operand with volatile-qualified type is deprecated
13477 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13478 << IsInc << ResType;
13479 }
13480 // In C++, a prefix increment is the same type as the operand. Otherwise
13481 // (in C or with postfix), the increment is the unqualified type of the
13482 // operand.
13483 if (IsPrefix && S.getLangOpts().CPlusPlus) {
13484 VK = VK_LValue;
13485 OK = Op->getObjectKind();
13486 return ResType;
13487 } else {
13488 VK = VK_PRValue;
13489 return ResType.getUnqualifiedType();
13490 }
13491}
13492
13493
13494/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13495/// This routine allows us to typecheck complex/recursive expressions
13496/// where the declaration is needed for type checking. We only need to
13497/// handle cases when the expression references a function designator
13498/// or is an lvalue. Here are some examples:
13499/// - &(x) => x
13500/// - &*****f => f for f a function designator.
13501/// - &s.xx => s
13502/// - &s.zz[1].yy -> s, if zz is an array
13503/// - *(x + 1) -> x, if x is an array
13504/// - &"123"[2] -> 0
13505/// - & __real__ x -> x
13506///
13507/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13508/// members.
13509static ValueDecl *getPrimaryDecl(Expr *E) {
13510 switch (E->getStmtClass()) {
13511 case Stmt::DeclRefExprClass:
13512 return cast<DeclRefExpr>(E)->getDecl();
13513 case Stmt::MemberExprClass:
13514 // If this is an arrow operator, the address is an offset from
13515 // the base's value, so the object the base refers to is
13516 // irrelevant.
13517 if (cast<MemberExpr>(E)->isArrow())
13518 return nullptr;
13519 // Otherwise, the expression refers to a part of the base
13520 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13521 case Stmt::ArraySubscriptExprClass: {
13522 // FIXME: This code shouldn't be necessary! We should catch the implicit
13523 // promotion of register arrays earlier.
13524 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13525 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13526 if (ICE->getSubExpr()->getType()->isArrayType())
13527 return getPrimaryDecl(ICE->getSubExpr());
13528 }
13529 return nullptr;
13530 }
13531 case Stmt::UnaryOperatorClass: {
13532 UnaryOperator *UO = cast<UnaryOperator>(E);
13533
13534 switch(UO->getOpcode()) {
13535 case UO_Real:
13536 case UO_Imag:
13537 case UO_Extension:
13538 return getPrimaryDecl(UO->getSubExpr());
13539 default:
13540 return nullptr;
13541 }
13542 }
13543 case Stmt::ParenExprClass:
13544 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13545 case Stmt::ImplicitCastExprClass:
13546 // If the result of an implicit cast is an l-value, we care about
13547 // the sub-expression; otherwise, the result here doesn't matter.
13548 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13549 case Stmt::CXXUuidofExprClass:
13550 return cast<CXXUuidofExpr>(E)->getGuidDecl();
13551 default:
13552 return nullptr;
13553 }
13554}
13555
13556namespace {
13557enum {
13558 AO_Bit_Field = 0,
13559 AO_Vector_Element = 1,
13560 AO_Property_Expansion = 2,
13561 AO_Register_Variable = 3,
13562 AO_Matrix_Element = 4,
13563 AO_No_Error = 5
13564};
13565}
13566/// Diagnose invalid operand for address of operations.
13567///
13568/// \param Type The type of operand which cannot have its address taken.
13569static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13570 Expr *E, unsigned Type) {
13571 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13572}
13573
13574/// CheckAddressOfOperand - The operand of & must be either a function
13575/// designator or an lvalue designating an object. If it is an lvalue, the
13576/// object cannot be declared with storage class register or be a bit field.
13577/// Note: The usual conversions are *not* applied to the operand of the &
13578/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13579/// In C++, the operand might be an overloaded function name, in which case
13580/// we allow the '&' but retain the overloaded-function type.
13581QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13582 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13583 if (PTy->getKind() == BuiltinType::Overload) {
13584 Expr *E = OrigOp.get()->IgnoreParens();
13585 if (!isa<OverloadExpr>(E)) {
13586 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)(static_cast<void> (0));
13587 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13588 << OrigOp.get()->getSourceRange();
13589 return QualType();
13590 }
13591
13592 OverloadExpr *Ovl = cast<OverloadExpr>(E);
13593 if (isa<UnresolvedMemberExpr>(Ovl))
13594 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13595 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13596 << OrigOp.get()->getSourceRange();
13597 return QualType();
13598 }
13599
13600 return Context.OverloadTy;
13601 }
13602
13603 if (PTy->getKind() == BuiltinType::UnknownAny)
13604 return Context.UnknownAnyTy;
13605
13606 if (PTy->getKind() == BuiltinType::BoundMember) {
13607 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13608 << OrigOp.get()->getSourceRange();
13609 return QualType();
13610 }
13611
13612 OrigOp = CheckPlaceholderExpr(OrigOp.get());
13613 if (OrigOp.isInvalid()) return QualType();
13614 }
13615
13616 if (OrigOp.get()->isTypeDependent())
13617 return Context.DependentTy;
13618
13619 assert(!OrigOp.get()->getType()->isPlaceholderType())(static_cast<void> (0));
13620
13621 // Make sure to ignore parentheses in subsequent checks
13622 Expr *op = OrigOp.get()->IgnoreParens();
13623
13624 // In OpenCL captures for blocks called as lambda functions
13625 // are located in the private address space. Blocks used in
13626 // enqueue_kernel can be located in a different address space
13627 // depending on a vendor implementation. Thus preventing
13628 // taking an address of the capture to avoid invalid AS casts.
13629 if (LangOpts.OpenCL) {
13630 auto* VarRef = dyn_cast<DeclRefExpr>(op);
13631 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13632 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13633 return QualType();
13634 }
13635 }
13636
13637 if (getLangOpts().C99) {
13638 // Implement C99-only parts of addressof rules.
13639 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13640 if (uOp->getOpcode() == UO_Deref)
13641 // Per C99 6.5.3.2, the address of a deref always returns a valid result
13642 // (assuming the deref expression is valid).
13643 return uOp->getSubExpr()->getType();
13644 }
13645 // Technically, there should be a check for array subscript
13646 // expressions here, but the result of one is always an lvalue anyway.
13647 }
13648 ValueDecl *dcl = getPrimaryDecl(op);
13649
13650 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13651 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13652 op->getBeginLoc()))
13653 return QualType();
13654
13655 Expr::LValueClassification lval = op->ClassifyLValue(Context);
13656 unsigned AddressOfError = AO_No_Error;
13657
13658 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13659 bool sfinae = (bool)isSFINAEContext();
13660 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13661 : diag::ext_typecheck_addrof_temporary)
13662 << op->getType() << op->getSourceRange();
13663 if (sfinae)
13664 return QualType();
13665 // Materialize the temporary as an lvalue so that we can take its address.
13666 OrigOp = op =
13667 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13668 } else if (isa<ObjCSelectorExpr>(op)) {
13669 return Context.getPointerType(op->getType());
13670 } else if (lval == Expr::LV_MemberFunction) {
13671 // If it's an instance method, make a member pointer.
13672 // The expression must have exactly the form &A::foo.
13673
13674 // If the underlying expression isn't a decl ref, give up.
13675 if (!isa<DeclRefExpr>(op)) {
13676 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13677 << OrigOp.get()->getSourceRange();
13678 return QualType();
13679 }
13680 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13681 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13682
13683 // The id-expression was parenthesized.
13684 if (OrigOp.get() != DRE) {
13685 Diag(OpLoc, diag::err_parens_pointer_member_function)
13686 << OrigOp.get()->getSourceRange();
13687
13688 // The method was named without a qualifier.
13689 } else if (!DRE->getQualifier()) {
13690 if (MD->getParent()->getName().empty())
13691 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13692 << op->getSourceRange();
13693 else {
13694 SmallString<32> Str;
13695 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13696 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13697 << op->getSourceRange()
13698 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13699 }
13700 }
13701
13702 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13703 if (isa<CXXDestructorDecl>(MD))
13704 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13705
13706 QualType MPTy = Context.getMemberPointerType(
13707 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13708 // Under the MS ABI, lock down the inheritance model now.
13709 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13710 (void)isCompleteType(OpLoc, MPTy);
13711 return MPTy;
13712 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13713 // C99 6.5.3.2p1
13714 // The operand must be either an l-value or a function designator
13715 if (!op->getType()->isFunctionType()) {
13716 // Use a special diagnostic for loads from property references.
13717 if (isa<PseudoObjectExpr>(op)) {
13718 AddressOfError = AO_Property_Expansion;
13719 } else {
13720 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13721 << op->getType() << op->getSourceRange();
13722 return QualType();
13723 }
13724 }
13725 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13726 // The operand cannot be a bit-field
13727 AddressOfError = AO_Bit_Field;
13728 } else if (op->getObjectKind() == OK_VectorComponent) {
13729 // The operand cannot be an element of a vector
13730 AddressOfError = AO_Vector_Element;
13731 } else if (op->getObjectKind() == OK_MatrixComponent) {
13732 // The operand cannot be an element of a matrix.
13733 AddressOfError = AO_Matrix_Element;
13734 } else if (dcl) { // C99 6.5.3.2p1
13735 // We have an lvalue with a decl. Make sure the decl is not declared
13736 // with the register storage-class specifier.
13737 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13738 // in C++ it is not error to take address of a register
13739 // variable (c++03 7.1.1P3)
13740 if (vd->getStorageClass() == SC_Register &&
13741 !getLangOpts().CPlusPlus) {
13742 AddressOfError = AO_Register_Variable;
13743 }
13744 } else if (isa<MSPropertyDecl>(dcl)) {
13745 AddressOfError = AO_Property_Expansion;
13746 } else if (isa<FunctionTemplateDecl>(dcl)) {
13747 return Context.OverloadTy;
13748 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13749 // Okay: we can take the address of a field.
13750 // Could be a pointer to member, though, if there is an explicit
13751 // scope qualifier for the class.
13752 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13753 DeclContext *Ctx = dcl->getDeclContext();
13754 if (Ctx && Ctx->isRecord()) {
13755 if (dcl->getType()->isReferenceType()) {
13756 Diag(OpLoc,
13757 diag::err_cannot_form_pointer_to_member_of_reference_type)
13758 << dcl->getDeclName() << dcl->getType();
13759 return QualType();
13760 }
13761
13762 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13763 Ctx = Ctx->getParent();
13764
13765 QualType MPTy = Context.getMemberPointerType(
13766 op->getType(),
13767 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13768 // Under the MS ABI, lock down the inheritance model now.
13769 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13770 (void)isCompleteType(OpLoc, MPTy);
13771 return MPTy;
13772 }
13773 }
13774 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13775 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13776 llvm_unreachable("Unknown/unexpected decl type")__builtin_unreachable();
13777 }
13778
13779 if (AddressOfError != AO_No_Error) {
13780 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13781 return QualType();
13782 }
13783
13784 if (lval == Expr::LV_IncompleteVoidType) {
13785 // Taking the address of a void variable is technically illegal, but we
13786 // allow it in cases which are otherwise valid.
13787 // Example: "extern void x; void* y = &x;".
13788 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13789 }
13790
13791 // If the operand has type "type", the result has type "pointer to type".
13792 if (op->getType()->isObjCObjectType())
13793 return Context.getObjCObjectPointerType(op->getType());
13794
13795 CheckAddressOfPackedMember(op);
13796
13797 return Context.getPointerType(op->getType());
13798}
13799
13800static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13801 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13802 if (!DRE)
13803 return;
13804 const Decl *D = DRE->getDecl();
13805 if (!D)
13806 return;
13807 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13808 if (!Param)
13809 return;
13810 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13811 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13812 return;
13813 if (FunctionScopeInfo *FD = S.getCurFunction())
13814 if (!FD->ModifiedNonNullParams.count(Param))
13815 FD->ModifiedNonNullParams.insert(Param);
13816}
13817
13818/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13819static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13820 SourceLocation OpLoc) {
13821 if (Op->isTypeDependent())
13822 return S.Context.DependentTy;
13823
13824 ExprResult ConvResult = S.UsualUnaryConversions(Op);
13825 if (ConvResult.isInvalid())
13826 return QualType();
13827 Op = ConvResult.get();
13828 QualType OpTy = Op->getType();
13829 QualType Result;
13830
13831 if (isa<CXXReinterpretCastExpr>(Op)) {
13832 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13833 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13834 Op->getSourceRange());
13835 }
13836
13837 if (const PointerType *PT = OpTy->getAs<PointerType>())
13838 {
13839 Result = PT->getPointeeType();
13840 }
13841 else if (const ObjCObjectPointerType *OPT =
13842 OpTy->getAs<ObjCObjectPointerType>())
13843 Result = OPT->getPointeeType();
13844 else {
13845 ExprResult PR = S.CheckPlaceholderExpr(Op);
13846 if (PR.isInvalid()) return QualType();
13847 if (PR.get() != Op)
13848 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13849 }
13850
13851 if (Result.isNull()) {
13852 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13853 << OpTy << Op->getSourceRange();
13854 return QualType();
13855 }
13856
13857 // Note that per both C89 and C99, indirection is always legal, even if Result
13858 // is an incomplete type or void. It would be possible to warn about
13859 // dereferencing a void pointer, but it's completely well-defined, and such a
13860 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13861 // for pointers to 'void' but is fine for any other pointer type:
13862 //
13863 // C++ [expr.unary.op]p1:
13864 // [...] the expression to which [the unary * operator] is applied shall
13865 // be a pointer to an object type, or a pointer to a function type
13866 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13867 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13868 << OpTy << Op->getSourceRange();
13869
13870 // Dereferences are usually l-values...
13871 VK = VK_LValue;
13872
13873 // ...except that certain expressions are never l-values in C.
13874 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13875 VK = VK_PRValue;
13876
13877 return Result;
13878}
13879
13880BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13881 BinaryOperatorKind Opc;
13882 switch (Kind) {
13883 default: llvm_unreachable("Unknown binop!")__builtin_unreachable();
13884 case tok::periodstar: Opc = BO_PtrMemD; break;
13885 case tok::arrowstar: Opc = BO_PtrMemI; break;
13886 case tok::star: Opc = BO_Mul; break;
13887 case tok::slash: Opc = BO_Div; break;
13888 case tok::percent: Opc = BO_Rem; break;
13889 case tok::plus: Opc = BO_Add; break;
13890 case tok::minus: Opc = BO_Sub; break;
13891 case tok::lessless: Opc = BO_Shl; break;
13892 case tok::greatergreater: Opc = BO_Shr; break;
13893 case tok::lessequal: Opc = BO_LE; break;
13894 case tok::less: Opc = BO_LT; break;
13895 case tok::greaterequal: Opc = BO_GE; break;
13896 case tok::greater: Opc = BO_GT; break;
13897 case tok::exclaimequal: Opc = BO_NE; break;
13898 case tok::equalequal: Opc = BO_EQ; break;
13899 case tok::spaceship: Opc = BO_Cmp; break;
13900 case tok::amp: Opc = BO_And; break;
13901 case tok::caret: Opc = BO_Xor; break;
13902 case tok::pipe: Opc = BO_Or; break;
13903 case tok::ampamp: Opc = BO_LAnd; break;
13904 case tok::pipepipe: Opc = BO_LOr; break;
13905 case tok::equal: Opc = BO_Assign; break;
13906 case tok::starequal: Opc = BO_MulAssign; break;
13907 case tok::slashequal: Opc = BO_DivAssign; break;
13908 case tok::percentequal: Opc = BO_RemAssign; break;
13909 case tok::plusequal: Opc = BO_AddAssign; break;
13910 case tok::minusequal: Opc = BO_SubAssign; break;
13911 case tok::lesslessequal: Opc = BO_ShlAssign; break;
13912 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
13913 case tok::ampequal: Opc = BO_AndAssign; break;
13914 case tok::caretequal: Opc = BO_XorAssign; break;
13915 case tok::pipeequal: Opc = BO_OrAssign; break;
13916 case tok::comma: Opc = BO_Comma; break;
13917 }
13918 return Opc;
13919}
13920
13921static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13922 tok::TokenKind Kind) {
13923 UnaryOperatorKind Opc;
13924 switch (Kind) {
13925 default: llvm_unreachable("Unknown unary op!")__builtin_unreachable();
13926 case tok::plusplus: Opc = UO_PreInc; break;
13927 case tok::minusminus: Opc = UO_PreDec; break;
13928 case tok::amp: Opc = UO_AddrOf; break;
13929 case tok::star: Opc = UO_Deref; break;
13930 case tok::plus: Opc = UO_Plus; break;
13931 case tok::minus: Opc = UO_Minus; break;
13932 case tok::tilde: Opc = UO_Not; break;
13933 case tok::exclaim: Opc = UO_LNot; break;
13934 case tok::kw___real: Opc = UO_Real; break;
13935 case tok::kw___imag: Opc = UO_Imag; break;
13936 case tok::kw___extension__: Opc = UO_Extension; break;
13937 }
13938 return Opc;
13939}
13940
13941/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13942/// This warning suppressed in the event of macro expansions.
13943static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13944 SourceLocation OpLoc, bool IsBuiltin) {
13945 if (S.inTemplateInstantiation())
13946 return;
13947 if (S.isUnevaluatedContext())
13948 return;
13949 if (OpLoc.isInvalid() || OpLoc.isMacroID())
13950 return;
13951 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13952 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13953 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13954 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13955 if (!LHSDeclRef || !RHSDeclRef ||
13956 LHSDeclRef->getLocation().isMacroID() ||
13957 RHSDeclRef->getLocation().isMacroID())
13958 return;
13959 const ValueDecl *LHSDecl =
13960 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13961 const ValueDecl *RHSDecl =
13962 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13963 if (LHSDecl != RHSDecl)
13964 return;
13965 if (LHSDecl->getType().isVolatileQualified())
13966 return;
13967 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13968 if (RefTy->getPointeeType().isVolatileQualified())
13969 return;
13970
13971 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13972 : diag::warn_self_assignment_overloaded)
13973 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13974 << RHSExpr->getSourceRange();
13975}
13976
13977/// Check if a bitwise-& is performed on an Objective-C pointer. This
13978/// is usually indicative of introspection within the Objective-C pointer.
13979static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13980 SourceLocation OpLoc) {
13981 if (!S.getLangOpts().ObjC)
13982 return;
13983
13984 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13985 const Expr *LHS = L.get();
13986 const Expr *RHS = R.get();
13987
13988 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13989 ObjCPointerExpr = LHS;
13990 OtherExpr = RHS;
13991 }
13992 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13993 ObjCPointerExpr = RHS;
13994 OtherExpr = LHS;
13995 }
13996
13997 // This warning is deliberately made very specific to reduce false
13998 // positives with logic that uses '&' for hashing. This logic mainly
13999 // looks for code trying to introspect into tagged pointers, which
14000 // code should generally never do.
14001 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14002 unsigned Diag = diag::warn_objc_pointer_masking;
14003 // Determine if we are introspecting the result of performSelectorXXX.
14004 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14005 // Special case messages to -performSelector and friends, which
14006 // can return non-pointer values boxed in a pointer value.
14007 // Some clients may wish to silence warnings in this subcase.
14008 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14009 Selector S = ME->getSelector();
14010 StringRef SelArg0 = S.getNameForSlot(0);
14011 if (SelArg0.startswith("performSelector"))
14012 Diag = diag::warn_objc_pointer_masking_performSelector;
14013 }
14014
14015 S.Diag(OpLoc, Diag)
14016 << ObjCPointerExpr->getSourceRange();
14017 }
14018}
14019
14020static NamedDecl *getDeclFromExpr(Expr *E) {
14021 if (!E)
14022 return nullptr;
14023 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14024 return DRE->getDecl();
14025 if (auto *ME = dyn_cast<MemberExpr>(E))
14026 return ME->getMemberDecl();
14027 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14028 return IRE->getDecl();
14029 return nullptr;
14030}
14031
14032// This helper function promotes a binary operator's operands (which are of a
14033// half vector type) to a vector of floats and then truncates the result to
14034// a vector of either half or short.
14035static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14036 BinaryOperatorKind Opc, QualType ResultTy,
14037 ExprValueKind VK, ExprObjectKind OK,
14038 bool IsCompAssign, SourceLocation OpLoc,
14039 FPOptionsOverride FPFeatures) {
14040 auto &Context = S.getASTContext();
14041 assert((isVector(ResultTy, Context.HalfTy) ||(static_cast<void> (0))
14042 isVector(ResultTy, Context.ShortTy)) &&(static_cast<void> (0))
14043 "Result must be a vector of half or short")(static_cast<void> (0));
14044 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&(static_cast<void> (0))
14045 isVector(RHS.get()->getType(), Context.HalfTy) &&(static_cast<void> (0))
14046 "both operands expected to be a half vector")(static_cast<void> (0));
14047
14048 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14049 QualType BinOpResTy = RHS.get()->getType();
14050
14051 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14052 // change BinOpResTy to a vector of ints.
14053 if (isVector(ResultTy, Context.ShortTy))
14054 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14055
14056 if (IsCompAssign)
14057 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14058 ResultTy, VK, OK, OpLoc, FPFeatures,
14059 BinOpResTy, BinOpResTy);
14060
14061 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14062 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14063 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14064 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14065}
14066
14067static std::pair<ExprResult, ExprResult>
14068CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14069 Expr *RHSExpr) {
14070 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14071 if (!S.Context.isDependenceAllowed()) {
14072 // C cannot handle TypoExpr nodes on either side of a binop because it
14073 // doesn't handle dependent types properly, so make sure any TypoExprs have
14074 // been dealt with before checking the operands.
14075 LHS = S.CorrectDelayedTyposInExpr(LHS);
14076 RHS = S.CorrectDelayedTyposInExpr(
14077 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14078 [Opc, LHS](Expr *E) {
14079 if (Opc != BO_Assign)
14080 return ExprResult(E);
14081 // Avoid correcting the RHS to the same Expr as the LHS.
14082 Decl *D = getDeclFromExpr(E);
14083 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14084 });
14085 }
14086 return std::make_pair(LHS, RHS);
14087}
14088
14089/// Returns true if conversion between vectors of halfs and vectors of floats
14090/// is needed.
14091static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14092 Expr *E0, Expr *E1 = nullptr) {
14093 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14094 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14095 return false;
14096
14097 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14098 QualType Ty = E->IgnoreImplicit()->getType();
14099
14100 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14101 // to vectors of floats. Although the element type of the vectors is __fp16,
14102 // the vectors shouldn't be treated as storage-only types. See the
14103 // discussion here: https://reviews.llvm.org/rG825235c140e7
14104 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14105 if (VT->getVectorKind() == VectorType::NeonVector)
14106 return false;
14107 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14108 }
14109 return false;
14110 };
14111
14112 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14113}
14114
14115/// CreateBuiltinBinOp - Creates a new built-in binary operation with
14116/// operator @p Opc at location @c TokLoc. This routine only supports
14117/// built-in operations; ActOnBinOp handles overloaded operators.
14118ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14119 BinaryOperatorKind Opc,
14120 Expr *LHSExpr, Expr *RHSExpr) {
14121 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14122 // The syntax only allows initializer lists on the RHS of assignment,
14123 // so we don't need to worry about accepting invalid code for
14124 // non-assignment operators.
14125 // C++11 5.17p9:
14126 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14127 // of x = {} is x = T().
14128 InitializationKind Kind = InitializationKind::CreateDirectList(
14129 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14130 InitializedEntity Entity =
14131 InitializedEntity::InitializeTemporary(LHSExpr->getType());
14132 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14133 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14134 if (Init.isInvalid())
14135 return Init;
14136 RHSExpr = Init.get();
14137 }
14138
14139 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14140 QualType ResultTy; // Result type of the binary operator.
14141 // The following two variables are used for compound assignment operators
14142 QualType CompLHSTy; // Type of LHS after promotions for computation
14143 QualType CompResultTy; // Type of computation result
14144 ExprValueKind VK = VK_PRValue;
14145 ExprObjectKind OK = OK_Ordinary;
14146 bool ConvertHalfVec = false;
14147
14148 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14149 if (!LHS.isUsable() || !RHS.isUsable())
14150 return ExprError();
14151
14152 if (getLangOpts().OpenCL) {
14153 QualType LHSTy = LHSExpr->getType();
14154 QualType RHSTy = RHSExpr->getType();
14155 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14156 // the ATOMIC_VAR_INIT macro.
14157 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14158 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14159 if (BO_Assign == Opc)
14160 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14161 else
14162 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14163 return ExprError();
14164 }
14165
14166 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14167 // only with a builtin functions and therefore should be disallowed here.
14168 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14169 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14170 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14171 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14172 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14173 return ExprError();
14174 }
14175 }
14176
14177 switch (Opc) {
14178 case BO_Assign:
14179 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14180 if (getLangOpts().CPlusPlus &&
14181 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14182 VK = LHS.get()->getValueKind();
14183 OK = LHS.get()->getObjectKind();
14184 }
14185 if (!ResultTy.isNull()) {
14186 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14187 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14188
14189 // Avoid copying a block to the heap if the block is assigned to a local
14190 // auto variable that is declared in the same scope as the block. This
14191 // optimization is unsafe if the local variable is declared in an outer
14192 // scope. For example:
14193 //
14194 // BlockTy b;
14195 // {
14196 // b = ^{...};
14197 // }
14198 // // It is unsafe to invoke the block here if it wasn't copied to the
14199 // // heap.
14200 // b();
14201
14202 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14203 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14204 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14205 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14206 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14207
14208 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14209 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14210 NTCUC_Assignment, NTCUK_Copy);
14211 }
14212 RecordModifiableNonNullParam(*this, LHS.get());
14213 break;
14214 case BO_PtrMemD:
14215 case BO_PtrMemI:
14216 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14217 Opc == BO_PtrMemI);
14218 break;
14219 case BO_Mul:
14220 case BO_Div:
14221 ConvertHalfVec = true;
14222 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14223 Opc == BO_Div);
14224 break;
14225 case BO_Rem:
14226 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14227 break;
14228 case BO_Add:
14229 ConvertHalfVec = true;
14230 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14231 break;
14232 case BO_Sub:
14233 ConvertHalfVec = true;
14234 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14235 break;
14236 case BO_Shl:
14237 case BO_Shr:
14238 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14239 break;
14240 case BO_LE:
14241 case BO_LT:
14242 case BO_GE:
14243 case BO_GT:
14244 ConvertHalfVec = true;
14245 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14246 break;
14247 case BO_EQ:
14248 case BO_NE:
14249 ConvertHalfVec = true;
14250 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14251 break;
14252 case BO_Cmp:
14253 ConvertHalfVec = true;
14254 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14255 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())(static_cast<void> (0));
14256 break;
14257 case BO_And:
14258 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14259 LLVM_FALLTHROUGH[[gnu::fallthrough]];
14260 case BO_Xor:
14261 case BO_Or:
14262 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14263 break;
14264 case BO_LAnd:
14265 case BO_LOr:
14266 ConvertHalfVec = true;
14267 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14268 break;
14269 case BO_MulAssign:
14270 case BO_DivAssign:
14271 ConvertHalfVec = true;
14272 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14273 Opc == BO_DivAssign);
14274 CompLHSTy = CompResultTy;
14275 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14276 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14277 break;
14278 case BO_RemAssign:
14279 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14280 CompLHSTy = CompResultTy;
14281 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14282 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14283 break;
14284 case BO_AddAssign:
14285 ConvertHalfVec = true;
14286 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14287 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14288 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14289 break;
14290 case BO_SubAssign:
14291 ConvertHalfVec = true;
14292 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14293 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14294 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14295 break;
14296 case BO_ShlAssign:
14297 case BO_ShrAssign:
14298 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14299 CompLHSTy = CompResultTy;
14300 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14301 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14302 break;
14303 case BO_AndAssign:
14304 case BO_OrAssign: // fallthrough
14305 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14306 LLVM_FALLTHROUGH[[gnu::fallthrough]];
14307 case BO_XorAssign:
14308 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14309 CompLHSTy = CompResultTy;
14310 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14311 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14312 break;
14313 case BO_Comma:
14314 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14315 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14316 VK = RHS.get()->getValueKind();
14317 OK = RHS.get()->getObjectKind();
14318 }
14319 break;
14320 }
14321 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14322 return ExprError();
14323
14324 // Some of the binary operations require promoting operands of half vector to
14325 // float vectors and truncating the result back to half vector. For now, we do
14326 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14327 // arm64).
14328 assert((static_cast<void> (0))
14329 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==(static_cast<void> (0))
14330 isVector(LHS.get()->getType(), Context.HalfTy)) &&(static_cast<void> (0))
14331 "both sides are half vectors or neither sides are")(static_cast<void> (0));
14332 ConvertHalfVec =
14333 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14334
14335 // Check for array bounds violations for both sides of the BinaryOperator
14336 CheckArrayAccess(LHS.get());
14337 CheckArrayAccess(RHS.get());
14338
14339 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14340 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14341 &Context.Idents.get("object_setClass"),
14342 SourceLocation(), LookupOrdinaryName);
14343 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14344 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14345 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14346 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14347 "object_setClass(")
14348 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14349 ",")
14350 << FixItHint::CreateInsertion(RHSLocEnd, ")");
14351 }
14352 else
14353 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14354 }
14355 else if (const ObjCIvarRefExpr *OIRE =
14356 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14357 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14358
14359 // Opc is not a compound assignment if CompResultTy is null.
14360 if (CompResultTy.isNull()) {
14361 if (ConvertHalfVec)
14362 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14363 OpLoc, CurFPFeatureOverrides());
14364 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14365 VK, OK, OpLoc, CurFPFeatureOverrides());
14366 }
14367
14368 // Handle compound assignments.
14369 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14370 OK_ObjCProperty) {
14371 VK = VK_LValue;
14372 OK = LHS.get()->getObjectKind();
14373 }
14374
14375 // The LHS is not converted to the result type for fixed-point compound
14376 // assignment as the common type is computed on demand. Reset the CompLHSTy
14377 // to the LHS type we would have gotten after unary conversions.
14378 if (CompResultTy->isFixedPointType())
14379 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14380
14381 if (ConvertHalfVec)
14382 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14383 OpLoc, CurFPFeatureOverrides());
14384
14385 return CompoundAssignOperator::Create(
14386 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14387 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14388}
14389
14390/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14391/// operators are mixed in a way that suggests that the programmer forgot that
14392/// comparison operators have higher precedence. The most typical example of
14393/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14394static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14395 SourceLocation OpLoc, Expr *LHSExpr,
14396 Expr *RHSExpr) {
14397 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14398 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14399
14400 // Check that one of the sides is a comparison operator and the other isn't.
14401 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14402 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14403 if (isLeftComp == isRightComp)
14404 return;
14405
14406 // Bitwise operations are sometimes used as eager logical ops.
14407 // Don't diagnose this.
14408 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14409 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14410 if (isLeftBitwise || isRightBitwise)
14411 return;
14412
14413 SourceRange DiagRange = isLeftComp
14414 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14415 : SourceRange(OpLoc, RHSExpr->getEndLoc());
14416 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14417 SourceRange ParensRange =
14418 isLeftComp
14419 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14420 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14421
14422 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14423 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14424 SuggestParentheses(Self, OpLoc,
14425 Self.PDiag(diag::note_precedence_silence) << OpStr,
14426 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14427 SuggestParentheses(Self, OpLoc,
14428 Self.PDiag(diag::note_precedence_bitwise_first)
14429 << BinaryOperator::getOpcodeStr(Opc),
14430 ParensRange);
14431}
14432
14433/// It accepts a '&&' expr that is inside a '||' one.
14434/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14435/// in parentheses.
14436static void
14437EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14438 BinaryOperator *Bop) {
14439 assert(Bop->getOpcode() == BO_LAnd)(static_cast<void> (0));
14440 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14441 << Bop->getSourceRange() << OpLoc;
14442 SuggestParentheses(Self, Bop->getOperatorLoc(),
14443 Self.PDiag(diag::note_precedence_silence)
14444 << Bop->getOpcodeStr(),
14445 Bop->getSourceRange());
14446}
14447
14448/// Returns true if the given expression can be evaluated as a constant
14449/// 'true'.
14450static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14451 bool Res;
14452 return !E->isValueDependent() &&
14453 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14454}
14455
14456/// Returns true if the given expression can be evaluated as a constant
14457/// 'false'.
14458static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14459 bool Res;
14460 return !E->isValueDependent() &&
14461 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14462}
14463
14464/// Look for '&&' in the left hand of a '||' expr.
14465static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14466 Expr *LHSExpr, Expr *RHSExpr) {
14467 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14468 if (Bop->getOpcode() == BO_LAnd) {
14469 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14470 if (EvaluatesAsFalse(S, RHSExpr))
14471 return;
14472 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14473 if (!EvaluatesAsTrue(S, Bop->getLHS()))
14474 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14475 } else if (Bop->getOpcode() == BO_LOr) {
14476 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14477 // If it's "a || b && 1 || c" we didn't warn earlier for
14478 // "a || b && 1", but warn now.
14479 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14480 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14481 }
14482 }
14483 }
14484}
14485
14486/// Look for '&&' in the right hand of a '||' expr.
14487static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14488 Expr *LHSExpr, Expr *RHSExpr) {
14489 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14490 if (Bop->getOpcode() == BO_LAnd) {
14491 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14492 if (EvaluatesAsFalse(S, LHSExpr))
14493 return;
14494 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14495 if (!EvaluatesAsTrue(S, Bop->getRHS()))
14496 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14497 }
14498 }
14499}
14500
14501/// Look for bitwise op in the left or right hand of a bitwise op with
14502/// lower precedence and emit a diagnostic together with a fixit hint that wraps
14503/// the '&' expression in parentheses.
14504static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14505 SourceLocation OpLoc, Expr *SubExpr) {
14506 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14507 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14508 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14509 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14510 << Bop->getSourceRange() << OpLoc;
14511 SuggestParentheses(S, Bop->getOperatorLoc(),
14512 S.PDiag(diag::note_precedence_silence)
14513 << Bop->getOpcodeStr(),
14514 Bop->getSourceRange());
14515 }
14516 }
14517}
14518
14519static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14520 Expr *SubExpr, StringRef Shift) {
14521 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14522 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14523 StringRef Op = Bop->getOpcodeStr();
14524 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14525 << Bop->getSourceRange() << OpLoc << Shift << Op;
14526 SuggestParentheses(S, Bop->getOperatorLoc(),
14527 S.PDiag(diag::note_precedence_silence) << Op,
14528 Bop->getSourceRange());
14529 }
14530 }
14531}
14532
14533static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14534 Expr *LHSExpr, Expr *RHSExpr) {
14535 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14536 if (!OCE)
14537 return;
14538
14539 FunctionDecl *FD = OCE->getDirectCallee();
14540 if (!FD || !FD->isOverloadedOperator())
14541 return;
14542
14543 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14544 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14545 return;
14546
14547 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14548 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14549 << (Kind == OO_LessLess);
14550 SuggestParentheses(S, OCE->getOperatorLoc(),
14551 S.PDiag(diag::note_precedence_silence)
14552 << (Kind == OO_LessLess ? "<<" : ">>"),
14553 OCE->getSourceRange());
14554 SuggestParentheses(
14555 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14556 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14557}
14558
14559/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14560/// precedence.
14561static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14562 SourceLocation OpLoc, Expr *LHSExpr,
14563 Expr *RHSExpr){
14564 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14565 if (BinaryOperator::isBitwiseOp(Opc))
14566 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14567
14568 // Diagnose "arg1 & arg2 | arg3"
14569 if ((Opc == BO_Or || Opc == BO_Xor) &&
14570 !OpLoc.isMacroID()/* Don't warn in macros. */) {
14571 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14572 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14573 }
14574
14575 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14576 // We don't warn for 'assert(a || b && "bad")' since this is safe.
14577 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14578 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14579 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14580 }
14581
14582 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14583 || Opc == BO_Shr) {
14584 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14585 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14586 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14587 }
14588
14589 // Warn on overloaded shift operators and comparisons, such as:
14590 // cout << 5 == 4;
14591 if (BinaryOperator::isComparisonOp(Opc))
14592 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14593}
14594
14595// Binary Operators. 'Tok' is the token for the operator.
14596ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14597 tok::TokenKind Kind,
14598 Expr *LHSExpr, Expr *RHSExpr) {
14599 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14600 assert(LHSExpr && "ActOnBinOp(): missing left expression")(static_cast<void> (0));
14601 assert(RHSExpr && "ActOnBinOp(): missing right expression")(static_cast<void> (0));
14602
14603 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14604 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14605
14606 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14607}
14608
14609void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14610 UnresolvedSetImpl &Functions) {
14611 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14612 if (OverOp != OO_None && OverOp != OO_Equal)
14613 LookupOverloadedOperatorName(OverOp, S, Functions);
14614
14615 // In C++20 onwards, we may have a second operator to look up.
14616 if (getLangOpts().CPlusPlus20) {
14617 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14618 LookupOverloadedOperatorName(ExtraOp, S, Functions);
14619 }
14620}
14621
14622/// Build an overloaded binary operator expression in the given scope.
14623static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14624 BinaryOperatorKind Opc,
14625 Expr *LHS, Expr *RHS) {
14626 switch (Opc) {
14627 case BO_Assign:
14628 case BO_DivAssign:
14629 case BO_RemAssign:
14630 case BO_SubAssign:
14631 case BO_AndAssign:
14632 case BO_OrAssign:
14633 case BO_XorAssign:
14634 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14635 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14636 break;
14637 default:
14638 break;
14639 }
14640
14641 // Find all of the overloaded operators visible from this point.
14642 UnresolvedSet<16> Functions;
14643 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14644
14645 // Build the (potentially-overloaded, potentially-dependent)
14646 // binary operation.
14647 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14648}
14649
14650ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14651 BinaryOperatorKind Opc,
14652 Expr *LHSExpr, Expr *RHSExpr) {
14653 ExprResult LHS, RHS;
14654 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14655 if (!LHS.isUsable() || !RHS.isUsable())
14656 return ExprError();
14657 LHSExpr = LHS.get();
14658 RHSExpr = RHS.get();
14659
14660 // We want to end up calling one of checkPseudoObjectAssignment
14661 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14662 // both expressions are overloadable or either is type-dependent),
14663 // or CreateBuiltinBinOp (in any other case). We also want to get
14664 // any placeholder types out of the way.
14665
14666 // Handle pseudo-objects in the LHS.
14667 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14668 // Assignments with a pseudo-object l-value need special analysis.
14669 if (pty->getKind() == BuiltinType::PseudoObject &&
14670 BinaryOperator::isAssignmentOp(Opc))
14671 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14672
14673 // Don't resolve overloads if the other type is overloadable.
14674 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14675 // We can't actually test that if we still have a placeholder,
14676 // though. Fortunately, none of the exceptions we see in that
14677 // code below are valid when the LHS is an overload set. Note
14678 // that an overload set can be dependently-typed, but it never
14679 // instantiates to having an overloadable type.
14680 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14681 if (resolvedRHS.isInvalid()) return ExprError();
14682 RHSExpr = resolvedRHS.get();
14683
14684 if (RHSExpr->isTypeDependent() ||
14685 RHSExpr->getType()->isOverloadableType())
14686 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14687 }
14688
14689 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14690 // template, diagnose the missing 'template' keyword instead of diagnosing
14691 // an invalid use of a bound member function.
14692 //
14693 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14694 // to C++1z [over.over]/1.4, but we already checked for that case above.
14695 if (Opc == BO_LT && inTemplateInstantiation() &&
14696 (pty->getKind() == BuiltinType::BoundMember ||
14697 pty->getKind() == BuiltinType::Overload)) {
14698 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14699 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14700 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14701 return isa<FunctionTemplateDecl>(ND);
14702 })) {
14703 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14704 : OE->getNameLoc(),
14705 diag::err_template_kw_missing)
14706 << OE->getName().getAsString() << "";
14707 return ExprError();
14708 }
14709 }
14710
14711 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14712 if (LHS.isInvalid()) return ExprError();
14713 LHSExpr = LHS.get();
14714 }
14715
14716 // Handle pseudo-objects in the RHS.
14717 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14718 // An overload in the RHS can potentially be resolved by the type
14719 // being assigned to.
14720 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14721 if (getLangOpts().CPlusPlus &&
14722 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14723 LHSExpr->getType()->isOverloadableType()))
14724 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14725
14726 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14727 }
14728
14729 // Don't resolve overloads if the other type is overloadable.
14730 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14731 LHSExpr->getType()->isOverloadableType())
14732 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14733
14734 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14735 if (!resolvedRHS.isUsable()) return ExprError();
14736 RHSExpr = resolvedRHS.get();
14737 }
14738
14739 if (getLangOpts().CPlusPlus) {
14740 // If either expression is type-dependent, always build an
14741 // overloaded op.
14742 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14743 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14744
14745 // Otherwise, build an overloaded op if either expression has an
14746 // overloadable type.
14747 if (LHSExpr->getType()->isOverloadableType() ||
14748 RHSExpr->getType()->isOverloadableType())
14749 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14750 }
14751
14752 if (getLangOpts().RecoveryAST &&
14753 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14754 assert(!getLangOpts().CPlusPlus)(static_cast<void> (0));
14755 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&(static_cast<void> (0))
14756 "Should only occur in error-recovery path.")(static_cast<void> (0));
14757 if (BinaryOperator::isCompoundAssignmentOp(Opc))
14758 // C [6.15.16] p3:
14759 // An assignment expression has the value of the left operand after the
14760 // assignment, but is not an lvalue.
14761 return CompoundAssignOperator::Create(
14762 Context, LHSExpr, RHSExpr, Opc,
14763 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
14764 OpLoc, CurFPFeatureOverrides());
14765 QualType ResultType;
14766 switch (Opc) {
14767 case BO_Assign:
14768 ResultType = LHSExpr->getType().getUnqualifiedType();
14769 break;
14770 case BO_LT:
14771 case BO_GT:
14772 case BO_LE:
14773 case BO_GE:
14774 case BO_EQ:
14775 case BO_NE:
14776 case BO_LAnd:
14777 case BO_LOr:
14778 // These operators have a fixed result type regardless of operands.
14779 ResultType = Context.IntTy;
14780 break;
14781 case BO_Comma:
14782 ResultType = RHSExpr->getType();
14783 break;
14784 default:
14785 ResultType = Context.DependentTy;
14786 break;
14787 }
14788 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14789 VK_PRValue, OK_Ordinary, OpLoc,
14790 CurFPFeatureOverrides());
14791 }
14792
14793 // Build a built-in binary operation.
14794 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14795}
14796
14797static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14798 if (T.isNull() || T->isDependentType())
14799 return false;
14800
14801 if (!T->isPromotableIntegerType())
14802 return true;
14803
14804 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14805}
14806
14807ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14808 UnaryOperatorKind Opc,
14809 Expr *InputExpr) {
14810 ExprResult Input = InputExpr;
14811 ExprValueKind VK = VK_PRValue;
14812 ExprObjectKind OK = OK_Ordinary;
14813 QualType resultType;
14814 bool CanOverflow = false;
14815
14816 bool ConvertHalfVec = false;
14817 if (getLangOpts().OpenCL) {
14818 QualType Ty = InputExpr->getType();
14819 // The only legal unary operation for atomics is '&'.
14820 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14821 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14822 // only with a builtin functions and therefore should be disallowed here.
14823 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14824 || Ty->isBlockPointerType())) {
14825 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14826 << InputExpr->getType()
14827 << Input.get()->getSourceRange());
14828 }
14829 }
14830
14831 switch (Opc) {
14832 case UO_PreInc:
14833 case UO_PreDec:
14834 case UO_PostInc:
14835 case UO_PostDec:
14836 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14837 OpLoc,
14838 Opc == UO_PreInc ||
14839 Opc == UO_PostInc,
14840 Opc == UO_PreInc ||
14841 Opc == UO_PreDec);
14842 CanOverflow = isOverflowingIntegerType(Context, resultType);
14843 break;
14844 case UO_AddrOf:
14845 resultType = CheckAddressOfOperand(Input, OpLoc);
14846 CheckAddressOfNoDeref(InputExpr);
14847 RecordModifiableNonNullParam(*this, InputExpr);
14848 break;
14849 case UO_Deref: {
14850 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14851 if (Input.isInvalid()) return ExprError();
14852 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14853 break;
14854 }
14855 case UO_Plus:
14856 case UO_Minus:
14857 CanOverflow = Opc == UO_Minus &&
14858 isOverflowingIntegerType(Context, Input.get()->getType());
14859 Input = UsualUnaryConversions(Input.get());
14860 if (Input.isInvalid()) return ExprError();
14861 // Unary plus and minus require promoting an operand of half vector to a
14862 // float vector and truncating the result back to a half vector. For now, we
14863 // do this only when HalfArgsAndReturns is set (that is, when the target is
14864 // arm or arm64).
14865 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14866
14867 // If the operand is a half vector, promote it to a float vector.
14868 if (ConvertHalfVec)
14869 Input = convertVector(Input.get(), Context.FloatTy, *this);
14870 resultType = Input.get()->getType();
14871 if (resultType->isDependentType())
14872 break;
14873 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14874 break;
14875 else if (resultType->isVectorType() &&
14876 // The z vector extensions don't allow + or - with bool vectors.
14877 (!Context.getLangOpts().ZVector ||
14878 resultType->castAs<VectorType>()->getVectorKind() !=
14879 VectorType::AltiVecBool))
14880 break;
14881 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14882 Opc == UO_Plus &&
14883 resultType->isPointerType())
14884 break;
14885
14886 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14887 << resultType << Input.get()->getSourceRange());
14888
14889 case UO_Not: // bitwise complement
14890 Input = UsualUnaryConversions(Input.get());
14891 if (Input.isInvalid())
14892 return ExprError();
14893 resultType = Input.get()->getType();
14894 if (resultType->isDependentType())
14895 break;
14896 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14897 if (resultType->isComplexType() || resultType->isComplexIntegerType())
14898 // C99 does not support '~' for complex conjugation.
14899 Diag(OpLoc, diag::ext_integer_complement_complex)
14900 << resultType << Input.get()->getSourceRange();
14901 else if (resultType->hasIntegerRepresentation())
14902 break;
14903 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14904 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14905 // on vector float types.
14906 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14907 if (!T->isIntegerType())
14908 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14909 << resultType << Input.get()->getSourceRange());
14910 } else {
14911 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14912 << resultType << Input.get()->getSourceRange());
14913 }
14914 break;
14915
14916 case UO_LNot: // logical negation
14917 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14918 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14919 if (Input.isInvalid()) return ExprError();
14920 resultType = Input.get()->getType();
14921
14922 // Though we still have to promote half FP to float...
14923 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14924 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14925 resultType = Context.FloatTy;
14926 }
14927
14928 if (resultType->isDependentType())
14929 break;
14930 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14931 // C99 6.5.3.3p1: ok, fallthrough;
14932 if (Context.getLangOpts().CPlusPlus) {
14933 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14934 // operand contextually converted to bool.
14935 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14936 ScalarTypeToBooleanCastKind(resultType));
14937 } else if (Context.getLangOpts().OpenCL &&
14938 Context.getLangOpts().OpenCLVersion < 120) {
14939 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14940 // operate on scalar float types.
14941 if (!resultType->isIntegerType() && !resultType->isPointerType())
14942 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14943 << resultType << Input.get()->getSourceRange());
14944 }
14945 } else if (resultType->isExtVectorType()) {
14946 if (Context.getLangOpts().OpenCL &&
14947 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
14948 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14949 // operate on vector float types.
14950 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14951 if (!T->isIntegerType())
14952 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14953 << resultType << Input.get()->getSourceRange());
14954 }
14955 // Vector logical not returns the signed variant of the operand type.
14956 resultType = GetSignedVectorType(resultType);
14957 break;
14958 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14959 const VectorType *VTy = resultType->castAs<VectorType>();
14960 if (VTy->getVectorKind() != VectorType::GenericVector)
14961 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14962 << resultType << Input.get()->getSourceRange());
14963
14964 // Vector logical not returns the signed variant of the operand type.
14965 resultType = GetSignedVectorType(resultType);
14966 break;
14967 } else {
14968 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14969 << resultType << Input.get()->getSourceRange());
14970 }
14971
14972 // LNot always has type int. C99 6.5.3.3p5.
14973 // In C++, it's bool. C++ 5.3.1p8
14974 resultType = Context.getLogicalOperationType();
14975 break;
14976 case UO_Real:
14977 case UO_Imag:
14978 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14979 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14980 // complex l-values to ordinary l-values and all other values to r-values.
14981 if (Input.isInvalid()) return ExprError();
14982 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14983 if (Input.get()->isGLValue() &&
14984 Input.get()->getObjectKind() == OK_Ordinary)
14985 VK = Input.get()->getValueKind();
14986 } else if (!getLangOpts().CPlusPlus) {
14987 // In C, a volatile scalar is read by __imag. In C++, it is not.
14988 Input = DefaultLvalueConversion(Input.get());
14989 }
14990 break;
14991 case UO_Extension:
14992 resultType = Input.get()->getType();
14993 VK = Input.get()->getValueKind();
14994 OK = Input.get()->getObjectKind();
14995 break;
14996 case UO_Coawait:
14997 // It's unnecessary to represent the pass-through operator co_await in the
14998 // AST; just return the input expression instead.
14999 assert(!Input.get()->getType()->isDependentType() &&(static_cast<void> (0))
15000 "the co_await expression must be non-dependant before "(static_cast<void> (0))
15001 "building operator co_await")(static_cast<void> (0));
15002 return Input;
15003 }
15004 if (resultType.isNull() || Input.isInvalid())
15005 return ExprError();
15006
15007 // Check for array bounds violations in the operand of the UnaryOperator,
15008 // except for the '*' and '&' operators that have to be handled specially
15009 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15010 // that are explicitly defined as valid by the standard).
15011 if (Opc != UO_AddrOf && Opc != UO_Deref)
15012 CheckArrayAccess(Input.get());
15013
15014 auto *UO =
15015 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15016 OpLoc, CanOverflow, CurFPFeatureOverrides());
15017
15018 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15019 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15020 !isUnevaluatedContext())
15021 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15022
15023 // Convert the result back to a half vector.
15024 if (ConvertHalfVec)
15025 return convertVector(UO, Context.HalfTy, *this);
15026 return UO;
15027}
15028
15029/// Determine whether the given expression is a qualified member
15030/// access expression, of a form that could be turned into a pointer to member
15031/// with the address-of operator.
15032bool Sema::isQualifiedMemberAccess(Expr *E) {
15033 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15034 if (!DRE->getQualifier())
15035 return false;
15036
15037 ValueDecl *VD = DRE->getDecl();
15038 if (!VD->isCXXClassMember())
15039 return false;
15040
15041 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15042 return true;
15043 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15044 return Method->isInstance();
15045
15046 return false;
15047 }
15048
15049 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15050 if (!ULE->getQualifier())
15051 return false;
15052
15053 for (NamedDecl *D : ULE->decls()) {
15054 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15055 if (Method->isInstance())
15056 return true;
15057 } else {
15058 // Overload set does not contain methods.
15059 break;
15060 }
15061 }
15062
15063 return false;
15064 }
15065
15066 return false;
15067}
15068
15069ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15070 UnaryOperatorKind Opc, Expr *Input) {
15071 // First things first: handle placeholders so that the
15072 // overloaded-operator check considers the right type.
15073 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15074 // Increment and decrement of pseudo-object references.
15075 if (pty->getKind() == BuiltinType::PseudoObject &&
15076 UnaryOperator::isIncrementDecrementOp(Opc))
15077 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15078
15079 // extension is always a builtin operator.
15080 if (Opc == UO_Extension)
15081 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15082
15083 // & gets special logic for several kinds of placeholder.
15084 // The builtin code knows what to do.
15085 if (Opc == UO_AddrOf &&
15086 (pty->getKind() == BuiltinType::Overload ||
15087 pty->getKind() == BuiltinType::UnknownAny ||
15088 pty->getKind() == BuiltinType::BoundMember))
15089 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15090
15091 // Anything else needs to be handled now.
15092 ExprResult Result = CheckPlaceholderExpr(Input);
15093 if (Result.isInvalid()) return ExprError();
15094 Input = Result.get();
15095 }
15096
15097 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15098 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15099 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15100 // Find all of the overloaded operators visible from this point.
15101 UnresolvedSet<16> Functions;
15102 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15103 if (S && OverOp != OO_None)
15104 LookupOverloadedOperatorName(OverOp, S, Functions);
15105
15106 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15107 }
15108
15109 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15110}
15111
15112// Unary Operators. 'Tok' is the token for the operator.
15113ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15114 tok::TokenKind Op, Expr *Input) {
15115 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15116}
15117
15118/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15119ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15120 LabelDecl *TheDecl) {
15121 TheDecl->markUsed(Context);
15122 // Create the AST node. The address of a label always has type 'void*'.
15123 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15124 Context.getPointerType(Context.VoidTy));
15125}
15126
15127void Sema::ActOnStartStmtExpr() {
15128 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15129}
15130
15131void Sema::ActOnStmtExprError() {
15132 // Note that function is also called by TreeTransform when leaving a
15133 // StmtExpr scope without rebuilding anything.
15134
15135 DiscardCleanupsInEvaluationContext();
15136 PopExpressionEvaluationContext();
15137}
15138
15139ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15140 SourceLocation RPLoc) {
15141 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15142}
15143
15144ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15145 SourceLocation RPLoc, unsigned TemplateDepth) {
15146 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")(static_cast<void> (0));
15147 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15148
15149 if (hasAnyUnrecoverableErrorsInThisFunction())
15150 DiscardCleanupsInEvaluationContext();
15151 assert(!Cleanup.exprNeedsCleanups() &&(static_cast<void> (0))
15152 "cleanups within StmtExpr not correctly bound!")(static_cast<void> (0));
15153 PopExpressionEvaluationContext();
15154
15155 // FIXME: there are a variety of strange constraints to enforce here, for
15156 // example, it is not possible to goto into a stmt expression apparently.
15157 // More semantic analysis is needed.
15158
15159 // If there are sub-stmts in the compound stmt, take the type of the last one
15160 // as the type of the stmtexpr.
15161 QualType Ty = Context.VoidTy;
15162 bool StmtExprMayBindToTemp = false;
15163 if (!Compound->body_empty()) {
15164 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15165 if (const auto *LastStmt =
15166 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15167 if (const Expr *Value = LastStmt->getExprStmt()) {
15168 StmtExprMayBindToTemp = true;
15169 Ty = Value->getType();
15170 }
15171 }
15172 }
15173
15174 // FIXME: Check that expression type is complete/non-abstract; statement
15175 // expressions are not lvalues.
15176 Expr *ResStmtExpr =
15177 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15178 if (StmtExprMayBindToTemp)
15179 return MaybeBindToTemporary(ResStmtExpr);
15180 return ResStmtExpr;
15181}
15182
15183ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15184 if (ER.isInvalid())
15185 return ExprError();
15186
15187 // Do function/array conversion on the last expression, but not
15188 // lvalue-to-rvalue. However, initialize an unqualified type.
15189 ER = DefaultFunctionArrayConversion(ER.get());
15190 if (ER.isInvalid())
15191 return ExprError();
15192 Expr *E = ER.get();
15193
15194 if (E->isTypeDependent())
15195 return E;
15196
15197 // In ARC, if the final expression ends in a consume, splice
15198 // the consume out and bind it later. In the alternate case
15199 // (when dealing with a retainable type), the result
15200 // initialization will create a produce. In both cases the
15201 // result will be +1, and we'll need to balance that out with
15202 // a bind.
15203 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15204 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15205 return Cast->getSubExpr();
15206
15207 // FIXME: Provide a better location for the initialization.
15208 return PerformCopyInitialization(
15209 InitializedEntity::InitializeStmtExprResult(
15210 E->getBeginLoc(), E->getType().getUnqualifiedType()),
15211 SourceLocation(), E);
15212}
15213
15214ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15215 TypeSourceInfo *TInfo,
15216 ArrayRef<OffsetOfComponent> Components,
15217 SourceLocation RParenLoc) {
15218 QualType ArgTy = TInfo->getType();
15219 bool Dependent = ArgTy->isDependentType();
15220 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15221
15222 // We must have at least one component that refers to the type, and the first
15223 // one is known to be a field designator. Verify that the ArgTy represents
15224 // a struct/union/class.
15225 if (!Dependent && !ArgTy->isRecordType())
15226 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15227 << ArgTy << TypeRange);
15228
15229 // Type must be complete per C99 7.17p3 because a declaring a variable
15230 // with an incomplete type would be ill-formed.
15231 if (!Dependent
15232 && RequireCompleteType(BuiltinLoc, ArgTy,
15233 diag::err_offsetof_incomplete_type, TypeRange))
15234 return ExprError();
15235
15236 bool DidWarnAboutNonPOD = false;
15237 QualType CurrentType = ArgTy;
15238 SmallVector<OffsetOfNode, 4> Comps;
15239 SmallVector<Expr*, 4> Exprs;
15240 for (const OffsetOfComponent &OC : Components) {
15241 if (OC.isBrackets) {
15242 // Offset of an array sub-field. TODO: Should we allow vector elements?
15243 if (!CurrentType->isDependentType()) {
15244 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15245 if(!AT)
15246 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15247 << CurrentType);
15248 CurrentType = AT->getElementType();
15249 } else
15250 CurrentType = Context.DependentTy;
15251
15252 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15253 if (IdxRval.isInvalid())
15254 return ExprError();
15255 Expr *Idx = IdxRval.get();
15256
15257 // The expression must be an integral expression.
15258 // FIXME: An integral constant expression?
15259 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15260 !Idx->getType()->isIntegerType())
15261 return ExprError(
15262 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15263 << Idx->getSourceRange());
15264
15265 // Record this array index.
15266 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15267 Exprs.push_back(Idx);
15268 continue;
15269 }
15270
15271 // Offset of a field.
15272 if (CurrentType->isDependentType()) {
15273 // We have the offset of a field, but we can't look into the dependent
15274 // type. Just record the identifier of the field.
15275 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15276 CurrentType = Context.DependentTy;
15277 continue;
15278 }
15279
15280 // We need to have a complete type to look into.
15281 if (RequireCompleteType(OC.LocStart, CurrentType,
15282 diag::err_offsetof_incomplete_type))
15283 return ExprError();
15284
15285 // Look for the designated field.
15286 const RecordType *RC = CurrentType->getAs<RecordType>();
15287 if (!RC)
15288 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15289 << CurrentType);
15290 RecordDecl *RD = RC->getDecl();
15291
15292 // C++ [lib.support.types]p5:
15293 // The macro offsetof accepts a restricted set of type arguments in this
15294 // International Standard. type shall be a POD structure or a POD union
15295 // (clause 9).
15296 // C++11 [support.types]p4:
15297 // If type is not a standard-layout class (Clause 9), the results are
15298 // undefined.
15299 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15300 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15301 unsigned DiagID =
15302 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15303 : diag::ext_offsetof_non_pod_type;
15304
15305 if (!IsSafe && !DidWarnAboutNonPOD &&
15306 DiagRuntimeBehavior(BuiltinLoc, nullptr,
15307 PDiag(DiagID)
15308 << SourceRange(Components[0].LocStart, OC.LocEnd)
15309 << CurrentType))
15310 DidWarnAboutNonPOD = true;
15311 }
15312
15313 // Look for the field.
15314 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15315 LookupQualifiedName(R, RD);
15316 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15317 IndirectFieldDecl *IndirectMemberDecl = nullptr;
15318 if (!MemberDecl) {
15319 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15320 MemberDecl = IndirectMemberDecl->getAnonField();
15321 }
15322
15323 if (!MemberDecl)
15324 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15325 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15326 OC.LocEnd));
15327
15328 // C99 7.17p3:
15329 // (If the specified member is a bit-field, the behavior is undefined.)
15330 //
15331 // We diagnose this as an error.
15332 if (MemberDecl->isBitField()) {
15333 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15334 << MemberDecl->getDeclName()
15335 << SourceRange(BuiltinLoc, RParenLoc);
15336 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15337 return ExprError();
15338 }
15339
15340 RecordDecl *Parent = MemberDecl->getParent();
15341 if (IndirectMemberDecl)
15342 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15343
15344 // If the member was found in a base class, introduce OffsetOfNodes for
15345 // the base class indirections.
15346 CXXBasePaths Paths;
15347 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15348 Paths)) {
15349 if (Paths.getDetectedVirtual()) {
15350 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15351 << MemberDecl->getDeclName()
15352 << SourceRange(BuiltinLoc, RParenLoc);
15353 return ExprError();
15354 }
15355
15356 CXXBasePath &Path = Paths.front();
15357 for (const CXXBasePathElement &B : Path)
15358 Comps.push_back(OffsetOfNode(B.Base));
15359 }
15360
15361 if (IndirectMemberDecl) {
15362 for (auto *FI : IndirectMemberDecl->chain()) {
15363 assert(isa<FieldDecl>(FI))(static_cast<void> (0));
15364 Comps.push_back(OffsetOfNode(OC.LocStart,
15365 cast<FieldDecl>(FI), OC.LocEnd));
15366 }
15367 } else
15368 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15369
15370 CurrentType = MemberDecl->getType().getNonReferenceType();
15371 }
15372
15373 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15374 Comps, Exprs, RParenLoc);
15375}
15376
15377ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15378 SourceLocation BuiltinLoc,
15379 SourceLocation TypeLoc,
15380 ParsedType ParsedArgTy,
15381 ArrayRef<OffsetOfComponent> Components,
15382 SourceLocation RParenLoc) {
15383
15384 TypeSourceInfo *ArgTInfo;
15385 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15386 if (ArgTy.isNull())
15387 return ExprError();
15388
15389 if (!ArgTInfo)
15390 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15391
15392 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15393}
15394
15395
15396ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15397 Expr *CondExpr,
15398 Expr *LHSExpr, Expr *RHSExpr,
15399 SourceLocation RPLoc) {
15400 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(static_cast<void> (0));
15401
15402 ExprValueKind VK = VK_PRValue;
15403 ExprObjectKind OK = OK_Ordinary;
15404 QualType resType;
15405 bool CondIsTrue = false;
15406 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15407 resType = Context.DependentTy;
15408 } else {
15409 // The conditional expression is required to be a constant expression.
15410 llvm::APSInt condEval(32);
15411 ExprResult CondICE = VerifyIntegerConstantExpression(
15412 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15413 if (CondICE.isInvalid())
15414 return ExprError();
15415 CondExpr = CondICE.get();
15416 CondIsTrue = condEval.getZExtValue();
15417
15418 // If the condition is > zero, then the AST type is the same as the LHSExpr.
15419 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15420
15421 resType = ActiveExpr->getType();
15422 VK = ActiveExpr->getValueKind();
15423 OK = ActiveExpr->getObjectKind();
15424 }
15425
15426 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15427 resType, VK, OK, RPLoc, CondIsTrue);
15428}
15429
15430//===----------------------------------------------------------------------===//
15431// Clang Extensions.
15432//===----------------------------------------------------------------------===//
15433
15434/// ActOnBlockStart - This callback is invoked when a block literal is started.
15435void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15436 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15437
15438 if (LangOpts.CPlusPlus) {
15439 MangleNumberingContext *MCtx;
15440 Decl *ManglingContextDecl;
15441 std::tie(MCtx, ManglingContextDecl) =
15442 getCurrentMangleNumberContext(Block->getDeclContext());
15443 if (MCtx) {
15444 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15445 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15446 }
15447 }
15448
15449 PushBlockScope(CurScope, Block);
15450 CurContext->addDecl(Block);
15451 if (CurScope)
15452 PushDeclContext(CurScope, Block);
15453 else
15454 CurContext = Block;
15455
15456 getCurBlock()->HasImplicitReturnType = true;
15457
15458 // Enter a new evaluation context to insulate the block from any
15459 // cleanups from the enclosing full-expression.
15460 PushExpressionEvaluationContext(
15461 ExpressionEvaluationContext::PotentiallyEvaluated);
15462}
15463
15464void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15465 Scope *CurScope) {
15466 assert(ParamInfo.getIdentifier() == nullptr &&(static_cast<void> (0))
15467 "block-id should have no identifier!")(static_cast<void> (0));
15468 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral)(static_cast<void> (0));
15469 BlockScopeInfo *CurBlock = getCurBlock();
15470
15471 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15472 QualType T = Sig->getType();
15473
15474 // FIXME: We should allow unexpanded parameter packs here, but that would,
15475 // in turn, make the block expression contain unexpanded parameter packs.
15476 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15477 // Drop the parameters.
15478 FunctionProtoType::ExtProtoInfo EPI;
15479 EPI.HasTrailingReturn = false;
15480 EPI.TypeQuals.addConst();
15481 T = Context.getFunctionType(Context.DependentTy, None, EPI);
15482 Sig = Context.getTrivialTypeSourceInfo(T);
15483 }
15484
15485 // GetTypeForDeclarator always produces a function type for a block
15486 // literal signature. Furthermore, it is always a FunctionProtoType
15487 // unless the function was written with a typedef.
15488 assert(T->isFunctionType() &&(static_cast<void> (0))
15489 "GetTypeForDeclarator made a non-function block signature")(static_cast<void> (0));
15490
15491 // Look for an explicit signature in that function type.
15492 FunctionProtoTypeLoc ExplicitSignature;
15493
15494 if ((ExplicitSignature = Sig->getTypeLoc()
15495 .getAsAdjusted<FunctionProtoTypeLoc>())) {
15496
15497 // Check whether that explicit signature was synthesized by
15498 // GetTypeForDeclarator. If so, don't save that as part of the
15499 // written signature.
15500 if (ExplicitSignature.getLocalRangeBegin() ==
15501 ExplicitSignature.getLocalRangeEnd()) {
15502 // This would be much cheaper if we stored TypeLocs instead of
15503 // TypeSourceInfos.
15504 TypeLoc Result = ExplicitSignature.getReturnLoc();
15505 unsigned Size = Result.getFullDataSize();
15506 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15507 Sig->getTypeLoc().initializeFullCopy(Result, Size);
15508
15509 ExplicitSignature = FunctionProtoTypeLoc();
15510 }
15511 }
15512
15513 CurBlock->TheDecl->setSignatureAsWritten(Sig);
15514 CurBlock->FunctionType = T;
15515
15516 const auto *Fn = T->castAs<FunctionType>();
15517 QualType RetTy = Fn->getReturnType();
15518 bool isVariadic =
15519 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15520
15521 CurBlock->TheDecl->setIsVariadic(isVariadic);
15522
15523 // Context.DependentTy is used as a placeholder for a missing block
15524 // return type. TODO: what should we do with declarators like:
15525 // ^ * { ... }
15526 // If the answer is "apply template argument deduction"....
15527 if (RetTy != Context.DependentTy) {
15528 CurBlock->ReturnType = RetTy;
15529 CurBlock->TheDecl->setBlockMissingReturnType(false);
15530 CurBlock->HasImplicitReturnType = false;
15531 }
15532
15533 // Push block parameters from the declarator if we had them.
15534 SmallVector<ParmVarDecl*, 8> Params;
15535 if (ExplicitSignature) {
15536 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15537 ParmVarDecl *Param = ExplicitSignature.getParam(I);
15538 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15539 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15540 // Diagnose this as an extension in C17 and earlier.
15541 if (!getLangOpts().C2x)
15542 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15543 }
15544 Params.push_back(Param);
15545 }
15546
15547 // Fake up parameter variables if we have a typedef, like
15548 // ^ fntype { ... }
15549 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15550 for (const auto &I : Fn->param_types()) {
15551 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15552 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15553 Params.push_back(Param);
15554 }
15555 }
15556
15557 // Set the parameters on the block decl.
15558 if (!Params.empty()) {
15559 CurBlock->TheDecl->setParams(Params);
15560 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15561 /*CheckParameterNames=*/false);
15562 }
15563
15564 // Finally we can process decl attributes.
15565 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15566
15567 // Put the parameter variables in scope.
15568 for (auto AI : CurBlock->TheDecl->parameters()) {
15569 AI->setOwningFunction(CurBlock->TheDecl);
15570
15571 // If this has an identifier, add it to the scope stack.
15572 if (AI->getIdentifier()) {
15573 CheckShadow(CurBlock->TheScope, AI);
15574
15575 PushOnScopeChains(AI, CurBlock->TheScope);
15576 }
15577 }
15578}
15579
15580/// ActOnBlockError - If there is an error parsing a block, this callback
15581/// is invoked to pop the information about the block from the action impl.
15582void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15583 // Leave the expression-evaluation context.
15584 DiscardCleanupsInEvaluationContext();
15585 PopExpressionEvaluationContext();
15586
15587 // Pop off CurBlock, handle nested blocks.
15588 PopDeclContext();
15589 PopFunctionScopeInfo();
15590}
15591
15592/// ActOnBlockStmtExpr - This is called when the body of a block statement
15593/// literal was successfully completed. ^(int x){...}
15594ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15595 Stmt *Body, Scope *CurScope) {
15596 // If blocks are disabled, emit an error.
15597 if (!LangOpts.Blocks)
15598 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15599
15600 // Leave the expression-evaluation context.
15601 if (hasAnyUnrecoverableErrorsInThisFunction())
15602 DiscardCleanupsInEvaluationContext();
15603 assert(!Cleanup.exprNeedsCleanups() &&(static_cast<void> (0))
15604 "cleanups within block not correctly bound!")(static_cast<void> (0));
15605 PopExpressionEvaluationContext();
15606
15607 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15608 BlockDecl *BD = BSI->TheDecl;
15609
15610 if (BSI->HasImplicitReturnType)
15611 deduceClosureReturnType(*BSI);
15612
15613 QualType RetTy = Context.VoidTy;
15614 if (!BSI->ReturnType.isNull())
15615 RetTy = BSI->ReturnType;
15616
15617 bool NoReturn = BD->hasAttr<NoReturnAttr>();
15618 QualType BlockTy;
15619
15620 // If the user wrote a function type in some form, try to use that.
15621 if (!BSI->FunctionType.isNull()) {
15622 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15623
15624 FunctionType::ExtInfo Ext = FTy->getExtInfo();
15625 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15626
15627 // Turn protoless block types into nullary block types.
15628 if (isa<FunctionNoProtoType>(FTy)) {
15629 FunctionProtoType::ExtProtoInfo EPI;
15630 EPI.ExtInfo = Ext;
15631 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15632
15633 // Otherwise, if we don't need to change anything about the function type,
15634 // preserve its sugar structure.
15635 } else if (FTy->getReturnType() == RetTy &&
15636 (!NoReturn || FTy->getNoReturnAttr())) {
15637 BlockTy = BSI->FunctionType;
15638
15639 // Otherwise, make the minimal modifications to the function type.
15640 } else {
15641 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15642 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15643 EPI.TypeQuals = Qualifiers();
15644 EPI.ExtInfo = Ext;
15645 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15646 }
15647
15648 // If we don't have a function type, just build one from nothing.
15649 } else {
15650 FunctionProtoType::ExtProtoInfo EPI;
15651 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15652 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15653 }
15654
15655 DiagnoseUnusedParameters(BD->parameters());
15656 BlockTy = Context.getBlockPointerType(BlockTy);
15657
15658 // If needed, diagnose invalid gotos and switches in the block.
15659 if (getCurFunction()->NeedsScopeChecking() &&
15660 !PP.isCodeCompletionEnabled())
15661 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15662
15663 BD->setBody(cast<CompoundStmt>(Body));
15664
15665 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15666 DiagnoseUnguardedAvailabilityViolations(BD);
15667
15668 // Try to apply the named return value optimization. We have to check again
15669 // if we can do this, though, because blocks keep return statements around
15670 // to deduce an implicit return type.
15671 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15672 !BD->isDependentContext())
15673 computeNRVO(Body, BSI);
15674
15675 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15676 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15677 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15678 NTCUK_Destruct|NTCUK_Copy);
15679
15680 PopDeclContext();
15681
15682 // Set the captured variables on the block.
15683 SmallVector<BlockDecl::Capture, 4> Captures;
15684 for (Capture &Cap : BSI->Captures) {
15685 if (Cap.isInvalid() || Cap.isThisCapture())
15686 continue;
15687
15688 VarDecl *Var = Cap.getVariable();
15689 Expr *CopyExpr = nullptr;
15690 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15691 if (const RecordType *Record =
15692 Cap.getCaptureType()->getAs<RecordType>()) {
15693 // The capture logic needs the destructor, so make sure we mark it.
15694 // Usually this is unnecessary because most local variables have
15695 // their destructors marked at declaration time, but parameters are
15696 // an exception because it's technically only the call site that
15697 // actually requires the destructor.
15698 if (isa<ParmVarDecl>(Var))
15699 FinalizeVarWithDestructor(Var, Record);
15700
15701 // Enter a separate potentially-evaluated context while building block
15702 // initializers to isolate their cleanups from those of the block
15703 // itself.
15704 // FIXME: Is this appropriate even when the block itself occurs in an
15705 // unevaluated operand?
15706 EnterExpressionEvaluationContext EvalContext(
15707 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15708
15709 SourceLocation Loc = Cap.getLocation();
15710
15711 ExprResult Result = BuildDeclarationNameExpr(
15712 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15713
15714 // According to the blocks spec, the capture of a variable from
15715 // the stack requires a const copy constructor. This is not true
15716 // of the copy/move done to move a __block variable to the heap.
15717 if (!Result.isInvalid() &&
15718 !Result.get()->getType().isConstQualified()) {
15719 Result = ImpCastExprToType(Result.get(),
15720 Result.get()->getType().withConst(),
15721 CK_NoOp, VK_LValue);
15722 }
15723
15724 if (!Result.isInvalid()) {
15725 Result = PerformCopyInitialization(
15726 InitializedEntity::InitializeBlock(Var->getLocation(),
15727 Cap.getCaptureType(), false),
15728 Loc, Result.get());
15729 }
15730
15731 // Build a full-expression copy expression if initialization
15732 // succeeded and used a non-trivial constructor. Recover from
15733 // errors by pretending that the copy isn't necessary.
15734 if (!Result.isInvalid() &&
15735 !cast<CXXConstructExpr>(Result.get())->getConstructor()
15736 ->isTrivial()) {
15737 Result = MaybeCreateExprWithCleanups(Result);
15738 CopyExpr = Result.get();
15739 }
15740 }
15741 }
15742
15743 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15744 CopyExpr);
15745 Captures.push_back(NewCap);
15746 }
15747 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15748
15749 // Pop the block scope now but keep it alive to the end of this function.
15750 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15751 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15752
15753 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15754
15755 // If the block isn't obviously global, i.e. it captures anything at
15756 // all, then we need to do a few things in the surrounding context:
15757 if (Result->getBlockDecl()->hasCaptures()) {
15758 // First, this expression has a new cleanup object.
15759 ExprCleanupObjects.push_back(Result->getBlockDecl());
15760 Cleanup.setExprNeedsCleanups(true);
15761
15762 // It also gets a branch-protected scope if any of the captured
15763 // variables needs destruction.
15764 for (const auto &CI : Result->getBlockDecl()->captures()) {
15765 const VarDecl *var = CI.getVariable();
15766 if (var->getType().isDestructedType() != QualType::DK_none) {
15767 setFunctionHasBranchProtectedScope();
15768 break;
15769 }
15770 }
15771 }
15772
15773 if (getCurFunction())
15774 getCurFunction()->addBlock(BD);
15775
15776 return Result;
15777}
15778
15779ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15780 SourceLocation RPLoc) {
15781 TypeSourceInfo *TInfo;
15782 GetTypeFromParser(Ty, &TInfo);
15783 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15784}
15785
15786ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15787 Expr *E, TypeSourceInfo *TInfo,
15788 SourceLocation RPLoc) {
15789 Expr *OrigExpr = E;
15790 bool IsMS = false;
15791
15792 // CUDA device code does not support varargs.
15793 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15794 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15795 CUDAFunctionTarget T = IdentifyCUDATarget(F);
15796 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15797 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15798 }
15799 }
15800
15801 // NVPTX does not support va_arg expression.
15802 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15803 Context.getTargetInfo().getTriple().isNVPTX())
15804 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15805
15806 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15807 // as Microsoft ABI on an actual Microsoft platform, where
15808 // __builtin_ms_va_list and __builtin_va_list are the same.)
15809 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15810 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15811 QualType MSVaListType = Context.getBuiltinMSVaListType();
15812 if (Context.hasSameType(MSVaListType, E->getType())) {
15813 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15814 return ExprError();
15815 IsMS = true;
15816 }
15817 }
15818
15819 // Get the va_list type
15820 QualType VaListType = Context.getBuiltinVaListType();
15821 if (!IsMS) {
15822 if (VaListType->isArrayType()) {
15823 // Deal with implicit array decay; for example, on x86-64,
15824 // va_list is an array, but it's supposed to decay to
15825 // a pointer for va_arg.
15826 VaListType = Context.getArrayDecayedType(VaListType);
15827 // Make sure the input expression also decays appropriately.
15828 ExprResult Result = UsualUnaryConversions(E);
15829 if (Result.isInvalid())
15830 return ExprError();
15831 E = Result.get();
15832 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15833 // If va_list is a record type and we are compiling in C++ mode,
15834 // check the argument using reference binding.
15835 InitializedEntity Entity = InitializedEntity::InitializeParameter(
15836 Context, Context.getLValueReferenceType(VaListType), false);
15837 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15838 if (Init.isInvalid())
15839 return ExprError();
15840 E = Init.getAs<Expr>();
15841 } else {
15842 // Otherwise, the va_list argument must be an l-value because
15843 // it is modified by va_arg.
15844 if (!E->isTypeDependent() &&
15845 CheckForModifiableLvalue(E, BuiltinLoc, *this))
15846 return ExprError();
15847 }
15848 }
15849
15850 if (!IsMS && !E->isTypeDependent() &&
15851 !Context.hasSameType(VaListType, E->getType()))
15852 return ExprError(
15853 Diag(E->getBeginLoc(),
15854 diag::err_first_argument_to_va_arg_not_of_type_va_list)
15855 << OrigExpr->getType() << E->getSourceRange());
15856
15857 if (!TInfo->getType()->isDependentType()) {
15858 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15859 diag::err_second_parameter_to_va_arg_incomplete,
15860 TInfo->getTypeLoc()))
15861 return ExprError();
15862
15863 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15864 TInfo->getType(),
15865 diag::err_second_parameter_to_va_arg_abstract,
15866 TInfo->getTypeLoc()))
15867 return ExprError();
15868
15869 if (!TInfo->getType().isPODType(Context)) {
15870 Diag(TInfo->getTypeLoc().getBeginLoc(),
15871 TInfo->getType()->isObjCLifetimeType()
15872 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15873 : diag::warn_second_parameter_to_va_arg_not_pod)
15874 << TInfo->getType()
15875 << TInfo->getTypeLoc().getSourceRange();
15876 }
15877
15878 // Check for va_arg where arguments of the given type will be promoted
15879 // (i.e. this va_arg is guaranteed to have undefined behavior).
15880 QualType PromoteType;
15881 if (TInfo->getType()->isPromotableIntegerType()) {
15882 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15883 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
15884 // and C2x 7.16.1.1p2 says, in part:
15885 // If type is not compatible with the type of the actual next argument
15886 // (as promoted according to the default argument promotions), the
15887 // behavior is undefined, except for the following cases:
15888 // - both types are pointers to qualified or unqualified versions of
15889 // compatible types;
15890 // - one type is a signed integer type, the other type is the
15891 // corresponding unsigned integer type, and the value is
15892 // representable in both types;
15893 // - one type is pointer to qualified or unqualified void and the
15894 // other is a pointer to a qualified or unqualified character type.
15895 // Given that type compatibility is the primary requirement (ignoring
15896 // qualifications), you would think we could call typesAreCompatible()
15897 // directly to test this. However, in C++, that checks for *same type*,
15898 // which causes false positives when passing an enumeration type to
15899 // va_arg. Instead, get the underlying type of the enumeration and pass
15900 // that.
15901 QualType UnderlyingType = TInfo->getType();
15902 if (const auto *ET = UnderlyingType->getAs<EnumType>())
15903 UnderlyingType = ET->getDecl()->getIntegerType();
15904 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
15905 /*CompareUnqualified*/ true))
15906 PromoteType = QualType();
15907
15908 // If the types are still not compatible, we need to test whether the
15909 // promoted type and the underlying type are the same except for
15910 // signedness. Ask the AST for the correctly corresponding type and see
15911 // if that's compatible.
15912 if (!PromoteType.isNull() &&
15913 PromoteType->isUnsignedIntegerType() !=
15914 UnderlyingType->isUnsignedIntegerType()) {
15915 UnderlyingType =
15916 UnderlyingType->isUnsignedIntegerType()
15917 ? Context.getCorrespondingSignedType(UnderlyingType)
15918 : Context.getCorrespondingUnsignedType(UnderlyingType);
15919 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
15920 /*CompareUnqualified*/ true))
15921 PromoteType = QualType();
15922 }
15923 }
15924 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15925 PromoteType = Context.DoubleTy;
15926 if (!PromoteType.isNull())
15927 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15928 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15929 << TInfo->getType()
15930 << PromoteType
15931 << TInfo->getTypeLoc().getSourceRange());
15932 }
15933
15934 QualType T = TInfo->getType().getNonLValueExprType(Context);
15935 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15936}
15937
15938ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15939 // The type of __null will be int or long, depending on the size of
15940 // pointers on the target.
15941 QualType Ty;
15942 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15943 if (pw == Context.getTargetInfo().getIntWidth())
15944 Ty = Context.IntTy;
15945 else if (pw == Context.getTargetInfo().getLongWidth())
15946 Ty = Context.LongTy;
15947 else if (pw == Context.getTargetInfo().getLongLongWidth())
15948 Ty = Context.LongLongTy;
15949 else {
15950 llvm_unreachable("I don't know size of pointer!")__builtin_unreachable();
15951 }
15952
15953 return new (Context) GNUNullExpr(Ty, TokenLoc);
15954}
15955
15956ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15957 SourceLocation BuiltinLoc,
15958 SourceLocation RPLoc) {
15959 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15960}
15961
15962ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15963 SourceLocation BuiltinLoc,
15964 SourceLocation RPLoc,
15965 DeclContext *ParentContext) {
15966 return new (Context)
15967 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15968}
15969
15970bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15971 bool Diagnose) {
15972 if (!getLangOpts().ObjC)
15973 return false;
15974
15975 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15976 if (!PT)
15977 return false;
15978 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15979
15980 // Ignore any parens, implicit casts (should only be
15981 // array-to-pointer decays), and not-so-opaque values. The last is
15982 // important for making this trigger for property assignments.
15983 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15984 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15985 if (OV->getSourceExpr())
15986 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15987
15988 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15989 if (!PT->isObjCIdType() &&
15990 !(ID && ID->getIdentifier()->isStr("NSString")))
15991 return false;
15992 if (!SL->isAscii())
15993 return false;
15994
15995 if (Diagnose) {
15996 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15997 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15998 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15999 }
16000 return true;
16001 }
16002
16003 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16004 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16005 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16006 !SrcExpr->isNullPointerConstant(
16007 getASTContext(), Expr::NPC_NeverValueDependent)) {
16008 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16009 return false;
16010 if (Diagnose) {
16011 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16012 << /*number*/1
16013 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16014 Expr *NumLit =
16015 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16016 if (NumLit)
16017 Exp = NumLit;
16018 }
16019 return true;
16020 }
16021
16022 return false;
16023}
16024
16025static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16026 const Expr *SrcExpr) {
16027 if (!DstType->isFunctionPointerType() ||
16028 !SrcExpr->getType()->isFunctionType())
16029 return false;
16030
16031 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16032 if (!DRE)
16033 return false;
16034
16035 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16036 if (!FD)
16037 return false;
16038
16039 return !S.checkAddressOfFunctionIsAvailable(FD,
16040 /*Complain=*/true,
16041 SrcExpr->getBeginLoc());
16042}
16043
16044bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16045 SourceLocation Loc,
16046 QualType DstType, QualType SrcType,
16047 Expr *SrcExpr, AssignmentAction Action,
16048 bool *Complained) {
16049 if (Complained)
16050 *Complained = false;
16051
16052 // Decode the result (notice that AST's are still created for extensions).
16053 bool CheckInferredResultType = false;
16054 bool isInvalid = false;
16055 unsigned DiagKind = 0;
16056 ConversionFixItGenerator ConvHints;
16057 bool MayHaveConvFixit = false;
16058 bool MayHaveFunctionDiff = false;
16059 const ObjCInterfaceDecl *IFace = nullptr;
16060 const ObjCProtocolDecl *PDecl = nullptr;
16061
16062 switch (ConvTy) {
16063 case Compatible:
16064 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16065 return false;
16066
16067 case PointerToInt:
16068 if (getLangOpts().CPlusPlus) {
16069 DiagKind = diag::err_typecheck_convert_pointer_int;
16070 isInvalid = true;
16071 } else {
16072 DiagKind = diag::ext_typecheck_convert_pointer_int;
16073 }
16074 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16075 MayHaveConvFixit = true;
16076 break;
16077 case IntToPointer:
16078 if (getLangOpts().CPlusPlus) {
16079 DiagKind = diag::err_typecheck_convert_int_pointer;
16080 isInvalid = true;
16081 } else {
16082 DiagKind = diag::ext_typecheck_convert_int_pointer;
16083 }
16084 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16085 MayHaveConvFixit = true;
16086 break;
16087 case IncompatibleFunctionPointer:
16088 if (getLangOpts().CPlusPlus) {
16089 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16090 isInvalid = true;
16091 } else {
16092 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16093 }
16094 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16095 MayHaveConvFixit = true;
16096 break;
16097 case IncompatiblePointer:
16098 if (Action == AA_Passing_CFAudited) {
16099 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16100 } else if (getLangOpts().CPlusPlus) {
16101 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16102 isInvalid = true;
16103 } else {
16104 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16105 }
16106 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16107 SrcType->isObjCObjectPointerType();
16108 if (!CheckInferredResultType) {
16109 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16110 } else if (CheckInferredResultType) {
16111 SrcType = SrcType.getUnqualifiedType();
16112 DstType = DstType.getUnqualifiedType();
16113 }
16114 MayHaveConvFixit = true;
16115 break;
16116 case IncompatiblePointerSign:
16117 if (getLangOpts().CPlusPlus) {
16118 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16119 isInvalid = true;
16120 } else {
16121 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16122 }
16123 break;
16124 case FunctionVoidPointer:
16125 if (getLangOpts().CPlusPlus) {
16126 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16127 isInvalid = true;
16128 } else {
16129 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16130 }
16131 break;
16132 case IncompatiblePointerDiscardsQualifiers: {
16133 // Perform array-to-pointer decay if necessary.
16134 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16135
16136 isInvalid = true;
16137
16138 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16139 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16140 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16141 DiagKind = diag::err_typecheck_incompatible_address_space;
16142 break;
16143
16144 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16145 DiagKind = diag::err_typecheck_incompatible_ownership;
16146 break;
16147 }
16148
16149 llvm_unreachable("unknown error case for discarding qualifiers!")__builtin_unreachable();
16150 // fallthrough
16151 }
16152 case CompatiblePointerDiscardsQualifiers:
16153 // If the qualifiers lost were because we were applying the
16154 // (deprecated) C++ conversion from a string literal to a char*
16155 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16156 // Ideally, this check would be performed in
16157 // checkPointerTypesForAssignment. However, that would require a
16158 // bit of refactoring (so that the second argument is an
16159 // expression, rather than a type), which should be done as part
16160 // of a larger effort to fix checkPointerTypesForAssignment for
16161 // C++ semantics.
16162 if (getLangOpts().CPlusPlus &&
16163 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16164 return false;
16165 if (getLangOpts().CPlusPlus) {
16166 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16167 isInvalid = true;
16168 } else {
16169 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16170 }
16171
16172 break;
16173 case IncompatibleNestedPointerQualifiers:
16174 if (getLangOpts().CPlusPlus) {
16175 isInvalid = true;
16176 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16177 } else {
16178 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16179 }
16180 break;
16181 case IncompatibleNestedPointerAddressSpaceMismatch:
16182 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16183 isInvalid = true;
16184 break;
16185 case IntToBlockPointer:
16186 DiagKind = diag::err_int_to_block_pointer;
16187 isInvalid = true;
16188 break;
16189 case IncompatibleBlockPointer:
16190 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16191 isInvalid = true;
16192 break;
16193 case IncompatibleObjCQualifiedId: {
16194 if (SrcType->isObjCQualifiedIdType()) {
16195 const ObjCObjectPointerType *srcOPT =
16196 SrcType->castAs<ObjCObjectPointerType>();
16197 for (auto *srcProto : srcOPT->quals()) {
16198 PDecl = srcProto;
16199 break;
16200 }
16201 if (const ObjCInterfaceType *IFaceT =
16202 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16203 IFace = IFaceT->getDecl();
16204 }
16205 else if (DstType->isObjCQualifiedIdType()) {
16206 const ObjCObjectPointerType *dstOPT =
16207 DstType->castAs<ObjCObjectPointerType>();
16208 for (auto *dstProto : dstOPT->quals()) {
16209 PDecl = dstProto;
16210 break;
16211 }
16212 if (const ObjCInterfaceType *IFaceT =
16213 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16214 IFace = IFaceT->getDecl();
16215 }
16216 if (getLangOpts().CPlusPlus) {
16217 DiagKind = diag::err_incompatible_qualified_id;
16218 isInvalid = true;
16219 } else {
16220 DiagKind = diag::warn_incompatible_qualified_id;
16221 }
16222 break;
16223 }
16224 case IncompatibleVectors:
16225 if (getLangOpts().CPlusPlus) {
16226 DiagKind = diag::err_incompatible_vectors;
16227 isInvalid = true;
16228 } else {
16229 DiagKind = diag::warn_incompatible_vectors;
16230 }
16231 break;
16232 case IncompatibleObjCWeakRef:
16233 DiagKind = diag::err_arc_weak_unavailable_assign;
16234 isInvalid = true;
16235 break;
16236 case Incompatible:
16237 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16238 if (Complained)
16239 *Complained = true;
16240 return true;
16241 }
16242
16243 DiagKind = diag::err_typecheck_convert_incompatible;
16244 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16245 MayHaveConvFixit = true;
16246 isInvalid = true;
16247 MayHaveFunctionDiff = true;
16248 break;
16249 }
16250
16251 QualType FirstType, SecondType;
16252 switch (Action) {
16253 case AA_Assigning:
16254 case AA_Initializing:
16255 // The destination type comes first.
16256 FirstType = DstType;
16257 SecondType = SrcType;
16258 break;
16259
16260 case AA_Returning:
16261 case AA_Passing:
16262 case AA_Passing_CFAudited:
16263 case AA_Converting:
16264 case AA_Sending:
16265 case AA_Casting:
16266 // The source type comes first.
16267 FirstType = SrcType;
16268 SecondType = DstType;
16269 break;
16270 }
16271
16272 PartialDiagnostic FDiag = PDiag(DiagKind);
16273 if (Action == AA_Passing_CFAudited)
16274 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16275 else
16276 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16277
16278 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16279 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16280 auto isPlainChar = [](const clang::Type *Type) {
16281 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16282 Type->isSpecificBuiltinType(BuiltinType::Char_U);
16283 };
16284 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16285 isPlainChar(SecondType->getPointeeOrArrayElementType()));
16286 }
16287
16288 // If we can fix the conversion, suggest the FixIts.
16289 if (!ConvHints.isNull()) {
16290 for (FixItHint &H : ConvHints.Hints)
16291 FDiag << H;
16292 }
16293
16294 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16295
16296 if (MayHaveFunctionDiff)
16297 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16298
16299 Diag(Loc, FDiag);
16300 if ((DiagKind == diag::warn_incompatible_qualified_id ||
16301 DiagKind == diag::err_incompatible_qualified_id) &&
16302 PDecl && IFace && !IFace->hasDefinition())
16303 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16304 << IFace << PDecl;
16305
16306 if (SecondType == Context.OverloadTy)
16307 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16308 FirstType, /*TakingAddress=*/true);
16309
16310 if (CheckInferredResultType)
16311 EmitRelatedResultTypeNote(SrcExpr);
16312
16313 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16314 EmitRelatedResultTypeNoteForReturn(DstType);
16315
16316 if (Complained)
16317 *Complained = true;
16318 return isInvalid;
16319}
16320
16321ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16322 llvm::APSInt *Result,
16323 AllowFoldKind CanFold) {
16324 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16325 public:
16326 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16327 QualType T) override {
16328 return S.Diag(Loc, diag::err_ice_not_integral)
16329 << T << S.LangOpts.CPlusPlus;
16330 }
16331 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16332 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16333 }
16334 } Diagnoser;
16335
16336 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16337}
16338
16339ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16340 llvm::APSInt *Result,
16341 unsigned DiagID,
16342 AllowFoldKind CanFold) {
16343 class IDDiagnoser : public VerifyICEDiagnoser {
16344 unsigned DiagID;
16345
16346 public:
16347 IDDiagnoser(unsigned DiagID)
16348 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16349
16350 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16351 return S.Diag(Loc, DiagID);
16352 }
16353 } Diagnoser(DiagID);
16354
16355 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16356}
16357
16358Sema::SemaDiagnosticBuilder
16359Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16360 QualType T) {
16361 return diagnoseNotICE(S, Loc);
16362}
16363
16364Sema::SemaDiagnosticBuilder
16365Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16366 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16367}
16368
16369ExprResult
16370Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16371 VerifyICEDiagnoser &Diagnoser,
16372 AllowFoldKind CanFold) {
16373 SourceLocation DiagLoc = E->getBeginLoc();
16374
16375 if (getLangOpts().CPlusPlus11) {
16376 // C++11 [expr.const]p5:
16377 // If an expression of literal class type is used in a context where an
16378 // integral constant expression is required, then that class type shall
16379 // have a single non-explicit conversion function to an integral or
16380 // unscoped enumeration type
16381 ExprResult Converted;
16382 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16383 VerifyICEDiagnoser &BaseDiagnoser;
16384 public:
16385 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16386 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16387 BaseDiagnoser.Suppress, true),
16388 BaseDiagnoser(BaseDiagnoser) {}
16389
16390 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16391 QualType T) override {
16392 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16393 }
16394
16395 SemaDiagnosticBuilder diagnoseIncomplete(
16396 Sema &S, SourceLocation Loc, QualType T) override {
16397 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16398 }
16399
16400 SemaDiagnosticBuilder diagnoseExplicitConv(
16401 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16402 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16403 }
16404
16405 SemaDiagnosticBuilder noteExplicitConv(
16406 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16407 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16408 << ConvTy->isEnumeralType() << ConvTy;
16409 }
16410
16411 SemaDiagnosticBuilder diagnoseAmbiguous(
16412 Sema &S, SourceLocation Loc, QualType T) override {
16413 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16414 }
16415
16416 SemaDiagnosticBuilder noteAmbiguous(
16417 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16418 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16419 << ConvTy->isEnumeralType() << ConvTy;
16420 }
16421
16422 SemaDiagnosticBuilder diagnoseConversion(
16423 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16424 llvm_unreachable("conversion functions are permitted")__builtin_unreachable();
16425 }
16426 } ConvertDiagnoser(Diagnoser);
16427
16428 Converted = PerformContextualImplicitConversion(DiagLoc, E,
16429 ConvertDiagnoser);
16430 if (Converted.isInvalid())
16431 return Converted;
16432 E = Converted.get();
16433 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16434 return ExprError();
16435 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16436 // An ICE must be of integral or unscoped enumeration type.
16437 if (!Diagnoser.Suppress)
16438 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16439 << E->getSourceRange();
16440 return ExprError();
16441 }
16442
16443 ExprResult RValueExpr = DefaultLvalueConversion(E);
16444 if (RValueExpr.isInvalid())
16445 return ExprError();
16446
16447 E = RValueExpr.get();
16448
16449 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16450 // in the non-ICE case.
16451 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16452 if (Result)
16453 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16454 if (!isa<ConstantExpr>(E))
16455 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
16456 : ConstantExpr::Create(Context, E);
16457 return E;
16458 }
16459
16460 Expr::EvalResult EvalResult;
16461 SmallVector<PartialDiagnosticAt, 8> Notes;
16462 EvalResult.Diag = &Notes;
16463
16464 // Try to evaluate the expression, and produce diagnostics explaining why it's
16465 // not a constant expression as a side-effect.
16466 bool Folded =
16467 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16468 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16469
16470 if (!isa<ConstantExpr>(E))
16471 E = ConstantExpr::Create(Context, E, EvalResult.Val);
16472
16473 // In C++11, we can rely on diagnostics being produced for any expression
16474 // which is not a constant expression. If no diagnostics were produced, then
16475 // this is a constant expression.
16476 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16477 if (Result)
16478 *Result = EvalResult.Val.getInt();
16479 return E;
16480 }
16481
16482 // If our only note is the usual "invalid subexpression" note, just point
16483 // the caret at its location rather than producing an essentially
16484 // redundant note.
16485 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16486 diag::note_invalid_subexpr_in_const_expr) {
16487 DiagLoc = Notes[0].first;
16488 Notes.clear();
16489 }
16490
16491 if (!Folded || !CanFold) {
16492 if (!Diagnoser.Suppress) {
16493 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16494 for (const PartialDiagnosticAt &Note : Notes)
16495 Diag(Note.first, Note.second);
16496 }
16497
16498 return ExprError();
16499 }
16500
16501 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16502 for (const PartialDiagnosticAt &Note : Notes)
16503 Diag(Note.first, Note.second);
16504
16505 if (Result)
16506 *Result = EvalResult.Val.getInt();
16507 return E;
16508}
16509
16510namespace {
16511 // Handle the case where we conclude a expression which we speculatively
16512 // considered to be unevaluated is actually evaluated.
16513 class TransformToPE : public TreeTransform<TransformToPE> {
16514 typedef TreeTransform<TransformToPE> BaseTransform;
16515
16516 public:
16517 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16518
16519 // Make sure we redo semantic analysis
16520 bool AlwaysRebuild() { return true; }
16521 bool ReplacingOriginal() { return true; }
16522
16523 // We need to special-case DeclRefExprs referring to FieldDecls which
16524 // are not part of a member pointer formation; normal TreeTransforming
16525 // doesn't catch this case because of the way we represent them in the AST.
16526 // FIXME: This is a bit ugly; is it really the best way to handle this
16527 // case?
16528 //
16529 // Error on DeclRefExprs referring to FieldDecls.
16530 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16531 if (isa<FieldDecl>(E->getDecl()) &&
16532 !SemaRef.isUnevaluatedContext())
16533 return SemaRef.Diag(E->getLocation(),
16534 diag::err_invalid_non_static_member_use)
16535 << E->getDecl() << E->getSourceRange();
16536
16537 return BaseTransform::TransformDeclRefExpr(E);
16538 }
16539
16540 // Exception: filter out member pointer formation
16541 ExprResult TransformUnaryOperator(UnaryOperator *E) {
16542 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16543 return E;
16544
16545 return BaseTransform::TransformUnaryOperator(E);
16546 }
16547
16548 // The body of a lambda-expression is in a separate expression evaluation
16549 // context so never needs to be transformed.
16550 // FIXME: Ideally we wouldn't transform the closure type either, and would
16551 // just recreate the capture expressions and lambda expression.
16552 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16553 return SkipLambdaBody(E, Body);
16554 }
16555 };
16556}
16557
16558ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16559 assert(isUnevaluatedContext() &&(static_cast<void> (0))
16560 "Should only transform unevaluated expressions")(static_cast<void> (0));
16561 ExprEvalContexts.back().Context =
16562 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16563 if (isUnevaluatedContext())
16564 return E;
16565 return TransformToPE(*this).TransformExpr(E);
16566}
16567
16568void
16569Sema::PushExpressionEvaluationContext(
16570 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16571 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16572 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16573 LambdaContextDecl, ExprContext);
16574 Cleanup.reset();
16575 if (!MaybeODRUseExprs.empty())
16576 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16577}
16578
16579void
16580Sema::PushExpressionEvaluationContext(
16581 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16582 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16583 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16584 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16585}
16586
16587namespace {
16588
16589const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16590 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16591 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16592 if (E->getOpcode() == UO_Deref)
16593 return CheckPossibleDeref(S, E->getSubExpr());
16594 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16595 return CheckPossibleDeref(S, E->getBase());
16596 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16597 return CheckPossibleDeref(S, E->getBase());
16598 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16599 QualType Inner;
16600 QualType Ty = E->getType();
16601 if (const auto *Ptr = Ty->getAs<PointerType>())
16602 Inner = Ptr->getPointeeType();
16603 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16604 Inner = Arr->getElementType();
16605 else
16606 return nullptr;
16607
16608 if (Inner->hasAttr(attr::NoDeref))
16609 return E;
16610 }
16611 return nullptr;
16612}
16613
16614} // namespace
16615
16616void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16617 for (const Expr *E : Rec.PossibleDerefs) {
16618 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16619 if (DeclRef) {
16620 const ValueDecl *Decl = DeclRef->getDecl();
16621 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16622 << Decl->getName() << E->getSourceRange();
16623 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16624 } else {
16625 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16626 << E->getSourceRange();
16627 }
16628 }
16629 Rec.PossibleDerefs.clear();
16630}
16631
16632/// Check whether E, which is either a discarded-value expression or an
16633/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16634/// and if so, remove it from the list of volatile-qualified assignments that
16635/// we are going to warn are deprecated.
16636void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16637 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16638 return;
16639
16640 // Note: ignoring parens here is not justified by the standard rules, but
16641 // ignoring parentheses seems like a more reasonable approach, and this only
16642 // drives a deprecation warning so doesn't affect conformance.
16643 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16644 if (BO->getOpcode() == BO_Assign) {
16645 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16646 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16647 LHSs.end());
16648 }
16649 }
16650}
16651
16652ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16653 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
16654 !Decl->isConsteval() || isConstantEvaluated() ||
16655 RebuildingImmediateInvocation)
16656 return E;
16657
16658 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16659 /// It's OK if this fails; we'll also remove this in
16660 /// HandleImmediateInvocations, but catching it here allows us to avoid
16661 /// walking the AST looking for it in simple cases.
16662 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16663 if (auto *DeclRef =
16664 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16665 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16666
16667 E = MaybeCreateExprWithCleanups(E);
16668
16669 ConstantExpr *Res = ConstantExpr::Create(
16670 getASTContext(), E.get(),
16671 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16672 getASTContext()),
16673 /*IsImmediateInvocation*/ true);
16674 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16675 return Res;
16676}
16677
16678static void EvaluateAndDiagnoseImmediateInvocation(
16679 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16680 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16681 Expr::EvalResult Eval;
16682 Eval.Diag = &Notes;
16683 ConstantExpr *CE = Candidate.getPointer();
16684 bool Result = CE->EvaluateAsConstantExpr(
16685 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16686 if (!Result || !Notes.empty()) {
16687 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16688 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16689 InnerExpr = FunctionalCast->getSubExpr();
16690 FunctionDecl *FD = nullptr;
16691 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16692 FD = cast<FunctionDecl>(Call->getCalleeDecl());
16693 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16694 FD = Call->getConstructor();
16695 else
16696 llvm_unreachable("unhandled decl kind")__builtin_unreachable();
16697 assert(FD->isConsteval())(static_cast<void> (0));
16698 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16699 for (auto &Note : Notes)
16700 SemaRef.Diag(Note.first, Note.second);
16701 return;
16702 }
16703 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16704}
16705
16706static void RemoveNestedImmediateInvocation(
16707 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16708 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16709 struct ComplexRemove : TreeTransform<ComplexRemove> {
16710 using Base = TreeTransform<ComplexRemove>;
16711 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16712 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16713 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16714 CurrentII;
16715 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16716 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16717 SmallVector<Sema::ImmediateInvocationCandidate,
16718 4>::reverse_iterator Current)
16719 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16720 void RemoveImmediateInvocation(ConstantExpr* E) {
16721 auto It = std::find_if(CurrentII, IISet.rend(),
16722 [E](Sema::ImmediateInvocationCandidate Elem) {
16723 return Elem.getPointer() == E;
16724 });
16725 assert(It != IISet.rend() &&(static_cast<void> (0))
16726 "ConstantExpr marked IsImmediateInvocation should "(static_cast<void> (0))
16727 "be present")(static_cast<void> (0));
16728 It->setInt(1); // Mark as deleted
16729 }
16730 ExprResult TransformConstantExpr(ConstantExpr *E) {
16731 if (!E->isImmediateInvocation())
16732 return Base::TransformConstantExpr(E);
16733 RemoveImmediateInvocation(E);
16734 return Base::TransformExpr(E->getSubExpr());
16735 }
16736 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16737 /// we need to remove its DeclRefExpr from the DRSet.
16738 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16739 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16740 return Base::TransformCXXOperatorCallExpr(E);
16741 }
16742 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16743 /// here.
16744 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16745 if (!Init)
16746 return Init;
16747 /// ConstantExpr are the first layer of implicit node to be removed so if
16748 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16749 if (auto *CE = dyn_cast<ConstantExpr>(Init))
16750 if (CE->isImmediateInvocation())
16751 RemoveImmediateInvocation(CE);
16752 return Base::TransformInitializer(Init, NotCopyInit);
16753 }
16754 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16755 DRSet.erase(E);
16756 return E;
16757 }
16758 bool AlwaysRebuild() { return false; }
16759 bool ReplacingOriginal() { return true; }
16760 bool AllowSkippingCXXConstructExpr() {
16761 bool Res = AllowSkippingFirstCXXConstructExpr;
16762 AllowSkippingFirstCXXConstructExpr = true;
16763 return Res;
16764 }
16765 bool AllowSkippingFirstCXXConstructExpr = true;
16766 } Transformer(SemaRef, Rec.ReferenceToConsteval,
16767 Rec.ImmediateInvocationCandidates, It);
16768
16769 /// CXXConstructExpr with a single argument are getting skipped by
16770 /// TreeTransform in some situtation because they could be implicit. This
16771 /// can only occur for the top-level CXXConstructExpr because it is used
16772 /// nowhere in the expression being transformed therefore will not be rebuilt.
16773 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16774 /// skipping the first CXXConstructExpr.
16775 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16776 Transformer.AllowSkippingFirstCXXConstructExpr = false;
16777
16778 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16779 assert(Res.isUsable())(static_cast<void> (0));
16780 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16781 It->getPointer()->setSubExpr(Res.get());
16782}
16783
16784static void
16785HandleImmediateInvocations(Sema &SemaRef,
16786 Sema::ExpressionEvaluationContextRecord &Rec) {
16787 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16788 Rec.ReferenceToConsteval.size() == 0) ||
16789 SemaRef.RebuildingImmediateInvocation)
16790 return;
16791
16792 /// When we have more then 1 ImmediateInvocationCandidates we need to check
16793 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16794 /// need to remove ReferenceToConsteval in the immediate invocation.
16795 if (Rec.ImmediateInvocationCandidates.size() > 1) {
16796
16797 /// Prevent sema calls during the tree transform from adding pointers that
16798 /// are already in the sets.
16799 llvm::SaveAndRestore<bool> DisableIITracking(
16800 SemaRef.RebuildingImmediateInvocation, true);
16801
16802 /// Prevent diagnostic during tree transfrom as they are duplicates
16803 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16804
16805 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16806 It != Rec.ImmediateInvocationCandidates.rend(); It++)
16807 if (!It->getInt())
16808 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16809 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16810 Rec.ReferenceToConsteval.size()) {
16811 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16812 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16813 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16814 bool VisitDeclRefExpr(DeclRefExpr *E) {
16815 DRSet.erase(E);
16816 return DRSet.size();
16817 }
16818 } Visitor(Rec.ReferenceToConsteval);
16819 Visitor.TraverseStmt(
16820 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16821 }
16822 for (auto CE : Rec.ImmediateInvocationCandidates)
16823 if (!CE.getInt())
16824 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16825 for (auto DR : Rec.ReferenceToConsteval) {
16826 auto *FD = cast<FunctionDecl>(DR->getDecl());
16827 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16828 << FD;
16829 SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16830 }
16831}
16832
16833void Sema::PopExpressionEvaluationContext() {
16834 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16835 unsigned NumTypos = Rec.NumTypos;
16836
16837 if (!Rec.Lambdas.empty()) {
16838 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16839 if (!getLangOpts().CPlusPlus20 &&
16840 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
16841 Rec.isUnevaluated() ||
16842 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
16843 unsigned D;
16844 if (Rec.isUnevaluated()) {
16845 // C++11 [expr.prim.lambda]p2:
16846 // A lambda-expression shall not appear in an unevaluated operand
16847 // (Clause 5).
16848 D = diag::err_lambda_unevaluated_operand;
16849 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16850 // C++1y [expr.const]p2:
16851 // A conditional-expression e is a core constant expression unless the
16852 // evaluation of e, following the rules of the abstract machine, would
16853 // evaluate [...] a lambda-expression.
16854 D = diag::err_lambda_in_constant_expression;
16855 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16856 // C++17 [expr.prim.lamda]p2:
16857 // A lambda-expression shall not appear [...] in a template-argument.
16858 D = diag::err_lambda_in_invalid_context;
16859 } else
16860 llvm_unreachable("Couldn't infer lambda error message.")__builtin_unreachable();
16861
16862 for (const auto *L : Rec.Lambdas)
16863 Diag(L->getBeginLoc(), D);
16864 }
16865 }
16866
16867 WarnOnPendingNoDerefs(Rec);
16868 HandleImmediateInvocations(*this, Rec);
16869
16870 // Warn on any volatile-qualified simple-assignments that are not discarded-
16871 // value expressions nor unevaluated operands (those cases get removed from
16872 // this list by CheckUnusedVolatileAssignment).
16873 for (auto *BO : Rec.VolatileAssignmentLHSs)
16874 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16875 << BO->getType();
16876
16877 // When are coming out of an unevaluated context, clear out any
16878 // temporaries that we may have created as part of the evaluation of
16879 // the expression in that context: they aren't relevant because they
16880 // will never be constructed.
16881 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16882 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16883 ExprCleanupObjects.end());
16884 Cleanup = Rec.ParentCleanup;
16885 CleanupVarDeclMarking();
16886 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16887 // Otherwise, merge the contexts together.
16888 } else {
16889 Cleanup.mergeFrom(Rec.ParentCleanup);
16890 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16891 Rec.SavedMaybeODRUseExprs.end());
16892 }
16893
16894 // Pop the current expression evaluation context off the stack.
16895 ExprEvalContexts.pop_back();
16896
16897 // The global expression evaluation context record is never popped.
16898 ExprEvalContexts.back().NumTypos += NumTypos;
16899}
16900
16901void Sema::DiscardCleanupsInEvaluationContext() {
16902 ExprCleanupObjects.erase(
16903 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16904 ExprCleanupObjects.end());
16905 Cleanup.reset();
16906 MaybeODRUseExprs.clear();
16907}
16908
16909ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16910 ExprResult Result = CheckPlaceholderExpr(E);
16911 if (Result.isInvalid())
16912 return ExprError();
16913 E = Result.get();
16914 if (!E->getType()->isVariablyModifiedType())
16915 return E;
16916 return TransformToPotentiallyEvaluated(E);
16917}
16918
16919/// Are we in a context that is potentially constant evaluated per C++20
16920/// [expr.const]p12?
16921static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16922 /// C++2a [expr.const]p12:
16923 // An expression or conversion is potentially constant evaluated if it is
16924 switch (SemaRef.ExprEvalContexts.back().Context) {
16925 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16926 // -- a manifestly constant-evaluated expression,
16927 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16928 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16929 case Sema::ExpressionEvaluationContext::DiscardedStatement:
16930 // -- a potentially-evaluated expression,
16931 case Sema::ExpressionEvaluationContext::UnevaluatedList:
16932 // -- an immediate subexpression of a braced-init-list,
16933
16934 // -- [FIXME] an expression of the form & cast-expression that occurs
16935 // within a templated entity
16936 // -- a subexpression of one of the above that is not a subexpression of
16937 // a nested unevaluated operand.
16938 return true;
16939
16940 case Sema::ExpressionEvaluationContext::Unevaluated:
16941 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16942 // Expressions in this context are never evaluated.
16943 return false;
16944 }
16945 llvm_unreachable("Invalid context")__builtin_unreachable();
16946}
16947
16948/// Return true if this function has a calling convention that requires mangling
16949/// in the size of the parameter pack.
16950static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16951 // These manglings don't do anything on non-Windows or non-x86 platforms, so
16952 // we don't need parameter type sizes.
16953 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16954 if (!TT.isOSWindows() || !TT.isX86())
16955 return false;
16956
16957 // If this is C++ and this isn't an extern "C" function, parameters do not
16958 // need to be complete. In this case, C++ mangling will apply, which doesn't
16959 // use the size of the parameters.
16960 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16961 return false;
16962
16963 // Stdcall, fastcall, and vectorcall need this special treatment.
16964 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16965 switch (CC) {
16966 case CC_X86StdCall:
16967 case CC_X86FastCall:
16968 case CC_X86VectorCall:
16969 return true;
16970 default:
16971 break;
16972 }
16973 return false;
16974}
16975
16976/// Require that all of the parameter types of function be complete. Normally,
16977/// parameter types are only required to be complete when a function is called
16978/// or defined, but to mangle functions with certain calling conventions, the
16979/// mangler needs to know the size of the parameter list. In this situation,
16980/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16981/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16982/// result in a linker error. Clang doesn't implement this behavior, and instead
16983/// attempts to error at compile time.
16984static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16985 SourceLocation Loc) {
16986 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16987 FunctionDecl *FD;
16988 ParmVarDecl *Param;
16989
16990 public:
16991 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16992 : FD(FD), Param(Param) {}
16993
16994 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16995 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16996 StringRef CCName;
16997 switch (CC) {
16998 case CC_X86StdCall:
16999 CCName = "stdcall";
17000 break;
17001 case CC_X86FastCall:
17002 CCName = "fastcall";
17003 break;
17004 case CC_X86VectorCall:
17005 CCName = "vectorcall";
17006 break;
17007 default:
17008 llvm_unreachable("CC does not need mangling")__builtin_unreachable();
17009 }
17010
17011 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17012 << Param->getDeclName() << FD->getDeclName() << CCName;
17013 }
17014 };
17015
17016 for (ParmVarDecl *Param : FD->parameters()) {
17017 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17018 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17019 }
17020}
17021
17022namespace {
17023enum class OdrUseContext {
17024 /// Declarations in this context are not odr-used.
17025 None,
17026 /// Declarations in this context are formally odr-used, but this is a
17027 /// dependent context.
17028 Dependent,
17029 /// Declarations in this context are odr-used but not actually used (yet).
17030 FormallyOdrUsed,
17031 /// Declarations in this context are used.
17032 Used
17033};
17034}
17035
17036/// Are we within a context in which references to resolved functions or to
17037/// variables result in odr-use?
17038static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17039 OdrUseContext Result;
17040
17041 switch (SemaRef.ExprEvalContexts.back().Context) {
17042 case Sema::ExpressionEvaluationContext::Unevaluated:
17043 case Sema::ExpressionEvaluationContext::UnevaluatedList:
17044 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17045 return OdrUseContext::None;
17046
17047 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17048 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17049 Result = OdrUseContext::Used;
17050 break;
17051
17052 case Sema::ExpressionEvaluationContext::DiscardedStatement:
17053 Result = OdrUseContext::FormallyOdrUsed;
17054 break;
17055
17056 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17057 // A default argument formally results in odr-use, but doesn't actually
17058 // result in a use in any real sense until it itself is used.
17059 Result = OdrUseContext::FormallyOdrUsed;
17060 break;
17061 }
17062
17063 if (SemaRef.CurContext->isDependentContext())
17064 return OdrUseContext::Dependent;
17065
17066 return Result;
17067}
17068
17069static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17070 if (!Func->isConstexpr())
17071 return false;
17072
17073 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17074 return true;
17075 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17076 return CCD && CCD->getInheritedConstructor();
17077}
17078
17079/// Mark a function referenced, and check whether it is odr-used
17080/// (C++ [basic.def.odr]p2, C99 6.9p3)
17081void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17082 bool MightBeOdrUse) {
17083 assert(Func && "No function?")(static_cast<void> (0));
17084
17085 Func->setReferenced();
17086
17087 // Recursive functions aren't really used until they're used from some other
17088 // context.
17089 bool IsRecursiveCall = CurContext == Func;
17090
17091 // C++11 [basic.def.odr]p3:
17092 // A function whose name appears as a potentially-evaluated expression is
17093 // odr-used if it is the unique lookup result or the selected member of a
17094 // set of overloaded functions [...].
17095 //
17096 // We (incorrectly) mark overload resolution as an unevaluated context, so we
17097 // can just check that here.
17098 OdrUseContext OdrUse =
17099 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17100 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17101 OdrUse = OdrUseContext::FormallyOdrUsed;
17102
17103 // Trivial default constructors and destructors are never actually used.
17104 // FIXME: What about other special members?
17105 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17106 OdrUse == OdrUseContext::Used) {
17107 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17108 if (Constructor->isDefaultConstructor())
17109 OdrUse = OdrUseContext::FormallyOdrUsed;
17110 if (isa<CXXDestructorDecl>(Func))
17111 OdrUse = OdrUseContext::FormallyOdrUsed;
17112 }
17113
17114 // C++20 [expr.const]p12:
17115 // A function [...] is needed for constant evaluation if it is [...] a
17116 // constexpr function that is named by an expression that is potentially
17117 // constant evaluated
17118 bool NeededForConstantEvaluation =
17119 isPotentiallyConstantEvaluatedContext(*this) &&
17120 isImplicitlyDefinableConstexprFunction(Func);
17121
17122 // Determine whether we require a function definition to exist, per
17123 // C++11 [temp.inst]p3:
17124 // Unless a function template specialization has been explicitly
17125 // instantiated or explicitly specialized, the function template
17126 // specialization is implicitly instantiated when the specialization is
17127 // referenced in a context that requires a function definition to exist.
17128 // C++20 [temp.inst]p7:
17129 // The existence of a definition of a [...] function is considered to
17130 // affect the semantics of the program if the [...] function is needed for
17131 // constant evaluation by an expression
17132 // C++20 [basic.def.odr]p10:
17133 // Every program shall contain exactly one definition of every non-inline
17134 // function or variable that is odr-used in that program outside of a
17135 // discarded statement
17136 // C++20 [special]p1:
17137 // The implementation will implicitly define [defaulted special members]
17138 // if they are odr-used or needed for constant evaluation.
17139 //
17140 // Note that we skip the implicit instantiation of templates that are only
17141 // used in unused default arguments or by recursive calls to themselves.
17142 // This is formally non-conforming, but seems reasonable in practice.
17143 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17144 NeededForConstantEvaluation);
17145
17146 // C++14 [temp.expl.spec]p6:
17147 // If a template [...] is explicitly specialized then that specialization
17148 // shall be declared before the first use of that specialization that would
17149 // cause an implicit instantiation to take place, in every translation unit
17150 // in which such a use occurs
17151 if (NeedDefinition &&
17152 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17153 Func->getMemberSpecializationInfo()))
17154 checkSpecializationVisibility(Loc, Func);
17155
17156 if (getLangOpts().CUDA)
17157 CheckCUDACall(Loc, Func);
17158
17159 if (getLangOpts().SYCLIsDevice)
17160 checkSYCLDeviceFunction(Loc, Func);
17161
17162 // If we need a definition, try to create one.
17163 if (NeedDefinition && !Func->getBody()) {
17164 runWithSufficientStackSpace(Loc, [&] {
17165 if (CXXConstructorDecl *Constructor =
17166 dyn_cast<CXXConstructorDecl>(Func)) {
17167 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17168 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17169 if (Constructor->isDefaultConstructor()) {
17170 if (Constructor->isTrivial() &&
17171 !Constructor->hasAttr<DLLExportAttr>())
17172 return;
17173 DefineImplicitDefaultConstructor(Loc, Constructor);
17174 } else if (Constructor->isCopyConstructor()) {
17175 DefineImplicitCopyConstructor(Loc, Constructor);
17176 } else if (Constructor->isMoveConstructor()) {
17177 DefineImplicitMoveConstructor(Loc, Constructor);
17178 }
17179 } else if (Constructor->getInheritedConstructor()) {
17180 DefineInheritingConstructor(Loc, Constructor);
17181 }
17182 } else if (CXXDestructorDecl *Destructor =
17183 dyn_cast<CXXDestructorDecl>(Func)) {
17184 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17185 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17186 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17187 return;
17188 DefineImplicitDestructor(Loc, Destructor);
17189 }
17190 if (Destructor->isVirtual() && getLangOpts().AppleKext)
17191 MarkVTableUsed(Loc, Destructor->getParent());
17192 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17193 if (MethodDecl->isOverloadedOperator() &&
17194 MethodDecl->getOverloadedOperator() == OO_Equal) {
17195 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17196 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17197 if (MethodDecl->isCopyAssignmentOperator())
17198 DefineImplicitCopyAssignment(Loc, MethodDecl);
17199 else if (MethodDecl->isMoveAssignmentOperator())
17200 DefineImplicitMoveAssignment(Loc, MethodDecl);
17201 }
17202 } else if (isa<CXXConversionDecl>(MethodDecl) &&
17203 MethodDecl->getParent()->isLambda()) {
17204 CXXConversionDecl *Conversion =
17205 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17206 if (Conversion->isLambdaToBlockPointerConversion())
17207 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17208 else
17209 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17210 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17211 MarkVTableUsed(Loc, MethodDecl->getParent());
17212 }
17213
17214 if (Func->isDefaulted() && !Func->isDeleted()) {
17215 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17216 if (DCK != DefaultedComparisonKind::None)
17217 DefineDefaultedComparison(Loc, Func, DCK);
17218 }
17219
17220 // Implicit instantiation of function templates and member functions of
17221 // class templates.
17222 if (Func->isImplicitlyInstantiable()) {
17223 TemplateSpecializationKind TSK =
17224 Func->getTemplateSpecializationKindForInstantiation();
17225 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17226 bool FirstInstantiation = PointOfInstantiation.isInvalid();
17227 if (FirstInstantiation) {
17228 PointOfInstantiation = Loc;
17229 if (auto *MSI = Func->getMemberSpecializationInfo())
17230 MSI->setPointOfInstantiation(Loc);
17231 // FIXME: Notify listener.
17232 else
17233 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17234 } else if (TSK != TSK_ImplicitInstantiation) {
17235 // Use the point of use as the point of instantiation, instead of the
17236 // point of explicit instantiation (which we track as the actual point
17237 // of instantiation). This gives better backtraces in diagnostics.
17238 PointOfInstantiation = Loc;
17239 }
17240
17241 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17242 Func->isConstexpr()) {
17243 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17244 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17245 CodeSynthesisContexts.size())
17246 PendingLocalImplicitInstantiations.push_back(
17247 std::make_pair(Func, PointOfInstantiation));
17248 else if (Func->isConstexpr())
17249 // Do not defer instantiations of constexpr functions, to avoid the
17250 // expression evaluator needing to call back into Sema if it sees a
17251 // call to such a function.
17252 InstantiateFunctionDefinition(PointOfInstantiation, Func);
17253 else {
17254 Func->setInstantiationIsPending(true);
17255 PendingInstantiations.push_back(
17256 std::make_pair(Func, PointOfInstantiation));
17257 // Notify the consumer that a function was implicitly instantiated.
17258 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17259 }
17260 }
17261 } else {
17262 // Walk redefinitions, as some of them may be instantiable.
17263 for (auto i : Func->redecls()) {
17264 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17265 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17266 }
17267 }
17268 });
17269 }
17270
17271 // C++14 [except.spec]p17:
17272 // An exception-specification is considered to be needed when:
17273 // - the function is odr-used or, if it appears in an unevaluated operand,
17274 // would be odr-used if the expression were potentially-evaluated;
17275 //
17276 // Note, we do this even if MightBeOdrUse is false. That indicates that the
17277 // function is a pure virtual function we're calling, and in that case the
17278 // function was selected by overload resolution and we need to resolve its
17279 // exception specification for a different reason.
17280 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17281 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17282 ResolveExceptionSpec(Loc, FPT);
17283
17284 // If this is the first "real" use, act on that.
17285 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17286 // Keep track of used but undefined functions.
17287 if (!Func->isDefined()) {
17288 if (mightHaveNonExternalLinkage(Func))
17289 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17290 else if (Func->getMostRecentDecl()->isInlined() &&
17291 !LangOpts.GNUInline &&
17292 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17293 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17294 else if (isExternalWithNoLinkageType(Func))
17295 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17296 }
17297
17298 // Some x86 Windows calling conventions mangle the size of the parameter
17299 // pack into the name. Computing the size of the parameters requires the
17300 // parameter types to be complete. Check that now.
17301 if (funcHasParameterSizeMangling(*this, Func))
17302 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17303
17304 // In the MS C++ ABI, the compiler emits destructor variants where they are
17305 // used. If the destructor is used here but defined elsewhere, mark the
17306 // virtual base destructors referenced. If those virtual base destructors
17307 // are inline, this will ensure they are defined when emitting the complete
17308 // destructor variant. This checking may be redundant if the destructor is
17309 // provided later in this TU.
17310 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17311 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17312 CXXRecordDecl *Parent = Dtor->getParent();
17313 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17314 CheckCompleteDestructorVariant(Loc, Dtor);
17315 }
17316 }
17317
17318 Func->markUsed(Context);
17319 }
17320}
17321
17322/// Directly mark a variable odr-used. Given a choice, prefer to use
17323/// MarkVariableReferenced since it does additional checks and then
17324/// calls MarkVarDeclODRUsed.
17325/// If the variable must be captured:
17326/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17327/// - else capture it in the DeclContext that maps to the
17328/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17329static void
17330MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17331 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17332 // Keep track of used but undefined variables.
17333 // FIXME: We shouldn't suppress this warning for static data members.
17334 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17335 (!Var->isExternallyVisible() || Var->isInline() ||
17336 SemaRef.isExternalWithNoLinkageType(Var)) &&
17337 !(Var->isStaticDataMember() && Var->hasInit())) {
17338 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17339 if (old.isInvalid())
17340 old = Loc;
17341 }
17342 QualType CaptureType, DeclRefType;
17343 if (SemaRef.LangOpts.OpenMP)
17344 SemaRef.tryCaptureOpenMPLambdas(Var);
17345 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17346 /*EllipsisLoc*/ SourceLocation(),
17347 /*BuildAndDiagnose*/ true,
17348 CaptureType, DeclRefType,
17349 FunctionScopeIndexToStopAt);
17350
17351 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) {
17352 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
17353 auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
17354 auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
17355 if (VarTarget == Sema::CVT_Host &&
17356 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
17357 UserTarget == Sema::CFT_Global)) {
17358 // Diagnose ODR-use of host global variables in device functions.
17359 // Reference of device global variables in host functions is allowed
17360 // through shadow variables therefore it is not diagnosed.
17361 if (SemaRef.LangOpts.CUDAIsDevice) {
17362 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
17363 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
17364 SemaRef.targetDiag(Var->getLocation(),
17365 Var->getType().isConstQualified()
17366 ? diag::note_cuda_const_var_unpromoted
17367 : diag::note_cuda_host_var);
17368 }
17369 } else if (VarTarget == Sema::CVT_Device &&
17370 (UserTarget == Sema::CFT_Host ||
17371 UserTarget == Sema::CFT_HostDevice) &&
17372 !Var->hasExternalStorage()) {
17373 // Record a CUDA/HIP device side variable if it is ODR-used
17374 // by host code. This is done conservatively, when the variable is
17375 // referenced in any of the following contexts:
17376 // - a non-function context
17377 // - a host function
17378 // - a host device function
17379 // This makes the ODR-use of the device side variable by host code to
17380 // be visible in the device compilation for the compiler to be able to
17381 // emit template variables instantiated by host code only and to
17382 // externalize the static device side variable ODR-used by host code.
17383 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
17384 }
17385 }
17386
17387 Var->markUsed(SemaRef.Context);
17388}
17389
17390void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17391 SourceLocation Loc,
17392 unsigned CapturingScopeIndex) {
17393 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17394}
17395
17396static void
17397diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17398 ValueDecl *var, DeclContext *DC) {
17399 DeclContext *VarDC = var->getDeclContext();
17400
17401 // If the parameter still belongs to the translation unit, then
17402 // we're actually just using one parameter in the declaration of
17403 // the next.
17404 if (isa<ParmVarDecl>(var) &&
17405 isa<TranslationUnitDecl>(VarDC))
17406 return;
17407
17408 // For C code, don't diagnose about capture if we're not actually in code
17409 // right now; it's impossible to write a non-constant expression outside of
17410 // function context, so we'll get other (more useful) diagnostics later.
17411 //
17412 // For C++, things get a bit more nasty... it would be nice to suppress this
17413 // diagnostic for certain cases like using a local variable in an array bound
17414 // for a member of a local class, but the correct predicate is not obvious.
17415 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17416 return;
17417
17418 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17419 unsigned ContextKind = 3; // unknown
17420 if (isa<CXXMethodDecl>(VarDC) &&
17421 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17422 ContextKind = 2;
17423 } else if (isa<FunctionDecl>(VarDC)) {
17424 ContextKind = 0;
17425 } else if (isa<BlockDecl>(VarDC)) {
17426 ContextKind = 1;
17427 }
17428
17429 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17430 << var << ValueKind << ContextKind << VarDC;
17431 S.Diag(var->getLocation(), diag::note_entity_declared_at)
17432 << var;
17433
17434 // FIXME: Add additional diagnostic info about class etc. which prevents
17435 // capture.
17436}
17437
17438
17439static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17440 bool &SubCapturesAreNested,
17441 QualType &CaptureType,
17442 QualType &DeclRefType) {
17443 // Check whether we've already captured it.
17444 if (CSI->CaptureMap.count(Var)) {
17445 // If we found a capture, any subcaptures are nested.
17446 SubCapturesAreNested = true;
17447
17448 // Retrieve the capture type for this variable.
17449 CaptureType = CSI->getCapture(Var).getCaptureType();
17450
17451 // Compute the type of an expression that refers to this variable.
17452 DeclRefType = CaptureType.getNonReferenceType();
17453
17454 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17455 // are mutable in the sense that user can change their value - they are
17456 // private instances of the captured declarations.
17457 const Capture &Cap = CSI->getCapture(Var);
17458 if (Cap.isCopyCapture() &&
17459 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17460 !(isa<CapturedRegionScopeInfo>(CSI) &&
17461 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17462 DeclRefType.addConst();
17463 return true;
17464 }
17465 return false;
17466}
17467
17468// Only block literals, captured statements, and lambda expressions can
17469// capture; other scopes don't work.
17470static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17471 SourceLocation Loc,
17472 const bool Diagnose, Sema &S) {
17473 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17474 return getLambdaAwareParentOfDeclContext(DC);
17475 else if (Var->hasLocalStorage()) {
17476 if (Diagnose)
17477 diagnoseUncapturableValueReference(S, Loc, Var, DC);
17478 }
17479 return nullptr;
17480}
17481
17482// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17483// certain types of variables (unnamed, variably modified types etc.)
17484// so check for eligibility.
17485static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17486 SourceLocation Loc,
17487 const bool Diagnose, Sema &S) {
17488
17489 bool IsBlock = isa<BlockScopeInfo>(CSI);
17490 bool IsLambda = isa<LambdaScopeInfo>(CSI);
17491
17492 // Lambdas are not allowed to capture unnamed variables
17493 // (e.g. anonymous unions).
17494 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17495 // assuming that's the intent.
17496 if (IsLambda && !Var->getDeclName()) {
17497 if (Diagnose) {
17498 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17499 S.Diag(Var->getLocation(), diag::note_declared_at);
17500 }
17501 return false;
17502 }
17503
17504 // Prohibit variably-modified types in blocks; they're difficult to deal with.
17505 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17506 if (Diagnose) {
17507 S.Diag(Loc, diag::err_ref_vm_type);
17508 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17509 }
17510 return false;
17511 }
17512 // Prohibit structs with flexible array members too.
17513 // We cannot capture what is in the tail end of the struct.
17514 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17515 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17516 if (Diagnose) {
17517 if (IsBlock)
17518 S.Diag(Loc, diag::err_ref_flexarray_type);
17519 else
17520 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17521 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17522 }
17523 return false;
17524 }
17525 }
17526 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17527 // Lambdas and captured statements are not allowed to capture __block
17528 // variables; they don't support the expected semantics.
17529 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17530 if (Diagnose) {
17531 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17532 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17533 }
17534 return false;
17535 }
17536 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17537 if (S.getLangOpts().OpenCL && IsBlock &&
17538 Var->getType()->isBlockPointerType()) {
17539 if (Diagnose)
17540 S.Diag(Loc, diag::err_opencl_block_ref_block);
17541 return false;
17542 }
17543
17544 return true;
17545}
17546
17547// Returns true if the capture by block was successful.
17548static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17549 SourceLocation Loc,
17550 const bool BuildAndDiagnose,
17551 QualType &CaptureType,
17552 QualType &DeclRefType,
17553 const bool Nested,
17554 Sema &S, bool Invalid) {
17555 bool ByRef = false;
17556
17557 // Blocks are not allowed to capture arrays, excepting OpenCL.
17558 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17559 // (decayed to pointers).
17560 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17561 if (BuildAndDiagnose) {
17562 S.Diag(Loc, diag::err_ref_array_type);
17563 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17564 Invalid = true;
17565 } else {
17566 return false;
17567 }
17568 }
17569
17570 // Forbid the block-capture of autoreleasing variables.
17571 if (!Invalid &&
17572 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17573 if (BuildAndDiagnose) {
17574 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17575 << /*block*/ 0;
17576 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17577 Invalid = true;
17578 } else {
17579 return false;
17580 }
17581 }
17582
17583 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17584 if (const auto *PT = CaptureType->getAs<PointerType>()) {
17585 QualType PointeeTy = PT->getPointeeType();
17586
17587 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17588 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17589 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17590 if (BuildAndDiagnose) {
17591 SourceLocation VarLoc = Var->getLocation();
17592 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17593 S.Diag(VarLoc, diag::note_declare_parameter_strong);
17594 }
17595 }
17596 }
17597
17598 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17599 if (HasBlocksAttr || CaptureType->isReferenceType() ||
17600 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17601 // Block capture by reference does not change the capture or
17602 // declaration reference types.
17603 ByRef = true;
17604 } else {
17605 // Block capture by copy introduces 'const'.
17606 CaptureType = CaptureType.getNonReferenceType().withConst();
17607 DeclRefType = CaptureType;
17608 }
17609
17610 // Actually capture the variable.
17611 if (BuildAndDiagnose)
17612 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17613 CaptureType, Invalid);
17614
17615 return !Invalid;
17616}
17617
17618
17619/// Capture the given variable in the captured region.
17620static bool captureInCapturedRegion(
17621 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
17622 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
17623 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
17624 bool IsTopScope, Sema &S, bool Invalid) {
17625 // By default, capture variables by reference.
17626 bool ByRef = true;
17627 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17628 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17629 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17630 // Using an LValue reference type is consistent with Lambdas (see below).
17631 if (S.isOpenMPCapturedDecl(Var)) {
17632 bool HasConst = DeclRefType.isConstQualified();
17633 DeclRefType = DeclRefType.getUnqualifiedType();
17634 // Don't lose diagnostics about assignments to const.
17635 if (HasConst)
17636 DeclRefType.addConst();
17637 }
17638 // Do not capture firstprivates in tasks.
17639 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17640 OMPC_unknown)
17641 return true;
17642 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17643 RSI->OpenMPCaptureLevel);
17644 }
17645
17646 if (ByRef)
17647 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17648 else
17649 CaptureType = DeclRefType;
17650
17651 // Actually capture the variable.
17652 if (BuildAndDiagnose)
17653 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17654 Loc, SourceLocation(), CaptureType, Invalid);
17655
17656 return !Invalid;
17657}
17658
17659/// Capture the given variable in the lambda.
17660static bool captureInLambda(LambdaScopeInfo *LSI,
17661 VarDecl *Var,
17662 SourceLocation Loc,
17663 const bool BuildAndDiagnose,
17664 QualType &CaptureType,
17665 QualType &DeclRefType,
17666 const bool RefersToCapturedVariable,
17667 const Sema::TryCaptureKind Kind,
17668 SourceLocation EllipsisLoc,
17669 const bool IsTopScope,
17670 Sema &S, bool Invalid) {
17671 // Determine whether we are capturing by reference or by value.
17672 bool ByRef = false;
17673 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17674 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17675 } else {
17676 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17677 }
17678
17679 // Compute the type of the field that will capture this variable.
17680 if (ByRef) {
17681 // C++11 [expr.prim.lambda]p15:
17682 // An entity is captured by reference if it is implicitly or
17683 // explicitly captured but not captured by copy. It is
17684 // unspecified whether additional unnamed non-static data
17685 // members are declared in the closure type for entities
17686 // captured by reference.
17687 //
17688 // FIXME: It is not clear whether we want to build an lvalue reference
17689 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17690 // to do the former, while EDG does the latter. Core issue 1249 will
17691 // clarify, but for now we follow GCC because it's a more permissive and
17692 // easily defensible position.
17693 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17694 } else {
17695 // C++11 [expr.prim.lambda]p14:
17696 // For each entity captured by copy, an unnamed non-static
17697 // data member is declared in the closure type. The
17698 // declaration order of these members is unspecified. The type
17699 // of such a data member is the type of the corresponding
17700 // captured entity if the entity is not a reference to an
17701 // object, or the referenced type otherwise. [Note: If the
17702 // captured entity is a reference to a function, the
17703 // corresponding data member is also a reference to a
17704 // function. - end note ]
17705 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17706 if (!RefType->getPointeeType()->isFunctionType())
17707 CaptureType = RefType->getPointeeType();
17708 }
17709
17710 // Forbid the lambda copy-capture of autoreleasing variables.
17711 if (!Invalid &&
17712 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17713 if (BuildAndDiagnose) {
17714 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17715 S.Diag(Var->getLocation(), diag::note_previous_decl)
17716 << Var->getDeclName();
17717 Invalid = true;
17718 } else {
17719 return false;
17720 }
17721 }
17722
17723 // Make sure that by-copy captures are of a complete and non-abstract type.
17724 if (!Invalid && BuildAndDiagnose) {
17725 if (!CaptureType->isDependentType() &&
17726 S.RequireCompleteSizedType(
17727 Loc, CaptureType,
17728 diag::err_capture_of_incomplete_or_sizeless_type,
17729 Var->getDeclName()))
17730 Invalid = true;
17731 else if (S.RequireNonAbstractType(Loc, CaptureType,
17732 diag::err_capture_of_abstract_type))
17733 Invalid = true;
17734 }
17735 }
17736
17737 // Compute the type of a reference to this captured variable.
17738 if (ByRef)
17739 DeclRefType = CaptureType.getNonReferenceType();
17740 else {
17741 // C++ [expr.prim.lambda]p5:
17742 // The closure type for a lambda-expression has a public inline
17743 // function call operator [...]. This function call operator is
17744 // declared const (9.3.1) if and only if the lambda-expression's
17745 // parameter-declaration-clause is not followed by mutable.
17746 DeclRefType = CaptureType.getNonReferenceType();
17747 if (!LSI->Mutable && !CaptureType->isReferenceType())
17748 DeclRefType.addConst();
17749 }
17750
17751 // Add the capture.
17752 if (BuildAndDiagnose)
17753 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17754 Loc, EllipsisLoc, CaptureType, Invalid);
17755
17756 return !Invalid;
17757}
17758
17759static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
17760 // Offer a Copy fix even if the type is dependent.
17761 if (Var->getType()->isDependentType())
17762 return true;
17763 QualType T = Var->getType().getNonReferenceType();
17764 if (T.isTriviallyCopyableType(Context))
17765 return true;
17766 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
17767
17768 if (!(RD = RD->getDefinition()))
17769 return false;
17770 if (RD->hasSimpleCopyConstructor())
17771 return true;
17772 if (RD->hasUserDeclaredCopyConstructor())
17773 for (CXXConstructorDecl *Ctor : RD->ctors())
17774 if (Ctor->isCopyConstructor())
17775 return !Ctor->isDeleted();
17776 }
17777 return false;
17778}
17779
17780/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
17781/// default capture. Fixes may be omitted if they aren't allowed by the
17782/// standard, for example we can't emit a default copy capture fix-it if we
17783/// already explicitly copy capture capture another variable.
17784static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
17785 VarDecl *Var) {
17786 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None)(static_cast<void> (0));
17787 // Don't offer Capture by copy of default capture by copy fixes if Var is
17788 // known not to be copy constructible.
17789 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
17790
17791 SmallString<32> FixBuffer;
17792 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
17793 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
17794 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
17795 if (ShouldOfferCopyFix) {
17796 // Offer fixes to insert an explicit capture for the variable.
17797 // [] -> [VarName]
17798 // [OtherCapture] -> [OtherCapture, VarName]
17799 FixBuffer.assign({Separator, Var->getName()});
17800 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17801 << Var << /*value*/ 0
17802 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17803 }
17804 // As above but capture by reference.
17805 FixBuffer.assign({Separator, "&", Var->getName()});
17806 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17807 << Var << /*reference*/ 1
17808 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17809 }
17810
17811 // Only try to offer default capture if there are no captures excluding this
17812 // and init captures.
17813 // [this]: OK.
17814 // [X = Y]: OK.
17815 // [&A, &B]: Don't offer.
17816 // [A, B]: Don't offer.
17817 if (llvm::any_of(LSI->Captures, [](Capture &C) {
17818 return !C.isThisCapture() && !C.isInitCapture();
17819 }))
17820 return;
17821
17822 // The default capture specifiers, '=' or '&', must appear first in the
17823 // capture body.
17824 SourceLocation DefaultInsertLoc =
17825 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
17826
17827 if (ShouldOfferCopyFix) {
17828 bool CanDefaultCopyCapture = true;
17829 // [=, *this] OK since c++17
17830 // [=, this] OK since c++20
17831 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
17832 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
17833 ? LSI->getCXXThisCapture().isCopyCapture()
17834 : false;
17835 // We can't use default capture by copy if any captures already specified
17836 // capture by copy.
17837 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
17838 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
17839 })) {
17840 FixBuffer.assign({"=", Separator});
17841 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17842 << /*value*/ 0
17843 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17844 }
17845 }
17846
17847 // We can't use default capture by reference if any captures already specified
17848 // capture by reference.
17849 if (llvm::none_of(LSI->Captures, [](Capture &C) {
17850 return !C.isInitCapture() && C.isReferenceCapture() &&
17851 !C.isThisCapture();
17852 })) {
17853 FixBuffer.assign({"&", Separator});
17854 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17855 << /*reference*/ 1
17856 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17857 }
17858}
17859
17860bool Sema::tryCaptureVariable(
17861 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17862 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17863 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17864 // An init-capture is notionally from the context surrounding its
17865 // declaration, but its parent DC is the lambda class.
17866 DeclContext *VarDC = Var->getDeclContext();
17867 if (Var->isInitCapture())
17868 VarDC = VarDC->getParent();
17869
17870 DeclContext *DC = CurContext;
17871 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17872 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17873 // We need to sync up the Declaration Context with the
17874 // FunctionScopeIndexToStopAt
17875 if (FunctionScopeIndexToStopAt) {
17876 unsigned FSIndex = FunctionScopes.size() - 1;
17877 while (FSIndex != MaxFunctionScopesIndex) {
17878 DC = getLambdaAwareParentOfDeclContext(DC);
17879 --FSIndex;
17880 }
17881 }
17882
17883
17884 // If the variable is declared in the current context, there is no need to
17885 // capture it.
17886 if (VarDC == DC) return true;
17887
17888 // Capture global variables if it is required to use private copy of this
17889 // variable.
17890 bool IsGlobal = !Var->hasLocalStorage();
17891 if (IsGlobal &&
17892 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17893 MaxFunctionScopesIndex)))
17894 return true;
17895 Var = Var->getCanonicalDecl();
17896
17897 // Walk up the stack to determine whether we can capture the variable,
17898 // performing the "simple" checks that don't depend on type. We stop when
17899 // we've either hit the declared scope of the variable or find an existing
17900 // capture of that variable. We start from the innermost capturing-entity
17901 // (the DC) and ensure that all intervening capturing-entities
17902 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17903 // declcontext can either capture the variable or have already captured
17904 // the variable.
17905 CaptureType = Var->getType();
17906 DeclRefType = CaptureType.getNonReferenceType();
17907 bool Nested = false;
17908 bool Explicit = (Kind != TryCapture_Implicit);
17909 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17910 do {
17911 // Only block literals, captured statements, and lambda expressions can
17912 // capture; other scopes don't work.
17913 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17914 ExprLoc,
17915 BuildAndDiagnose,
17916 *this);
17917 // We need to check for the parent *first* because, if we *have*
17918 // private-captured a global variable, we need to recursively capture it in
17919 // intermediate blocks, lambdas, etc.
17920 if (!ParentDC) {
17921 if (IsGlobal) {
17922 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17923 break;
17924 }
17925 return true;
17926 }
17927
17928 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
17929 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17930
17931
17932 // Check whether we've already captured it.
17933 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17934 DeclRefType)) {
17935 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17936 break;
17937 }
17938 // If we are instantiating a generic lambda call operator body,
17939 // we do not want to capture new variables. What was captured
17940 // during either a lambdas transformation or initial parsing
17941 // should be used.
17942 if (isGenericLambdaCallOperatorSpecialization(DC)) {
17943 if (BuildAndDiagnose) {
17944 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17945 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17946 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17947 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17948 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17949 buildLambdaCaptureFixit(*this, LSI, Var);
17950 } else
17951 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17952 }
17953 return true;
17954 }
17955
17956 // Try to capture variable-length arrays types.
17957 if (Var->getType()->isVariablyModifiedType()) {
17958 // We're going to walk down into the type and look for VLA
17959 // expressions.
17960 QualType QTy = Var->getType();
17961 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17962 QTy = PVD->getOriginalType();
17963 captureVariablyModifiedType(Context, QTy, CSI);
17964 }
17965
17966 if (getLangOpts().OpenMP) {
17967 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17968 // OpenMP private variables should not be captured in outer scope, so
17969 // just break here. Similarly, global variables that are captured in a
17970 // target region should not be captured outside the scope of the region.
17971 if (RSI->CapRegionKind == CR_OpenMP) {
17972 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17973 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17974 // If the variable is private (i.e. not captured) and has variably
17975 // modified type, we still need to capture the type for correct
17976 // codegen in all regions, associated with the construct. Currently,
17977 // it is captured in the innermost captured region only.
17978 if (IsOpenMPPrivateDecl != OMPC_unknown &&
17979 Var->getType()->isVariablyModifiedType()) {
17980 QualType QTy = Var->getType();
17981 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17982 QTy = PVD->getOriginalType();
17983 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17984 I < E; ++I) {
17985 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17986 FunctionScopes[FunctionScopesIndex - I]);
17987 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&(static_cast<void> (0))
17988 "Wrong number of captured regions associated with the "(static_cast<void> (0))
17989 "OpenMP construct.")(static_cast<void> (0));
17990 captureVariablyModifiedType(Context, QTy, OuterRSI);
17991 }
17992 }
17993 bool IsTargetCap =
17994 IsOpenMPPrivateDecl != OMPC_private &&
17995 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17996 RSI->OpenMPCaptureLevel);
17997 // Do not capture global if it is not privatized in outer regions.
17998 bool IsGlobalCap =
17999 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18000 RSI->OpenMPCaptureLevel);
18001
18002 // When we detect target captures we are looking from inside the
18003 // target region, therefore we need to propagate the capture from the
18004 // enclosing region. Therefore, the capture is not initially nested.
18005 if (IsTargetCap)
18006 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18007
18008 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18009 (IsGlobal && !IsGlobalCap)) {
18010 Nested = !IsTargetCap;
18011 bool HasConst = DeclRefType.isConstQualified();
18012 DeclRefType = DeclRefType.getUnqualifiedType();
18013 // Don't lose diagnostics about assignments to const.
18014 if (HasConst)
18015 DeclRefType.addConst();
18016 CaptureType = Context.getLValueReferenceType(DeclRefType);
18017 break;
18018 }
18019 }
18020 }
18021 }
18022 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18023 // No capture-default, and this is not an explicit capture
18024 // so cannot capture this variable.
18025 if (BuildAndDiagnose) {
18026 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18027 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18028 auto *LSI = cast<LambdaScopeInfo>(CSI);
18029 if (LSI->Lambda) {
18030 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18031 buildLambdaCaptureFixit(*this, LSI, Var);
18032 }
18033 // FIXME: If we error out because an outer lambda can not implicitly
18034 // capture a variable that an inner lambda explicitly captures, we
18035 // should have the inner lambda do the explicit capture - because
18036 // it makes for cleaner diagnostics later. This would purely be done
18037 // so that the diagnostic does not misleadingly claim that a variable
18038 // can not be captured by a lambda implicitly even though it is captured
18039 // explicitly. Suggestion:
18040 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18041 // at the function head
18042 // - cache the StartingDeclContext - this must be a lambda
18043 // - captureInLambda in the innermost lambda the variable.
18044 }
18045 return true;
18046 }
18047
18048 FunctionScopesIndex--;
18049 DC = ParentDC;
18050 Explicit = false;
18051 } while (!VarDC->Equals(DC));
18052
18053 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18054 // computing the type of the capture at each step, checking type-specific
18055 // requirements, and adding captures if requested.
18056 // If the variable had already been captured previously, we start capturing
18057 // at the lambda nested within that one.
18058 bool Invalid = false;
18059 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18060 ++I) {
18061 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18062
18063 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18064 // certain types of variables (unnamed, variably modified types etc.)
18065 // so check for eligibility.
18066 if (!Invalid)
18067 Invalid =
18068 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18069
18070 // After encountering an error, if we're actually supposed to capture, keep
18071 // capturing in nested contexts to suppress any follow-on diagnostics.
18072 if (Invalid && !BuildAndDiagnose)
18073 return true;
18074
18075 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18076 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18077 DeclRefType, Nested, *this, Invalid);
18078 Nested = true;
18079 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18080 Invalid = !captureInCapturedRegion(
18081 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18082 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18083 Nested = true;
18084 } else {
18085 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18086 Invalid =
18087 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18088 DeclRefType, Nested, Kind, EllipsisLoc,
18089 /*IsTopScope*/ I == N - 1, *this, Invalid);
18090 Nested = true;
18091 }
18092
18093 if (Invalid && !BuildAndDiagnose)
18094 return true;
18095 }
18096 return Invalid;
18097}
18098
18099bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18100 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18101 QualType CaptureType;
18102 QualType DeclRefType;
18103 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18104 /*BuildAndDiagnose=*/true, CaptureType,
18105 DeclRefType, nullptr);
18106}
18107
18108bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18109 QualType CaptureType;
18110 QualType DeclRefType;
18111 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18112 /*BuildAndDiagnose=*/false, CaptureType,
18113 DeclRefType, nullptr);
18114}
18115
18116QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18117 QualType CaptureType;
18118 QualType DeclRefType;
18119
18120 // Determine whether we can capture this variable.
18121 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18122 /*BuildAndDiagnose=*/false, CaptureType,
18123 DeclRefType, nullptr))
18124 return QualType();
18125
18126 return DeclRefType;
18127}
18128
18129namespace {
18130// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18131// The produced TemplateArgumentListInfo* points to data stored within this
18132// object, so should only be used in contexts where the pointer will not be
18133// used after the CopiedTemplateArgs object is destroyed.
18134class CopiedTemplateArgs {
18135 bool HasArgs;
18136 TemplateArgumentListInfo TemplateArgStorage;
18137public:
18138 template<typename RefExpr>
18139 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18140 if (HasArgs)
18141 E->copyTemplateArgumentsInto(TemplateArgStorage);
18142 }
18143 operator TemplateArgumentListInfo*()
18144#ifdef __has_cpp_attribute
18145#if0 __has_cpp_attribute(clang::lifetimebound)1
18146 [[clang::lifetimebound]]
18147#endif
18148#endif
18149 {
18150 return HasArgs ? &TemplateArgStorage : nullptr;
18151 }
18152};
18153}
18154
18155/// Walk the set of potential results of an expression and mark them all as
18156/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18157///
18158/// \return A new expression if we found any potential results, ExprEmpty() if
18159/// not, and ExprError() if we diagnosed an error.
18160static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18161 NonOdrUseReason NOUR) {
18162 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18163 // an object that satisfies the requirements for appearing in a
18164 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18165 // is immediately applied." This function handles the lvalue-to-rvalue
18166 // conversion part.
18167 //
18168 // If we encounter a node that claims to be an odr-use but shouldn't be, we
18169 // transform it into the relevant kind of non-odr-use node and rebuild the
18170 // tree of nodes leading to it.
18171 //
18172 // This is a mini-TreeTransform that only transforms a restricted subset of
18173 // nodes (and only certain operands of them).
18174
18175 // Rebuild a subexpression.
18176 auto Rebuild = [&](Expr *Sub) {
18177 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18178 };
18179
18180 // Check whether a potential result satisfies the requirements of NOUR.
18181 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18182 // Any entity other than a VarDecl is always odr-used whenever it's named
18183 // in a potentially-evaluated expression.
18184 auto *VD = dyn_cast<VarDecl>(D);
18185 if (!VD)
18186 return true;
18187
18188 // C++2a [basic.def.odr]p4:
18189 // A variable x whose name appears as a potentially-evalauted expression
18190 // e is odr-used by e unless
18191 // -- x is a reference that is usable in constant expressions, or
18192 // -- x is a variable of non-reference type that is usable in constant
18193 // expressions and has no mutable subobjects, and e is an element of
18194 // the set of potential results of an expression of
18195 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
18196 // conversion is applied, or
18197 // -- x is a variable of non-reference type, and e is an element of the
18198 // set of potential results of a discarded-value expression to which
18199 // the lvalue-to-rvalue conversion is not applied
18200 //
18201 // We check the first bullet and the "potentially-evaluated" condition in
18202 // BuildDeclRefExpr. We check the type requirements in the second bullet
18203 // in CheckLValueToRValueConversionOperand below.
18204 switch (NOUR) {
18205 case NOUR_None:
18206 case NOUR_Unevaluated:
18207 llvm_unreachable("unexpected non-odr-use-reason")__builtin_unreachable();
18208
18209 case NOUR_Constant:
18210 // Constant references were handled when they were built.
18211 if (VD->getType()->isReferenceType())
18212 return true;
18213 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18214 if (RD->hasMutableFields())
18215 return true;
18216 if (!VD->isUsableInConstantExpressions(S.Context))
18217 return true;
18218 break;
18219
18220 case NOUR_Discarded:
18221 if (VD->getType()->isReferenceType())
18222 return true;
18223 break;
18224 }
18225 return false;
18226 };
18227
18228 // Mark that this expression does not constitute an odr-use.
18229 auto MarkNotOdrUsed = [&] {
18230 S.MaybeODRUseExprs.remove(E);
18231 if (LambdaScopeInfo *LSI = S.getCurLambda())
18232 LSI->markVariableExprAsNonODRUsed(E);
18233 };
18234
18235 // C++2a [basic.def.odr]p2:
18236 // The set of potential results of an expression e is defined as follows:
18237 switch (E->getStmtClass()) {
18238 // -- If e is an id-expression, ...
18239 case Expr::DeclRefExprClass: {
18240 auto *DRE = cast<DeclRefExpr>(E);
18241 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18242 break;
18243
18244 // Rebuild as a non-odr-use DeclRefExpr.
18245 MarkNotOdrUsed();
18246 return DeclRefExpr::Create(
18247 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18248 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18249 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18250 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18251 }
18252
18253 case Expr::FunctionParmPackExprClass: {
18254 auto *FPPE = cast<FunctionParmPackExpr>(E);
18255 // If any of the declarations in the pack is odr-used, then the expression
18256 // as a whole constitutes an odr-use.
18257 for (VarDecl *D : *FPPE)
18258 if (IsPotentialResultOdrUsed(D))
18259 return ExprEmpty();
18260
18261 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18262 // nothing cares about whether we marked this as an odr-use, but it might
18263 // be useful for non-compiler tools.
18264 MarkNotOdrUsed();
18265 break;
18266 }
18267
18268 // -- If e is a subscripting operation with an array operand...
18269 case Expr::ArraySubscriptExprClass: {
18270 auto *ASE = cast<ArraySubscriptExpr>(E);
18271 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18272 if (!OldBase->getType()->isArrayType())
18273 break;
18274 ExprResult Base = Rebuild(OldBase);
18275 if (!Base.isUsable())
18276 return Base;
18277 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18278 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18279 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18280 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
18281 ASE->getRBracketLoc());
18282 }
18283
18284 case Expr::MemberExprClass: {
18285 auto *ME = cast<MemberExpr>(E);
18286 // -- If e is a class member access expression [...] naming a non-static
18287 // data member...
18288 if (isa<FieldDecl>(ME->getMemberDecl())) {
18289 ExprResult Base = Rebuild(ME->getBase());
18290 if (!Base.isUsable())
18291 return Base;
18292 return MemberExpr::Create(
18293 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
18294 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
18295 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
18296 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
18297 ME->getObjectKind(), ME->isNonOdrUse());
18298 }
18299
18300 if (ME->getMemberDecl()->isCXXInstanceMember())
18301 break;
18302
18303 // -- If e is a class member access expression naming a static data member,
18304 // ...
18305 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
18306 break;
18307
18308 // Rebuild as a non-odr-use MemberExpr.
18309 MarkNotOdrUsed();
18310 return MemberExpr::Create(
18311 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
18312 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
18313 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
18314 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
18315 }
18316
18317 case Expr::BinaryOperatorClass: {
18318 auto *BO = cast<BinaryOperator>(E);
18319 Expr *LHS = BO->getLHS();
18320 Expr *RHS = BO->getRHS();
18321 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
18322 if (BO->getOpcode() == BO_PtrMemD) {
18323 ExprResult Sub = Rebuild(LHS);
18324 if (!Sub.isUsable())
18325 return Sub;
18326 LHS = Sub.get();
18327 // -- If e is a comma expression, ...
18328 } else if (BO->getOpcode() == BO_Comma) {
18329 ExprResult Sub = Rebuild(RHS);
18330 if (!Sub.isUsable())
18331 return Sub;
18332 RHS = Sub.get();
18333 } else {
18334 break;
18335 }
18336 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18337 LHS, RHS);
18338 }
18339
18340 // -- If e has the form (e1)...
18341 case Expr::ParenExprClass: {
18342 auto *PE = cast<ParenExpr>(E);
18343 ExprResult Sub = Rebuild(PE->getSubExpr());
18344 if (!Sub.isUsable())
18345 return Sub;
18346 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18347 }
18348
18349 // -- If e is a glvalue conditional expression, ...
18350 // We don't apply this to a binary conditional operator. FIXME: Should we?
18351 case Expr::ConditionalOperatorClass: {
18352 auto *CO = cast<ConditionalOperator>(E);
18353 ExprResult LHS = Rebuild(CO->getLHS());
18354 if (LHS.isInvalid())
18355 return ExprError();
18356 ExprResult RHS = Rebuild(CO->getRHS());
18357 if (RHS.isInvalid())
18358 return ExprError();
18359 if (!LHS.isUsable() && !RHS.isUsable())
18360 return ExprEmpty();
18361 if (!LHS.isUsable())
18362 LHS = CO->getLHS();
18363 if (!RHS.isUsable())
18364 RHS = CO->getRHS();
18365 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18366 CO->getCond(), LHS.get(), RHS.get());
18367 }
18368
18369 // [Clang extension]
18370 // -- If e has the form __extension__ e1...
18371 case Expr::UnaryOperatorClass: {
18372 auto *UO = cast<UnaryOperator>(E);
18373 if (UO->getOpcode() != UO_Extension)
18374 break;
18375 ExprResult Sub = Rebuild(UO->getSubExpr());
18376 if (!Sub.isUsable())
18377 return Sub;
18378 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18379 Sub.get());
18380 }
18381
18382 // [Clang extension]
18383 // -- If e has the form _Generic(...), the set of potential results is the
18384 // union of the sets of potential results of the associated expressions.
18385 case Expr::GenericSelectionExprClass: {
18386 auto *GSE = cast<GenericSelectionExpr>(E);
18387
18388 SmallVector<Expr *, 4> AssocExprs;
18389 bool AnyChanged = false;
18390 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18391 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18392 if (AssocExpr.isInvalid())
18393 return ExprError();
18394 if (AssocExpr.isUsable()) {
18395 AssocExprs.push_back(AssocExpr.get());
18396 AnyChanged = true;
18397 } else {
18398 AssocExprs.push_back(OrigAssocExpr);
18399 }
18400 }
18401
18402 return AnyChanged ? S.CreateGenericSelectionExpr(
18403 GSE->getGenericLoc(), GSE->getDefaultLoc(),
18404 GSE->getRParenLoc(), GSE->getControllingExpr(),
18405 GSE->getAssocTypeSourceInfos(), AssocExprs)
18406 : ExprEmpty();
18407 }
18408
18409 // [Clang extension]
18410 // -- If e has the form __builtin_choose_expr(...), the set of potential
18411 // results is the union of the sets of potential results of the
18412 // second and third subexpressions.
18413 case Expr::ChooseExprClass: {
18414 auto *CE = cast<ChooseExpr>(E);
18415
18416 ExprResult LHS = Rebuild(CE->getLHS());
18417 if (LHS.isInvalid())
18418 return ExprError();
18419
18420 ExprResult RHS = Rebuild(CE->getLHS());
18421 if (RHS.isInvalid())
18422 return ExprError();
18423
18424 if (!LHS.get() && !RHS.get())
18425 return ExprEmpty();
18426 if (!LHS.isUsable())
18427 LHS = CE->getLHS();
18428 if (!RHS.isUsable())
18429 RHS = CE->getRHS();
18430
18431 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18432 RHS.get(), CE->getRParenLoc());
18433 }
18434
18435 // Step through non-syntactic nodes.
18436 case Expr::ConstantExprClass: {
18437 auto *CE = cast<ConstantExpr>(E);
18438 ExprResult Sub = Rebuild(CE->getSubExpr());
18439 if (!Sub.isUsable())
18440 return Sub;
18441 return ConstantExpr::Create(S.Context, Sub.get());
18442 }
18443
18444 // We could mostly rely on the recursive rebuilding to rebuild implicit
18445 // casts, but not at the top level, so rebuild them here.
18446 case Expr::ImplicitCastExprClass: {
18447 auto *ICE = cast<ImplicitCastExpr>(E);
18448 // Only step through the narrow set of cast kinds we expect to encounter.
18449 // Anything else suggests we've left the region in which potential results
18450 // can be found.
18451 switch (ICE->getCastKind()) {
18452 case CK_NoOp:
18453 case CK_DerivedToBase:
18454 case CK_UncheckedDerivedToBase: {
18455 ExprResult Sub = Rebuild(ICE->getSubExpr());
18456 if (!Sub.isUsable())
18457 return Sub;
18458 CXXCastPath Path(ICE->path());
18459 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18460 ICE->getValueKind(), &Path);
18461 }
18462
18463 default:
18464 break;
18465 }
18466 break;
18467 }
18468
18469 default:
18470 break;
18471 }
18472
18473 // Can't traverse through this node. Nothing to do.
18474 return ExprEmpty();
18475}
18476
18477ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18478 // Check whether the operand is or contains an object of non-trivial C union
18479 // type.
18480 if (E->getType().isVolatileQualified() &&
18481 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18482 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18483 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18484 Sema::NTCUC_LValueToRValueVolatile,
18485 NTCUK_Destruct|NTCUK_Copy);
18486
18487 // C++2a [basic.def.odr]p4:
18488 // [...] an expression of non-volatile-qualified non-class type to which
18489 // the lvalue-to-rvalue conversion is applied [...]
18490 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18491 return E;
18492
18493 ExprResult Result =
18494 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18495 if (Result.isInvalid())
18496 return ExprError();
18497 return Result.get() ? Result : E;
18498}
18499
18500ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18501 Res = CorrectDelayedTyposInExpr(Res);
18502
18503 if (!Res.isUsable())
18504 return Res;
18505
18506 // If a constant-expression is a reference to a variable where we delay
18507 // deciding whether it is an odr-use, just assume we will apply the
18508 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
18509 // (a non-type template argument), we have special handling anyway.
18510 return CheckLValueToRValueConversionOperand(Res.get());
18511}
18512
18513void Sema::CleanupVarDeclMarking() {
18514 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18515 // call.
18516 MaybeODRUseExprSet LocalMaybeODRUseExprs;
18517 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18518
18519 for (Expr *E : LocalMaybeODRUseExprs) {
18520 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18521 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18522 DRE->getLocation(), *this);
18523 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18524 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18525 *this);
18526 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18527 for (VarDecl *VD : *FP)
18528 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18529 } else {
18530 llvm_unreachable("Unexpected expression")__builtin_unreachable();
18531 }
18532 }
18533
18534 assert(MaybeODRUseExprs.empty() &&(static_cast<void> (0))
18535 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")(static_cast<void> (0));
18536}
18537
18538static void DoMarkVarDeclReferenced(
18539 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
18540 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18541 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(static_cast<void> (0))
18542 isa<FunctionParmPackExpr>(E)) &&(static_cast<void> (0))
18543 "Invalid Expr argument to DoMarkVarDeclReferenced")(static_cast<void> (0));
18544 Var->setReferenced();
18545
18546 if (Var->isInvalidDecl())
18547 return;
18548
18549 auto *MSI = Var->getMemberSpecializationInfo();
18550 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18551 : Var->getTemplateSpecializationKind();
18552
18553 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18554 bool UsableInConstantExpr =
18555 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18556
18557 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
18558 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
18559 }
18560
18561 // C++20 [expr.const]p12:
18562 // A variable [...] is needed for constant evaluation if it is [...] a
18563 // variable whose name appears as a potentially constant evaluated
18564 // expression that is either a contexpr variable or is of non-volatile
18565 // const-qualified integral type or of reference type
18566 bool NeededForConstantEvaluation =
18567 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18568
18569 bool NeedDefinition =
18570 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18571
18572 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&(static_cast<void> (0))
18573 "Can't instantiate a partial template specialization.")(static_cast<void> (0));
18574
18575 // If this might be a member specialization of a static data member, check
18576 // the specialization is visible. We already did the checks for variable
18577 // template specializations when we created them.
18578 if (NeedDefinition && TSK != TSK_Undeclared &&
18579 !isa<VarTemplateSpecializationDecl>(Var))
18580 SemaRef.checkSpecializationVisibility(Loc, Var);
18581
18582 // Perform implicit instantiation of static data members, static data member
18583 // templates of class templates, and variable template specializations. Delay
18584 // instantiations of variable templates, except for those that could be used
18585 // in a constant expression.
18586 if (NeedDefinition && isTemplateInstantiation(TSK)) {
18587 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18588 // instantiation declaration if a variable is usable in a constant
18589 // expression (among other cases).
18590 bool TryInstantiating =
18591 TSK == TSK_ImplicitInstantiation ||
18592 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18593
18594 if (TryInstantiating) {
18595 SourceLocation PointOfInstantiation =
18596 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18597 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18598 if (FirstInstantiation) {
18599 PointOfInstantiation = Loc;
18600 if (MSI)
18601 MSI->setPointOfInstantiation(PointOfInstantiation);
18602 // FIXME: Notify listener.
18603 else
18604 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18605 }
18606
18607 if (UsableInConstantExpr) {
18608 // Do not defer instantiations of variables that could be used in a
18609 // constant expression.
18610 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18611 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18612 });
18613
18614 // Re-set the member to trigger a recomputation of the dependence bits
18615 // for the expression.
18616 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18617 DRE->setDecl(DRE->getDecl());
18618 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18619 ME->setMemberDecl(ME->getMemberDecl());
18620 } else if (FirstInstantiation ||
18621 isa<VarTemplateSpecializationDecl>(Var)) {
18622 // FIXME: For a specialization of a variable template, we don't
18623 // distinguish between "declaration and type implicitly instantiated"
18624 // and "implicit instantiation of definition requested", so we have
18625 // no direct way to avoid enqueueing the pending instantiation
18626 // multiple times.
18627 SemaRef.PendingInstantiations
18628 .push_back(std::make_pair(Var, PointOfInstantiation));
18629 }
18630 }
18631 }
18632
18633 // C++2a [basic.def.odr]p4:
18634 // A variable x whose name appears as a potentially-evaluated expression e
18635 // is odr-used by e unless
18636 // -- x is a reference that is usable in constant expressions
18637 // -- x is a variable of non-reference type that is usable in constant
18638 // expressions and has no mutable subobjects [FIXME], and e is an
18639 // element of the set of potential results of an expression of
18640 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
18641 // conversion is applied
18642 // -- x is a variable of non-reference type, and e is an element of the set
18643 // of potential results of a discarded-value expression to which the
18644 // lvalue-to-rvalue conversion is not applied [FIXME]
18645 //
18646 // We check the first part of the second bullet here, and
18647 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18648 // FIXME: To get the third bullet right, we need to delay this even for
18649 // variables that are not usable in constant expressions.
18650
18651 // If we already know this isn't an odr-use, there's nothing more to do.
18652 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18653 if (DRE->isNonOdrUse())
18654 return;
18655 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18656 if (ME->isNonOdrUse())
18657 return;
18658
18659 switch (OdrUse) {
18660 case OdrUseContext::None:
18661 assert((!E || isa<FunctionParmPackExpr>(E)) &&(static_cast<void> (0))
18662 "missing non-odr-use marking for unevaluated decl ref")(static_cast<void> (0));
18663 break;
18664
18665 case OdrUseContext::FormallyOdrUsed:
18666 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18667 // behavior.
18668 break;
18669
18670 case OdrUseContext::Used:
18671 // If we might later find that this expression isn't actually an odr-use,
18672 // delay the marking.
18673 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18674 SemaRef.MaybeODRUseExprs.insert(E);
18675 else
18676 MarkVarDeclODRUsed(Var, Loc, SemaRef);
18677 break;
18678
18679 case OdrUseContext::Dependent:
18680 // If this is a dependent context, we don't need to mark variables as
18681 // odr-used, but we may still need to track them for lambda capture.
18682 // FIXME: Do we also need to do this inside dependent typeid expressions
18683 // (which are modeled as unevaluated at this point)?
18684 const bool RefersToEnclosingScope =
18685 (SemaRef.CurContext != Var->getDeclContext() &&
18686 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18687 if (RefersToEnclosingScope) {
18688 LambdaScopeInfo *const LSI =
18689 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18690 if (LSI && (!LSI->CallOperator ||
18691 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18692 // If a variable could potentially be odr-used, defer marking it so
18693 // until we finish analyzing the full expression for any
18694 // lvalue-to-rvalue
18695 // or discarded value conversions that would obviate odr-use.
18696 // Add it to the list of potential captures that will be analyzed
18697 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18698 // unless the variable is a reference that was initialized by a constant
18699 // expression (this will never need to be captured or odr-used).
18700 //
18701 // FIXME: We can simplify this a lot after implementing P0588R1.
18702 assert(E && "Capture variable should be used in an expression.")(static_cast<void> (0));
18703 if (!Var->getType()->isReferenceType() ||
18704 !Var->isUsableInConstantExpressions(SemaRef.Context))
18705 LSI->addPotentialCapture(E->IgnoreParens());
18706 }
18707 }
18708 break;
18709 }
18710}
18711
18712/// Mark a variable referenced, and check whether it is odr-used
18713/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
18714/// used directly for normal expressions referring to VarDecl.
18715void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18716 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
18717}
18718
18719static void
18720MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
18721 bool MightBeOdrUse,
18722 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18723 if (SemaRef.isInOpenMPDeclareTargetContext())
18724 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18725
18726 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18727 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
18728 return;
18729 }
18730
18731 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18732
18733 // If this is a call to a method via a cast, also mark the method in the
18734 // derived class used in case codegen can devirtualize the call.
18735 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18736 if (!ME)
18737 return;
18738 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18739 if (!MD)
18740 return;
18741 // Only attempt to devirtualize if this is truly a virtual call.
18742 bool IsVirtualCall = MD->isVirtual() &&
18743 ME->performsVirtualDispatch(SemaRef.getLangOpts());
18744 if (!IsVirtualCall)
18745 return;
18746
18747 // If it's possible to devirtualize the call, mark the called function
18748 // referenced.
18749 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18750 ME->getBase(), SemaRef.getLangOpts().AppleKext);
18751 if (DM)
18752 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18753}
18754
18755/// Perform reference-marking and odr-use handling for a DeclRefExpr.
18756///
18757/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
18758/// handled with care if the DeclRefExpr is not newly-created.
18759void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18760 // TODO: update this with DR# once a defect report is filed.
18761 // C++11 defect. The address of a pure member should not be an ODR use, even
18762 // if it's a qualified reference.
18763 bool OdrUse = true;
18764 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18765 if (Method->isVirtual() &&
18766 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18767 OdrUse = false;
18768
18769 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18770 if (!isUnevaluatedContext() && !isConstantEvaluated() &&
18771 FD->isConsteval() && !RebuildingImmediateInvocation)
18772 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18773 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
18774 RefsMinusAssignments);
18775}
18776
18777/// Perform reference-marking and odr-use handling for a MemberExpr.
18778void Sema::MarkMemberReferenced(MemberExpr *E) {
18779 // C++11 [basic.def.odr]p2:
18780 // A non-overloaded function whose name appears as a potentially-evaluated
18781 // expression or a member of a set of candidate functions, if selected by
18782 // overload resolution when referred to from a potentially-evaluated
18783 // expression, is odr-used, unless it is a pure virtual function and its
18784 // name is not explicitly qualified.
18785 bool MightBeOdrUse = true;
18786 if (E->performsVirtualDispatch(getLangOpts())) {
18787 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18788 if (Method->isPure())
18789 MightBeOdrUse = false;
18790 }
18791 SourceLocation Loc =
18792 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18793 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
18794 RefsMinusAssignments);
18795}
18796
18797/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18798void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18799 for (VarDecl *VD : *E)
18800 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
18801 RefsMinusAssignments);
18802}
18803
18804/// Perform marking for a reference to an arbitrary declaration. It
18805/// marks the declaration referenced, and performs odr-use checking for
18806/// functions and variables. This method should not be used when building a
18807/// normal expression which refers to a variable.
18808void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18809 bool MightBeOdrUse) {
18810 if (MightBeOdrUse) {
18811 if (auto *VD = dyn_cast<VarDecl>(D)) {
18812 MarkVariableReferenced(Loc, VD);
18813 return;
18814 }
18815 }
18816 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18817 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18818 return;
18819 }
18820 D->setReferenced();
18821}
18822
18823namespace {
18824 // Mark all of the declarations used by a type as referenced.
18825 // FIXME: Not fully implemented yet! We need to have a better understanding
18826 // of when we're entering a context we should not recurse into.
18827 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18828 // TreeTransforms rebuilding the type in a new context. Rather than
18829 // duplicating the TreeTransform logic, we should consider reusing it here.
18830 // Currently that causes problems when rebuilding LambdaExprs.
18831 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18832 Sema &S;
18833 SourceLocation Loc;
18834
18835 public:
18836 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18837
18838 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18839
18840 bool TraverseTemplateArgument(const TemplateArgument &Arg);
18841 };
18842}
18843
18844bool MarkReferencedDecls::TraverseTemplateArgument(
18845 const TemplateArgument &Arg) {
18846 {
18847 // A non-type template argument is a constant-evaluated context.
18848 EnterExpressionEvaluationContext Evaluated(
18849 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18850 if (Arg.getKind() == TemplateArgument::Declaration) {
18851 if (Decl *D = Arg.getAsDecl())
18852 S.MarkAnyDeclReferenced(Loc, D, true);
18853 } else if (Arg.getKind() == TemplateArgument::Expression) {
18854 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18855 }
18856 }
18857
18858 return Inherited::TraverseTemplateArgument(Arg);
18859}
18860
18861void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18862 MarkReferencedDecls Marker(*this, Loc);
18863 Marker.TraverseType(T);
18864}
18865
18866namespace {
18867/// Helper class that marks all of the declarations referenced by
18868/// potentially-evaluated subexpressions as "referenced".
18869class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18870public:
18871 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18872 bool SkipLocalVariables;
18873
18874 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18875 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18876
18877 void visitUsedDecl(SourceLocation Loc, Decl *D) {
18878 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18879 }
18880
18881 void VisitDeclRefExpr(DeclRefExpr *E) {
18882 // If we were asked not to visit local variables, don't.
18883 if (SkipLocalVariables) {
18884 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18885 if (VD->hasLocalStorage())
18886 return;
18887 }
18888
18889 // FIXME: This can trigger the instantiation of the initializer of a
18890 // variable, which can cause the expression to become value-dependent
18891 // or error-dependent. Do we need to propagate the new dependence bits?
18892 S.MarkDeclRefReferenced(E);
18893 }
18894
18895 void VisitMemberExpr(MemberExpr *E) {
18896 S.MarkMemberReferenced(E);
18897 Visit(E->getBase());
18898 }
18899};
18900} // namespace
18901
18902/// Mark any declarations that appear within this expression or any
18903/// potentially-evaluated subexpressions as "referenced".
18904///
18905/// \param SkipLocalVariables If true, don't mark local variables as
18906/// 'referenced'.
18907void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18908 bool SkipLocalVariables) {
18909 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18910}
18911
18912/// Emit a diagnostic that describes an effect on the run-time behavior
18913/// of the program being compiled.
18914///
18915/// This routine emits the given diagnostic when the code currently being
18916/// type-checked is "potentially evaluated", meaning that there is a
18917/// possibility that the code will actually be executable. Code in sizeof()
18918/// expressions, code used only during overload resolution, etc., are not
18919/// potentially evaluated. This routine will suppress such diagnostics or,
18920/// in the absolutely nutty case of potentially potentially evaluated
18921/// expressions (C++ typeid), queue the diagnostic to potentially emit it
18922/// later.
18923///
18924/// This routine should be used for all diagnostics that describe the run-time
18925/// behavior of a program, such as passing a non-POD value through an ellipsis.
18926/// Failure to do so will likely result in spurious diagnostics or failures
18927/// during overload resolution or within sizeof/alignof/typeof/typeid.
18928bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18929 const PartialDiagnostic &PD) {
18930 switch (ExprEvalContexts.back().Context) {
18931 case ExpressionEvaluationContext::Unevaluated:
18932 case ExpressionEvaluationContext::UnevaluatedList:
18933 case ExpressionEvaluationContext::UnevaluatedAbstract:
18934 case ExpressionEvaluationContext::DiscardedStatement:
18935 // The argument will never be evaluated, so don't complain.
18936 break;
18937
18938 case ExpressionEvaluationContext::ConstantEvaluated:
18939 // Relevant diagnostics should be produced by constant evaluation.
18940 break;
18941
18942 case ExpressionEvaluationContext::PotentiallyEvaluated:
18943 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18944 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18945 FunctionScopes.back()->PossiblyUnreachableDiags.
18946 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18947 return true;
18948 }
18949
18950 // The initializer of a constexpr variable or of the first declaration of a
18951 // static data member is not syntactically a constant evaluated constant,
18952 // but nonetheless is always required to be a constant expression, so we
18953 // can skip diagnosing.
18954 // FIXME: Using the mangling context here is a hack.
18955 if (auto *VD = dyn_cast_or_null<VarDecl>(
18956 ExprEvalContexts.back().ManglingContextDecl)) {
18957 if (VD->isConstexpr() ||
18958 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18959 break;
18960 // FIXME: For any other kind of variable, we should build a CFG for its
18961 // initializer and check whether the context in question is reachable.
18962 }
18963
18964 Diag(Loc, PD);
18965 return true;
18966 }
18967
18968 return false;
18969}
18970
18971bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18972 const PartialDiagnostic &PD) {
18973 return DiagRuntimeBehavior(
18974 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18975}
18976
18977bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18978 CallExpr *CE, FunctionDecl *FD) {
18979 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18980 return false;
18981
18982 // If we're inside a decltype's expression, don't check for a valid return
18983 // type or construct temporaries until we know whether this is the last call.
18984 if (ExprEvalContexts.back().ExprContext ==
18985 ExpressionEvaluationContextRecord::EK_Decltype) {
18986 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18987 return false;
18988 }
18989
18990 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18991 FunctionDecl *FD;
18992 CallExpr *CE;
18993
18994 public:
18995 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18996 : FD(FD), CE(CE) { }
18997
18998 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18999 if (!FD) {
19000 S.Diag(Loc, diag::err_call_incomplete_return)
19001 << T << CE->getSourceRange();
19002 return;
19003 }
19004
19005 S.Diag(Loc, diag::err_call_function_incomplete_return)
19006 << CE->getSourceRange() << FD << T;
19007 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19008 << FD->getDeclName();
19009 }
19010 } Diagnoser(FD, CE);
19011
19012 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19013 return true;
19014
19015 return false;
19016}
19017
19018// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19019// will prevent this condition from triggering, which is what we want.
19020void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19021 SourceLocation Loc;
19022
19023 unsigned diagnostic = diag::warn_condition_is_assignment;
19024 bool IsOrAssign = false;
19025
19026 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19027 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19028 return;
19029
19030 IsOrAssign = Op->getOpcode() == BO_OrAssign;
19031
19032 // Greylist some idioms by putting them into a warning subcategory.
19033 if (ObjCMessageExpr *ME
19034 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19035 Selector Sel = ME->getSelector();
19036
19037 // self = [<foo> init...]
19038 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19039 diagnostic = diag::warn_condition_is_idiomatic_assignment;
19040
19041 // <foo> = [<bar> nextObject]
19042 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19043 diagnostic = diag::warn_condition_is_idiomatic_assignment;
19044 }
19045
19046 Loc = Op->getOperatorLoc();
19047 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19048 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19049 return;
19050
19051 IsOrAssign = Op->getOperator() == OO_PipeEqual;
19052 Loc = Op->getOperatorLoc();
19053 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19054 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19055 else {
19056 // Not an assignment.
19057 return;
19058 }
19059
19060 Diag(Loc, diagnostic) << E->getSourceRange();
19061
19062 SourceLocation Open = E->getBeginLoc();
19063 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19064 Diag(Loc, diag::note_condition_assign_silence)
19065 << FixItHint::CreateInsertion(Open, "(")
19066 << FixItHint::CreateInsertion(Close, ")");
19067
19068 if (IsOrAssign)
19069 Diag(Loc, diag::note_condition_or_assign_to_comparison)
19070 << FixItHint::CreateReplacement(Loc, "!=");
19071 else
19072 Diag(Loc, diag::note_condition_assign_to_comparison)
19073 << FixItHint::CreateReplacement(Loc, "==");
19074}
19075
19076/// Redundant parentheses over an equality comparison can indicate
19077/// that the user intended an assignment used as condition.
19078void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19079 // Don't warn if the parens came from a macro.
19080 SourceLocation parenLoc = ParenE->getBeginLoc();
19081 if (parenLoc.isInvalid() || parenLoc.isMacroID())
19082 return;
19083 // Don't warn for dependent expressions.
19084 if (ParenE->isTypeDependent())
19085 return;
19086
19087 Expr *E = ParenE->IgnoreParens();
19088
19089 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19090 if (opE->getOpcode() == BO_EQ &&
19091 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19092 == Expr::MLV_Valid) {
19093 SourceLocation Loc = opE->getOperatorLoc();
19094
19095 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19096 SourceRange ParenERange = ParenE->getSourceRange();
19097 Diag(Loc, diag::note_equality_comparison_silence)
19098 << FixItHint::CreateRemoval(ParenERange.getBegin())
19099 << FixItHint::CreateRemoval(ParenERange.getEnd());
19100 Diag(Loc, diag::note_equality_comparison_to_assign)
19101 << FixItHint::CreateReplacement(Loc, "=");
19102 }
19103}
19104
19105ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19106 bool IsConstexpr) {
19107 DiagnoseAssignmentAsCondition(E);
19108 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19109 DiagnoseEqualityWithExtraParens(parenE);
19110
19111 ExprResult result = CheckPlaceholderExpr(E);
19112 if (result.isInvalid()) return ExprError();
19113 E = result.get();
19114
19115 if (!E->isTypeDependent()) {
19116 if (getLangOpts().CPlusPlus)
19117 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19118
19119 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19120 if (ERes.isInvalid())
19121 return ExprError();
19122 E = ERes.get();
19123
19124 QualType T = E->getType();
19125 if (!T->isScalarType()) { // C99 6.8.4.1p1
19126 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19127 << T << E->getSourceRange();
19128 return ExprError();
19129 }
19130 CheckBoolLikeConversion(E, Loc);
19131 }
19132
19133 return E;
19134}
19135
19136Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19137 Expr *SubExpr, ConditionKind CK) {
19138 // Empty conditions are valid in for-statements.
19139 if (!SubExpr)
19140 return ConditionResult();
19141
19142 ExprResult Cond;
19143 switch (CK) {
19144 case ConditionKind::Boolean:
19145 Cond = CheckBooleanCondition(Loc, SubExpr);
19146 break;
19147
19148 case ConditionKind::ConstexprIf:
19149 Cond = CheckBooleanCondition(Loc, SubExpr, true);
19150 break;
19151
19152 case ConditionKind::Switch:
19153 Cond = CheckSwitchCondition(Loc, SubExpr);
19154 break;
19155 }
19156 if (Cond.isInvalid()) {
19157 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19158 {SubExpr});
19159 if (!Cond.get())
19160 return ConditionError();
19161 }
19162 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19163 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19164 if (!FullExpr.get())
19165 return ConditionError();
19166
19167 return ConditionResult(*this, nullptr, FullExpr,
19168 CK == ConditionKind::ConstexprIf);
19169}
19170
19171namespace {
19172 /// A visitor for rebuilding a call to an __unknown_any expression
19173 /// to have an appropriate type.
19174 struct RebuildUnknownAnyFunction
19175 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19176
19177 Sema &S;
19178
19179 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19180
19181 ExprResult VisitStmt(Stmt *S) {
19182 llvm_unreachable("unexpected statement!")__builtin_unreachable();
19183 }
19184
19185 ExprResult VisitExpr(Expr *E) {
19186 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19187 << E->getSourceRange();
19188 return ExprError();
19189 }
19190
19191 /// Rebuild an expression which simply semantically wraps another
19192 /// expression which it shares the type and value kind of.
19193 template <class T> ExprResult rebuildSugarExpr(T *E) {
19194 ExprResult SubResult = Visit(E->getSubExpr());
19195 if (SubResult.isInvalid()) return ExprError();
19196
19197 Expr *SubExpr = SubResult.get();
19198 E->setSubExpr(SubExpr);
19199 E->setType(SubExpr->getType());
19200 E->setValueKind(SubExpr->getValueKind());
19201 assert(E->getObjectKind() == OK_Ordinary)(static_cast<void> (0));
19202 return E;
19203 }
19204
19205 ExprResult VisitParenExpr(ParenExpr *E) {
19206 return rebuildSugarExpr(E);
19207 }
19208
19209 ExprResult VisitUnaryExtension(UnaryOperator *E) {
19210 return rebuildSugarExpr(E);
19211 }
19212
19213 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19214 ExprResult SubResult = Visit(E->getSubExpr());
19215 if (SubResult.isInvalid()) return ExprError();
19216
19217 Expr *SubExpr = SubResult.get();
19218 E->setSubExpr(SubExpr);
19219 E->setType(S.Context.getPointerType(SubExpr->getType()));
19220 assert(E->isPRValue())(static_cast<void> (0));
19221 assert(E->getObjectKind() == OK_Ordinary)(static_cast<void> (0));
19222 return E;
19223 }
19224
19225 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
19226 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
19227
19228 E->setType(VD->getType());
19229
19230 assert(E->isPRValue())(static_cast<void> (0));
19231 if (S.getLangOpts().CPlusPlus &&
19232 !(isa<CXXMethodDecl>(VD) &&
19233 cast<CXXMethodDecl>(VD)->isInstance()))
19234 E->setValueKind(VK_LValue);
19235
19236 return E;
19237 }
19238
19239 ExprResult VisitMemberExpr(MemberExpr *E) {
19240 return resolveDecl(E, E->getMemberDecl());
19241 }
19242
19243 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19244 return resolveDecl(E, E->getDecl());
19245 }
19246 };
19247}
19248
19249/// Given a function expression of unknown-any type, try to rebuild it
19250/// to have a function type.
19251static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19252 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
19253 if (Result.isInvalid()) return ExprError();
19254 return S.DefaultFunctionArrayConversion(Result.get());
19255}
19256
19257namespace {
19258 /// A visitor for rebuilding an expression of type __unknown_anytype
19259 /// into one which resolves the type directly on the referring
19260 /// expression. Strict preservation of the original source
19261 /// structure is not a goal.
19262 struct RebuildUnknownAnyExpr
19263 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
19264
19265 Sema &S;
19266
19267 /// The current destination type.
19268 QualType DestType;
19269
19270 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
19271 : S(S), DestType(CastType) {}
19272
19273 ExprResult VisitStmt(Stmt *S) {
19274 llvm_unreachable("unexpected statement!")__builtin_unreachable();
19275 }
19276
19277 ExprResult VisitExpr(Expr *E) {
19278 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19279 << E->getSourceRange();
19280 return ExprError();
19281 }
19282
19283 ExprResult VisitCallExpr(CallExpr *E);
19284 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
19285
19286 /// Rebuild an expression which simply semantically wraps another
19287 /// expression which it shares the type and value kind of.
19288 template <class T> ExprResult rebuildSugarExpr(T *E) {
19289 ExprResult SubResult = Visit(E->getSubExpr());
19290 if (SubResult.isInvalid()) return ExprError();
19291 Expr *SubExpr = SubResult.get();
19292 E->setSubExpr(SubExpr);
19293 E->setType(SubExpr->getType());
19294 E->setValueKind(SubExpr->getValueKind());
19295 assert(E->getObjectKind() == OK_Ordinary)(static_cast<void> (0));
19296 return E;
19297 }
19298
19299 ExprResult VisitParenExpr(ParenExpr *E) {
19300 return rebuildSugarExpr(E);
19301 }
19302
19303 ExprResult VisitUnaryExtension(UnaryOperator *E) {
19304 return rebuildSugarExpr(E);
19305 }
19306
19307 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19308 const PointerType *Ptr = DestType->getAs<PointerType>();
19309 if (!Ptr) {
19310 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
19311 << E->getSourceRange();
19312 return ExprError();
19313 }
19314
19315 if (isa<CallExpr>(E->getSubExpr())) {
19316 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
19317 << E->getSourceRange();
19318 return ExprError();
19319 }
19320
19321 assert(E->isPRValue())(static_cast<void> (0));
19322 assert(E->getObjectKind() == OK_Ordinary)(static_cast<void> (0));
19323 E->setType(DestType);
19324
19325 // Build the sub-expression as if it were an object of the pointee type.
19326 DestType = Ptr->getPointeeType();
19327 ExprResult SubResult = Visit(E->getSubExpr());
19328 if (SubResult.isInvalid()) return ExprError();
19329 E->setSubExpr(SubResult.get());
19330 return E;
19331 }
19332
19333 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
19334
19335 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
19336
19337 ExprResult VisitMemberExpr(MemberExpr *E) {
19338 return resolveDecl(E, E->getMemberDecl());
19339 }
19340
19341 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19342 return resolveDecl(E, E->getDecl());
19343 }
19344 };
19345}
19346
19347/// Rebuilds a call expression which yielded __unknown_anytype.
19348ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19349 Expr *CalleeExpr = E->getCallee();
19350
19351 enum FnKind {
19352 FK_MemberFunction,
19353 FK_FunctionPointer,
19354 FK_BlockPointer
19355 };
19356
19357 FnKind Kind;
19358 QualType CalleeType = CalleeExpr->getType();
19359 if (CalleeType == S.Context.BoundMemberTy) {
19360 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))(static_cast<void> (0));
19361 Kind = FK_MemberFunction;
19362 CalleeType = Expr::findBoundMemberType(CalleeExpr);
19363 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19364 CalleeType = Ptr->getPointeeType();
19365 Kind = FK_FunctionPointer;
19366 } else {
19367 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19368 Kind = FK_BlockPointer;
19369 }
19370 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19371
19372 // Verify that this is a legal result type of a function.
19373 if (DestType->isArrayType() || DestType->isFunctionType()) {
19374 unsigned diagID = diag::err_func_returning_array_function;
19375 if (Kind == FK_BlockPointer)
19376 diagID = diag::err_block_returning_array_function;
19377
19378 S.Diag(E->getExprLoc(), diagID)
19379 << DestType->isFunctionType() << DestType;
19380 return ExprError();
19381 }
19382
19383 // Otherwise, go ahead and set DestType as the call's result.
19384 E->setType(DestType.getNonLValueExprType(S.Context));
19385 E->setValueKind(Expr::getValueKindForType(DestType));
19386 assert(E->getObjectKind() == OK_Ordinary)(static_cast<void> (0));
19387
19388 // Rebuild the function type, replacing the result type with DestType.
19389 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19390 if (Proto) {
19391 // __unknown_anytype(...) is a special case used by the debugger when
19392 // it has no idea what a function's signature is.
19393 //
19394 // We want to build this call essentially under the K&R
19395 // unprototyped rules, but making a FunctionNoProtoType in C++
19396 // would foul up all sorts of assumptions. However, we cannot
19397 // simply pass all arguments as variadic arguments, nor can we
19398 // portably just call the function under a non-variadic type; see
19399 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19400 // However, it turns out that in practice it is generally safe to
19401 // call a function declared as "A foo(B,C,D);" under the prototype
19402 // "A foo(B,C,D,...);". The only known exception is with the
19403 // Windows ABI, where any variadic function is implicitly cdecl
19404 // regardless of its normal CC. Therefore we change the parameter
19405 // types to match the types of the arguments.
19406 //
19407 // This is a hack, but it is far superior to moving the
19408 // corresponding target-specific code from IR-gen to Sema/AST.
19409
19410 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19411 SmallVector<QualType, 8> ArgTypes;
19412 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19413 ArgTypes.reserve(E->getNumArgs());
19414 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19415 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
19416 }
19417 ParamTypes = ArgTypes;
19418 }
19419 DestType = S.Context.getFunctionType(DestType, ParamTypes,
19420 Proto->getExtProtoInfo());
19421 } else {
19422 DestType = S.Context.getFunctionNoProtoType(DestType,
19423 FnType->getExtInfo());
19424 }
19425
19426 // Rebuild the appropriate pointer-to-function type.
19427 switch (Kind) {
19428 case FK_MemberFunction:
19429 // Nothing to do.
19430 break;
19431
19432 case FK_FunctionPointer:
19433 DestType = S.Context.getPointerType(DestType);
19434 break;
19435
19436 case FK_BlockPointer:
19437 DestType = S.Context.getBlockPointerType(DestType);
19438 break;
19439 }
19440
19441 // Finally, we can recurse.
19442 ExprResult CalleeResult = Visit(CalleeExpr);
19443 if (!CalleeResult.isUsable()) return ExprError();
19444 E->setCallee(CalleeResult.get());
19445
19446 // Bind a temporary if necessary.
19447 return S.MaybeBindToTemporary(E);
19448}
19449
19450ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19451 // Verify that this is a legal result type of a call.
19452 if (DestType->isArrayType() || DestType->isFunctionType()) {
19453 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19454 << DestType->isFunctionType() << DestType;
19455 return ExprError();
19456 }
19457
19458 // Rewrite the method result type if available.
19459 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19460 assert(Method->getReturnType() == S.Context.UnknownAnyTy)(static_cast<void> (0));
19461 Method->setReturnType(DestType);
19462 }
19463
19464 // Change the type of the message.
19465 E->setType(DestType.getNonReferenceType());
19466 E->setValueKind(Expr::getValueKindForType(DestType));
19467
19468 return S.MaybeBindToTemporary(E);
19469}
19470
19471ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19472 // The only case we should ever see here is a function-to-pointer decay.
19473 if (E->getCastKind() == CK_FunctionToPointerDecay) {
19474 assert(E->isPRValue())(static_cast<void> (0));
19475 assert(E->getObjectKind() == OK_Ordinary)(static_cast<void> (0));
19476
19477 E->setType(DestType);
19478
19479 // Rebuild the sub-expression as the pointee (function) type.
19480 DestType = DestType->castAs<PointerType>()->getPointeeType();
19481
19482 ExprResult Result = Visit(E->getSubExpr());
19483 if (!Result.isUsable()) return ExprError();
19484
19485 E->setSubExpr(Result.get());
19486 return E;
19487 } else if (E->getCastKind() == CK_LValueToRValue) {
19488 assert(E->isPRValue())(static_cast<void> (0));
19489 assert(E->getObjectKind() == OK_Ordinary)(static_cast<void> (0));
19490
19491 assert(isa<BlockPointerType>(E->getType()))(static_cast<void> (0));
19492
19493 E->setType(DestType);
19494
19495 // The sub-expression has to be a lvalue reference, so rebuild it as such.
19496 DestType = S.Context.getLValueReferenceType(DestType);
19497
19498 ExprResult Result = Visit(E->getSubExpr());
19499 if (!Result.isUsable()) return ExprError();
19500
19501 E->setSubExpr(Result.get());
19502 return E;
19503 } else {
19504 llvm_unreachable("Unhandled cast type!")__builtin_unreachable();
19505 }
19506}
19507
19508ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19509 ExprValueKind ValueKind = VK_LValue;
19510 QualType Type = DestType;
19511
19512 // We know how to make this work for certain kinds of decls:
19513
19514 // - functions
19515 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19516 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19517 DestType = Ptr->getPointeeType();
19518 ExprResult Result = resolveDecl(E, VD);
19519 if (Result.isInvalid()) return ExprError();
19520 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
19521 VK_PRValue);
19522 }
19523
19524 if (!Type->isFunctionType()) {
19525 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19526 << VD << E->getSourceRange();
19527 return ExprError();
19528 }
19529 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19530 // We must match the FunctionDecl's type to the hack introduced in
19531 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19532 // type. See the lengthy commentary in that routine.
19533 QualType FDT = FD->getType();
19534 const FunctionType *FnType = FDT->castAs<FunctionType>();
19535 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19536 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19537 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19538 SourceLocation Loc = FD->getLocation();
19539 FunctionDecl *NewFD = FunctionDecl::Create(
19540 S.Context, FD->getDeclContext(), Loc, Loc,
19541 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19542 SC_None, S.getCurFPFeatures().isFPConstrained(),
19543 false /*isInlineSpecified*/, FD->hasPrototype(),
19544 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19545
19546 if (FD->getQualifier())
19547 NewFD->setQualifierInfo(FD->getQualifierLoc());
19548
19549 SmallVector<ParmVarDecl*, 16> Params;
19550 for (const auto &AI : FT->param_types()) {
19551 ParmVarDecl *Param =
19552 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19553 Param->setScopeInfo(0, Params.size());
19554 Params.push_back(Param);
19555 }
19556 NewFD->setParams(Params);
19557 DRE->setDecl(NewFD);
19558 VD = DRE->getDecl();
19559 }
19560 }
19561
19562 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19563 if (MD->isInstance()) {
19564 ValueKind = VK_PRValue;
19565 Type = S.Context.BoundMemberTy;
19566 }
19567
19568 // Function references aren't l-values in C.
19569 if (!S.getLangOpts().CPlusPlus)
19570 ValueKind = VK_PRValue;
19571
19572 // - variables
19573 } else if (isa<VarDecl>(VD)) {
19574 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19575 Type = RefTy->getPointeeType();
19576 } else if (Type->isFunctionType()) {
19577 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19578 << VD << E->getSourceRange();
19579 return ExprError();
19580 }
19581
19582 // - nothing else
19583 } else {
19584 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19585 << VD << E->getSourceRange();
19586 return ExprError();
19587 }
19588
19589 // Modifying the declaration like this is friendly to IR-gen but
19590 // also really dangerous.
19591 VD->setType(DestType);
19592 E->setType(Type);
19593 E->setValueKind(ValueKind);
19594 return E;
19595}
19596
19597/// Check a cast of an unknown-any type. We intentionally only
19598/// trigger this for C-style casts.
19599ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19600 Expr *CastExpr, CastKind &CastKind,
19601 ExprValueKind &VK, CXXCastPath &Path) {
19602 // The type we're casting to must be either void or complete.
19603 if (!CastType->isVoidType() &&
19604 RequireCompleteType(TypeRange.getBegin(), CastType,
19605 diag::err_typecheck_cast_to_incomplete))
19606 return ExprError();
19607
19608 // Rewrite the casted expression from scratch.
19609 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19610 if (!result.isUsable()) return ExprError();
19611
19612 CastExpr = result.get();
19613 VK = CastExpr->getValueKind();
19614 CastKind = CK_NoOp;
19615
19616 return CastExpr;
19617}
19618
19619ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19620 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19621}
19622
19623ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19624 Expr *arg, QualType &paramType) {
19625 // If the syntactic form of the argument is not an explicit cast of
19626 // any sort, just do default argument promotion.
19627 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19628 if (!castArg) {
19629 ExprResult result = DefaultArgumentPromotion(arg);
19630 if (result.isInvalid()) return ExprError();
19631 paramType = result.get()->getType();
19632 return result;
19633 }
19634
19635 // Otherwise, use the type that was written in the explicit cast.
19636 assert(!arg->hasPlaceholderType())(static_cast<void> (0));
19637 paramType = castArg->getTypeAsWritten();
19638
19639 // Copy-initialize a parameter of that type.
19640 InitializedEntity entity =
19641 InitializedEntity::InitializeParameter(Context, paramType,
19642 /*consumed*/ false);
19643 return PerformCopyInitialization(entity, callLoc, arg);
19644}
19645
19646static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19647 Expr *orig = E;
19648 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19649 while (true) {
19650 E = E->IgnoreParenImpCasts();
19651 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19652 E = call->getCallee();
19653 diagID = diag::err_uncasted_call_of_unknown_any;
19654 } else {
19655 break;
19656 }
19657 }
19658
19659 SourceLocation loc;
19660 NamedDecl *d;
19661 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19662 loc = ref->getLocation();
19663 d = ref->getDecl();
19664 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19665 loc = mem->getMemberLoc();
19666 d = mem->getMemberDecl();
19667 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19668 diagID = diag::err_uncasted_call_of_unknown_any;
19669 loc = msg->getSelectorStartLoc();
19670 d = msg->getMethodDecl();
19671 if (!d) {
19672 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19673 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19674 << orig->getSourceRange();
19675 return ExprError();
19676 }
19677 } else {
19678 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19679 << E->getSourceRange();
19680 return ExprError();
19681 }
19682
19683 S.Diag(loc, diagID) << d << orig->getSourceRange();
19684
19685 // Never recoverable.
19686 return ExprError();
19687}
19688
19689/// Check for operands with placeholder types and complain if found.
19690/// Returns ExprError() if there was an error and no recovery was possible.
19691ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19692 if (!Context.isDependenceAllowed()) {
19693 // C cannot handle TypoExpr nodes on either side of a binop because it
19694 // doesn't handle dependent types properly, so make sure any TypoExprs have
19695 // been dealt with before checking the operands.
19696 ExprResult Result = CorrectDelayedTyposInExpr(E);
19697 if (!Result.isUsable()) return ExprError();
19698 E = Result.get();
19699 }
19700
19701 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19702 if (!placeholderType) return E;
19703
19704 switch (placeholderType->getKind()) {
19705
19706 // Overloaded expressions.
19707 case BuiltinType::Overload: {
19708 // Try to resolve a single function template specialization.
19709 // This is obligatory.
19710 ExprResult Result = E;
19711 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19712 return Result;
19713
19714 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19715 // leaves Result unchanged on failure.
19716 Result = E;
19717 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19718 return Result;
19719
19720 // If that failed, try to recover with a call.
19721 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19722 /*complain*/ true);
19723 return Result;
19724 }
19725
19726 // Bound member functions.
19727 case BuiltinType::BoundMember: {
19728 ExprResult result = E;
19729 const Expr *BME = E->IgnoreParens();
19730 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19731 // Try to give a nicer diagnostic if it is a bound member that we recognize.
19732 if (isa<CXXPseudoDestructorExpr>(BME)) {
19733 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19734 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19735 if (ME->getMemberNameInfo().getName().getNameKind() ==
19736 DeclarationName::CXXDestructorName)
19737 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19738 }
19739 tryToRecoverWithCall(result, PD,
19740 /*complain*/ true);
19741 return result;
19742 }
19743
19744 // ARC unbridged casts.
19745 case BuiltinType::ARCUnbridgedCast: {
19746 Expr *realCast = stripARCUnbridgedCast(E);
19747 diagnoseARCUnbridgedCast(realCast);
19748 return realCast;
19749 }
19750
19751 // Expressions of unknown type.
19752 case BuiltinType::UnknownAny:
19753 return diagnoseUnknownAnyExpr(*this, E);
19754
19755 // Pseudo-objects.
19756 case BuiltinType::PseudoObject:
19757 return checkPseudoObjectRValue(E);
19758
19759 case BuiltinType::BuiltinFn: {
19760 // Accept __noop without parens by implicitly converting it to a call expr.
19761 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19762 if (DRE) {
19763 auto *FD = cast<FunctionDecl>(DRE->getDecl());
19764 if (FD->getBuiltinID() == Builtin::BI__noop) {
19765 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19766 CK_BuiltinFnToFnPtr)
19767 .get();
19768 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19769 VK_PRValue, SourceLocation(),
19770 FPOptionsOverride());
19771 }
19772 }
19773
19774 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19775 return ExprError();
19776 }
19777
19778 case BuiltinType::IncompleteMatrixIdx:
19779 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19780 ->getRowIdx()
19781 ->getBeginLoc(),
19782 diag::err_matrix_incomplete_index);
19783 return ExprError();
19784
19785 // Expressions of unknown type.
19786 case BuiltinType::OMPArraySection:
19787 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19788 return ExprError();
19789
19790 // Expressions of unknown type.
19791 case BuiltinType::OMPArrayShaping:
19792 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19793
19794 case BuiltinType::OMPIterator:
19795 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19796
19797 // Everything else should be impossible.
19798#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19799 case BuiltinType::Id:
19800#include "clang/Basic/OpenCLImageTypes.def"
19801#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19802 case BuiltinType::Id:
19803#include "clang/Basic/OpenCLExtensionTypes.def"
19804#define SVE_TYPE(Name, Id, SingletonId) \
19805 case BuiltinType::Id:
19806#include "clang/Basic/AArch64SVEACLETypes.def"
19807#define PPC_VECTOR_TYPE(Name, Id, Size) \
19808 case BuiltinType::Id:
19809#include "clang/Basic/PPCTypes.def"
19810#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
19811#include "clang/Basic/RISCVVTypes.def"
19812#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19813#define PLACEHOLDER_TYPE(Id, SingletonId)
19814#include "clang/AST/BuiltinTypes.def"
19815 break;
19816 }
19817
19818 llvm_unreachable("invalid placeholder type!")__builtin_unreachable();
19819}
19820
19821bool Sema::CheckCaseExpression(Expr *E) {
19822 if (E->isTypeDependent())
19823 return true;
19824 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19825 return E->getType()->isIntegralOrEnumerationType();
19826 return false;
19827}
19828
19829/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19830ExprResult
19831Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19832 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(static_cast<void> (0))
19833 "Unknown Objective-C Boolean value!")(static_cast<void> (0));
19834 QualType BoolT = Context.ObjCBuiltinBoolTy;
19835 if (!Context.getBOOLDecl()) {
19836 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19837 Sema::LookupOrdinaryName);
19838 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19839 NamedDecl *ND = Result.getFoundDecl();
19840 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19841 Context.setBOOLDecl(TD);
19842 }
19843 }
19844 if (Context.getBOOLDecl())
19845 BoolT = Context.getBOOLType();
19846 return new (Context)
19847 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19848}
19849
19850ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19851 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19852 SourceLocation RParen) {
19853 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
19854 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19855 return Spec.getPlatform() == Platform;
19856 });
19857 // Transcribe the "ios" availability check to "maccatalyst" when compiling
19858 // for "maccatalyst" if "maccatalyst" is not specified.
19859 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
19860 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19861 return Spec.getPlatform() == "ios";
19862 });
19863 }
19864 if (Spec == AvailSpecs.end())
19865 return None;
19866 return Spec->getVersion();
19867 };
19868
19869 VersionTuple Version;
19870 if (auto MaybeVersion =
19871 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
19872 Version = *MaybeVersion;
19873
19874 // The use of `@available` in the enclosing context should be analyzed to
19875 // warn when it's used inappropriately (i.e. not if(@available)).
19876 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
19877 Context->HasPotentialAvailabilityViolations = true;
19878
19879 return new (Context)
19880 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19881}
19882
19883ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19884 ArrayRef<Expr *> SubExprs, QualType T) {
19885 if (!Context.getLangOpts().RecoveryAST)
19886 return ExprError();
19887
19888 if (isSFINAEContext())
19889 return ExprError();
19890
19891 if (T.isNull() || T->isUndeducedType() ||
19892 !Context.getLangOpts().RecoveryASTType)
19893 // We don't know the concrete type, fallback to dependent type.
19894 T = Context.DependentTy;
19895
19896 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19897}