Bug Summary

File:build/source/clang/lib/Sema/SemaExpr.cpp
Warning:line 4855, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaExpr.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/clang/lib/Sema/SemaExpr.cpp

/build/source/clang/lib/Sema/SemaExpr.cpp

1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "UsedDeclVisitor.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExprOpenMP.h"
27#include "clang/AST/OperationKinds.h"
28#include "clang/AST/ParentMapContext.h"
29#include "clang/AST/RecursiveASTVisitor.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/Basic/Builtins.h"
33#include "clang/Basic/DiagnosticSema.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/Specifiers.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Lex/LiteralSupport.h"
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/DeclSpec.h"
42#include "clang/Sema/DelayedDiagnostic.h"
43#include "clang/Sema/Designator.h"
44#include "clang/Sema/EnterExpressionEvaluationContext.h"
45#include "clang/Sema/Initialization.h"
46#include "clang/Sema/Lookup.h"
47#include "clang/Sema/Overload.h"
48#include "clang/Sema/ParsedTemplate.h"
49#include "clang/Sema/Scope.h"
50#include "clang/Sema/ScopeInfo.h"
51#include "clang/Sema/SemaFixItUtils.h"
52#include "clang/Sema/SemaInternal.h"
53#include "clang/Sema/Template.h"
54#include "llvm/ADT/STLExtras.h"
55#include "llvm/ADT/StringExtras.h"
56#include "llvm/Support/Casting.h"
57#include "llvm/Support/ConvertUTF.h"
58#include "llvm/Support/SaveAndRestore.h"
59#include "llvm/Support/TypeSize.h"
60#include <optional>
61
62using namespace clang;
63using namespace sema;
64
65/// Determine whether the use of this declaration is valid, without
66/// emitting diagnostics.
67bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
68 // See if this is an auto-typed variable whose initializer we are parsing.
69 if (ParsingInitForAutoVars.count(D))
70 return false;
71
72 // See if this is a deleted function.
73 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74 if (FD->isDeleted())
75 return false;
76
77 // If the function has a deduced return type, and we can't deduce it,
78 // then we can't use it either.
79 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
80 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
81 return false;
82
83 // See if this is an aligned allocation/deallocation function that is
84 // unavailable.
85 if (TreatUnavailableAsInvalid &&
86 isUnavailableAlignedAllocationFunction(*FD))
87 return false;
88 }
89
90 // See if this function is unavailable.
91 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
92 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
93 return false;
94
95 if (isa<UnresolvedUsingIfExistsDecl>(D))
96 return false;
97
98 return true;
99}
100
101static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
102 // Warn if this is used but marked unused.
103 if (const auto *A = D->getAttr<UnusedAttr>()) {
104 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
105 // should diagnose them.
106 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
107 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
108 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
109 if (DC && !DC->hasAttr<UnusedAttr>())
110 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
111 }
112 }
113}
114
115/// Emit a note explaining that this function is deleted.
116void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
117 assert(Decl && Decl->isDeleted())(static_cast <bool> (Decl && Decl->isDeleted
()) ? void (0) : __assert_fail ("Decl && Decl->isDeleted()"
, "clang/lib/Sema/SemaExpr.cpp", 117, __extension__ __PRETTY_FUNCTION__
))
;
118
119 if (Decl->isDefaulted()) {
120 // If the method was explicitly defaulted, point at that declaration.
121 if (!Decl->isImplicit())
122 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
123
124 // Try to diagnose why this special member function was implicitly
125 // deleted. This might fail, if that reason no longer applies.
126 DiagnoseDeletedDefaultedFunction(Decl);
127 return;
128 }
129
130 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
131 if (Ctor && Ctor->isInheritingConstructor())
132 return NoteDeletedInheritingConstructor(Ctor);
133
134 Diag(Decl->getLocation(), diag::note_availability_specified_here)
135 << Decl << 1;
136}
137
138/// Determine whether a FunctionDecl was ever declared with an
139/// explicit storage class.
140static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
141 for (auto *I : D->redecls()) {
142 if (I->getStorageClass() != SC_None)
143 return true;
144 }
145 return false;
146}
147
148/// Check whether we're in an extern inline function and referring to a
149/// variable or function with internal linkage (C11 6.7.4p3).
150///
151/// This is only a warning because we used to silently accept this code, but
152/// in many cases it will not behave correctly. This is not enabled in C++ mode
153/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
154/// and so while there may still be user mistakes, most of the time we can't
155/// prove that there are errors.
156static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
157 const NamedDecl *D,
158 SourceLocation Loc) {
159 // This is disabled under C++; there are too many ways for this to fire in
160 // contexts where the warning is a false positive, or where it is technically
161 // correct but benign.
162 if (S.getLangOpts().CPlusPlus)
163 return;
164
165 // Check if this is an inlined function or method.
166 FunctionDecl *Current = S.getCurFunctionDecl();
167 if (!Current)
168 return;
169 if (!Current->isInlined())
170 return;
171 if (!Current->isExternallyVisible())
172 return;
173
174 // Check if the decl has internal linkage.
175 if (D->getFormalLinkage() != InternalLinkage)
176 return;
177
178 // Downgrade from ExtWarn to Extension if
179 // (1) the supposedly external inline function is in the main file,
180 // and probably won't be included anywhere else.
181 // (2) the thing we're referencing is a pure function.
182 // (3) the thing we're referencing is another inline function.
183 // This last can give us false negatives, but it's better than warning on
184 // wrappers for simple C library functions.
185 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
186 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
187 if (!DowngradeWarning && UsedFn)
188 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
189
190 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
191 : diag::ext_internal_in_extern_inline)
192 << /*IsVar=*/!UsedFn << D;
193
194 S.MaybeSuggestAddingStaticToDecl(Current);
195
196 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
197 << D;
198}
199
200void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
201 const FunctionDecl *First = Cur->getFirstDecl();
202
203 // Suggest "static" on the function, if possible.
204 if (!hasAnyExplicitStorageClass(First)) {
205 SourceLocation DeclBegin = First->getSourceRange().getBegin();
206 Diag(DeclBegin, diag::note_convert_inline_to_static)
207 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
208 }
209}
210
211/// Determine whether the use of this declaration is valid, and
212/// emit any corresponding diagnostics.
213///
214/// This routine diagnoses various problems with referencing
215/// declarations that can occur when using a declaration. For example,
216/// it might warn if a deprecated or unavailable declaration is being
217/// used, or produce an error (and return true) if a C++0x deleted
218/// function is being used.
219///
220/// \returns true if there was an error (this declaration cannot be
221/// referenced), false otherwise.
222///
223bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
224 const ObjCInterfaceDecl *UnknownObjCClass,
225 bool ObjCPropertyAccess,
226 bool AvoidPartialAvailabilityChecks,
227 ObjCInterfaceDecl *ClassReceiver,
228 bool SkipTrailingRequiresClause) {
229 SourceLocation Loc = Locs.front();
230 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
231 // If there were any diagnostics suppressed by template argument deduction,
232 // emit them now.
233 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
234 if (Pos != SuppressedDiagnostics.end()) {
235 for (const PartialDiagnosticAt &Suppressed : Pos->second)
236 Diag(Suppressed.first, Suppressed.second);
237
238 // Clear out the list of suppressed diagnostics, so that we don't emit
239 // them again for this specialization. However, we don't obsolete this
240 // entry from the table, because we want to avoid ever emitting these
241 // diagnostics again.
242 Pos->second.clear();
243 }
244
245 // C++ [basic.start.main]p3:
246 // The function 'main' shall not be used within a program.
247 if (cast<FunctionDecl>(D)->isMain())
248 Diag(Loc, diag::ext_main_used);
249
250 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
251 }
252
253 // See if this is an auto-typed variable whose initializer we are parsing.
254 if (ParsingInitForAutoVars.count(D)) {
255 if (isa<BindingDecl>(D)) {
256 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
257 << D->getDeclName();
258 } else {
259 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
260 << D->getDeclName() << cast<VarDecl>(D)->getType();
261 }
262 return true;
263 }
264
265 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
266 // See if this is a deleted function.
267 if (FD->isDeleted()) {
268 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
269 if (Ctor && Ctor->isInheritingConstructor())
270 Diag(Loc, diag::err_deleted_inherited_ctor_use)
271 << Ctor->getParent()
272 << Ctor->getInheritedConstructor().getConstructor()->getParent();
273 else
274 Diag(Loc, diag::err_deleted_function_use);
275 NoteDeletedFunction(FD);
276 return true;
277 }
278
279 // [expr.prim.id]p4
280 // A program that refers explicitly or implicitly to a function with a
281 // trailing requires-clause whose constraint-expression is not satisfied,
282 // other than to declare it, is ill-formed. [...]
283 //
284 // See if this is a function with constraints that need to be satisfied.
285 // Check this before deducing the return type, as it might instantiate the
286 // definition.
287 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
288 ConstraintSatisfaction Satisfaction;
289 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
290 /*ForOverloadResolution*/ true))
291 // A diagnostic will have already been generated (non-constant
292 // constraint expression, for example)
293 return true;
294 if (!Satisfaction.IsSatisfied) {
295 Diag(Loc,
296 diag::err_reference_to_function_with_unsatisfied_constraints)
297 << D;
298 DiagnoseUnsatisfiedConstraint(Satisfaction);
299 return true;
300 }
301 }
302
303 // If the function has a deduced return type, and we can't deduce it,
304 // then we can't use it either.
305 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
306 DeduceReturnType(FD, Loc))
307 return true;
308
309 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
310 return true;
311
312 }
313
314 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
315 // Lambdas are only default-constructible or assignable in C++2a onwards.
316 if (MD->getParent()->isLambda() &&
317 ((isa<CXXConstructorDecl>(MD) &&
318 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
319 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
320 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
321 << !isa<CXXConstructorDecl>(MD);
322 }
323 }
324
325 auto getReferencedObjCProp = [](const NamedDecl *D) ->
326 const ObjCPropertyDecl * {
327 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
328 return MD->findPropertyDecl();
329 return nullptr;
330 };
331 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
332 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
333 return true;
334 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
335 return true;
336 }
337
338 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
339 // Only the variables omp_in and omp_out are allowed in the combiner.
340 // Only the variables omp_priv and omp_orig are allowed in the
341 // initializer-clause.
342 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
343 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
344 isa<VarDecl>(D)) {
345 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
346 << getCurFunction()->HasOMPDeclareReductionCombiner;
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348 return true;
349 }
350
351 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
352 // List-items in map clauses on this construct may only refer to the declared
353 // variable var and entities that could be referenced by a procedure defined
354 // at the same location.
355 // [OpenMP 5.2] Also allow iterator declared variables.
356 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
357 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
358 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
359 << getOpenMPDeclareMapperVarName();
360 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
365 Diag(Loc, diag::err_use_of_empty_using_if_exists);
366 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
367 return true;
368 }
369
370 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
371 AvoidPartialAvailabilityChecks, ClassReceiver);
372
373 DiagnoseUnusedOfDecl(*this, D, Loc);
374
375 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
376
377 if (auto *VD = dyn_cast<ValueDecl>(D))
378 checkTypeSupport(VD->getType(), Loc, VD);
379
380 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
381 if (!Context.getTargetInfo().isTLSSupported())
382 if (const auto *VD = dyn_cast<VarDecl>(D))
383 if (VD->getTLSKind() != VarDecl::TLS_None)
384 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
385 }
386
387 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
388 !isUnevaluatedContext()) {
389 // C++ [expr.prim.req.nested] p3
390 // A local parameter shall only appear as an unevaluated operand
391 // (Clause 8) within the constraint-expression.
392 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
393 << D;
394 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
395 return true;
396 }
397
398 return false;
399}
400
401/// DiagnoseSentinelCalls - This routine checks whether a call or
402/// message-send is to a declaration with the sentinel attribute, and
403/// if so, it checks that the requirements of the sentinel are
404/// satisfied.
405void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
406 ArrayRef<Expr *> Args) {
407 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
408 if (!attr)
409 return;
410
411 // The number of formal parameters of the declaration.
412 unsigned numFormalParams;
413
414 // The kind of declaration. This is also an index into a %select in
415 // the diagnostic.
416 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
417
418 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
419 numFormalParams = MD->param_size();
420 calleeType = CT_Method;
421 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
422 numFormalParams = FD->param_size();
423 calleeType = CT_Function;
424 } else if (isa<VarDecl>(D)) {
425 QualType type = cast<ValueDecl>(D)->getType();
426 const FunctionType *fn = nullptr;
427 if (const PointerType *ptr = type->getAs<PointerType>()) {
428 fn = ptr->getPointeeType()->getAs<FunctionType>();
429 if (!fn) return;
430 calleeType = CT_Function;
431 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
432 fn = ptr->getPointeeType()->castAs<FunctionType>();
433 calleeType = CT_Block;
434 } else {
435 return;
436 }
437
438 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
439 numFormalParams = proto->getNumParams();
440 } else {
441 numFormalParams = 0;
442 }
443 } else {
444 return;
445 }
446
447 // "nullPos" is the number of formal parameters at the end which
448 // effectively count as part of the variadic arguments. This is
449 // useful if you would prefer to not have *any* formal parameters,
450 // but the language forces you to have at least one.
451 unsigned nullPos = attr->getNullPos();
452 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(static_cast <bool> ((nullPos == 0 || nullPos == 1) &&
"invalid null position on sentinel") ? void (0) : __assert_fail
("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\""
, "clang/lib/Sema/SemaExpr.cpp", 452, __extension__ __PRETTY_FUNCTION__
))
;
453 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
454
455 // The number of arguments which should follow the sentinel.
456 unsigned numArgsAfterSentinel = attr->getSentinel();
457
458 // If there aren't enough arguments for all the formal parameters,
459 // the sentinel, and the args after the sentinel, complain.
460 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
461 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
462 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
463 return;
464 }
465
466 // Otherwise, find the sentinel expression.
467 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
468 if (!sentinelExpr) return;
469 if (sentinelExpr->isValueDependent()) return;
470 if (Context.isSentinelNullExpr(sentinelExpr)) return;
471
472 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
473 // or 'NULL' if those are actually defined in the context. Only use
474 // 'nil' for ObjC methods, where it's much more likely that the
475 // variadic arguments form a list of object pointers.
476 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
477 std::string NullValue;
478 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
479 NullValue = "nil";
480 else if (getLangOpts().CPlusPlus11)
481 NullValue = "nullptr";
482 else if (PP.isMacroDefined("NULL"))
483 NullValue = "NULL";
484 else
485 NullValue = "(void*) 0";
486
487 if (MissingNilLoc.isInvalid())
488 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
489 else
490 Diag(MissingNilLoc, diag::warn_missing_sentinel)
491 << int(calleeType)
492 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
493 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
494}
495
496SourceRange Sema::getExprRange(Expr *E) const {
497 return E ? E->getSourceRange() : SourceRange();
498}
499
500//===----------------------------------------------------------------------===//
501// Standard Promotions and Conversions
502//===----------------------------------------------------------------------===//
503
504/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
505ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
506 // Handle any placeholder expressions which made it here.
507 if (E->hasPlaceholderType()) {
508 ExprResult result = CheckPlaceholderExpr(E);
509 if (result.isInvalid()) return ExprError();
510 E = result.get();
511 }
512
513 QualType Ty = E->getType();
514 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"
) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\""
, "clang/lib/Sema/SemaExpr.cpp", 514, __extension__ __PRETTY_FUNCTION__
))
;
515
516 if (Ty->isFunctionType()) {
517 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
518 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
519 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
520 return ExprError();
521
522 E = ImpCastExprToType(E, Context.getPointerType(Ty),
523 CK_FunctionToPointerDecay).get();
524 } else if (Ty->isArrayType()) {
525 // In C90 mode, arrays only promote to pointers if the array expression is
526 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
527 // type 'array of type' is converted to an expression that has type 'pointer
528 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
529 // that has type 'array of type' ...". The relevant change is "an lvalue"
530 // (C90) to "an expression" (C99).
531 //
532 // C++ 4.2p1:
533 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
534 // T" can be converted to an rvalue of type "pointer to T".
535 //
536 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
537 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
538 CK_ArrayToPointerDecay);
539 if (Res.isInvalid())
540 return ExprError();
541 E = Res.get();
542 }
543 }
544 return E;
545}
546
547static void CheckForNullPointerDereference(Sema &S, Expr *E) {
548 // Check to see if we are dereferencing a null pointer. If so,
549 // and if not volatile-qualified, this is undefined behavior that the
550 // optimizer will delete, so warn about it. People sometimes try to use this
551 // to get a deterministic trap and are surprised by clang's behavior. This
552 // only handles the pattern "*null", which is a very syntactic check.
553 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
554 if (UO && UO->getOpcode() == UO_Deref &&
555 UO->getSubExpr()->getType()->isPointerType()) {
556 const LangAS AS =
557 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
558 if ((!isTargetAddressSpace(AS) ||
559 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
560 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
561 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
562 !UO->getType().isVolatileQualified()) {
563 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564 S.PDiag(diag::warn_indirection_through_null)
565 << UO->getSubExpr()->getSourceRange());
566 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
567 S.PDiag(diag::note_indirection_through_null));
568 }
569 }
570}
571
572static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
573 SourceLocation AssignLoc,
574 const Expr* RHS) {
575 const ObjCIvarDecl *IV = OIRE->getDecl();
576 if (!IV)
577 return;
578
579 DeclarationName MemberName = IV->getDeclName();
580 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
581 if (!Member || !Member->isStr("isa"))
582 return;
583
584 const Expr *Base = OIRE->getBase();
585 QualType BaseType = Base->getType();
586 if (OIRE->isArrow())
587 BaseType = BaseType->getPointeeType();
588 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
589 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
590 ObjCInterfaceDecl *ClassDeclared = nullptr;
591 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
592 if (!ClassDeclared->getSuperClass()
593 && (*ClassDeclared->ivar_begin()) == IV) {
594 if (RHS) {
595 NamedDecl *ObjectSetClass =
596 S.LookupSingleName(S.TUScope,
597 &S.Context.Idents.get("object_setClass"),
598 SourceLocation(), S.LookupOrdinaryName);
599 if (ObjectSetClass) {
600 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
601 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
602 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
603 "object_setClass(")
604 << FixItHint::CreateReplacement(
605 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
606 << FixItHint::CreateInsertion(RHSLocEnd, ")");
607 }
608 else
609 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
610 } else {
611 NamedDecl *ObjectGetClass =
612 S.LookupSingleName(S.TUScope,
613 &S.Context.Idents.get("object_getClass"),
614 SourceLocation(), S.LookupOrdinaryName);
615 if (ObjectGetClass)
616 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
617 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
618 "object_getClass(")
619 << FixItHint::CreateReplacement(
620 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
621 else
622 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
623 }
624 S.Diag(IV->getLocation(), diag::note_ivar_decl);
625 }
626 }
627}
628
629ExprResult Sema::DefaultLvalueConversion(Expr *E) {
630 // Handle any placeholder expressions which made it here.
631 if (E->hasPlaceholderType()) {
632 ExprResult result = CheckPlaceholderExpr(E);
633 if (result.isInvalid()) return ExprError();
634 E = result.get();
635 }
636
637 // C++ [conv.lval]p1:
638 // A glvalue of a non-function, non-array type T can be
639 // converted to a prvalue.
640 if (!E->isGLValue()) return E;
641
642 QualType T = E->getType();
643 assert(!T.isNull() && "r-value conversion on typeless expression?")(static_cast <bool> (!T.isNull() && "r-value conversion on typeless expression?"
) ? void (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\""
, "clang/lib/Sema/SemaExpr.cpp", 643, __extension__ __PRETTY_FUNCTION__
))
;
644
645 // lvalue-to-rvalue conversion cannot be applied to function or array types.
646 if (T->isFunctionType() || T->isArrayType())
647 return E;
648
649 // We don't want to throw lvalue-to-rvalue casts on top of
650 // expressions of certain types in C++.
651 if (getLangOpts().CPlusPlus &&
652 (E->getType() == Context.OverloadTy ||
653 T->isDependentType() ||
654 T->isRecordType()))
655 return E;
656
657 // The C standard is actually really unclear on this point, and
658 // DR106 tells us what the result should be but not why. It's
659 // generally best to say that void types just doesn't undergo
660 // lvalue-to-rvalue at all. Note that expressions of unqualified
661 // 'void' type are never l-values, but qualified void can be.
662 if (T->isVoidType())
663 return E;
664
665 // OpenCL usually rejects direct accesses to values of 'half' type.
666 if (getLangOpts().OpenCL &&
667 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
668 T->isHalfType()) {
669 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
670 << 0 << T;
671 return ExprError();
672 }
673
674 CheckForNullPointerDereference(*this, E);
675 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
676 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
677 &Context.Idents.get("object_getClass"),
678 SourceLocation(), LookupOrdinaryName);
679 if (ObjectGetClass)
680 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
681 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
682 << FixItHint::CreateReplacement(
683 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
684 else
685 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
686 }
687 else if (const ObjCIvarRefExpr *OIRE =
688 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
689 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
690
691 // C++ [conv.lval]p1:
692 // [...] If T is a non-class type, the type of the prvalue is the
693 // cv-unqualified version of T. Otherwise, the type of the
694 // rvalue is T.
695 //
696 // C99 6.3.2.1p2:
697 // If the lvalue has qualified type, the value has the unqualified
698 // version of the type of the lvalue; otherwise, the value has the
699 // type of the lvalue.
700 if (T.hasQualifiers())
701 T = T.getUnqualifiedType();
702
703 // Under the MS ABI, lock down the inheritance model now.
704 if (T->isMemberPointerType() &&
705 Context.getTargetInfo().getCXXABI().isMicrosoft())
706 (void)isCompleteType(E->getExprLoc(), T);
707
708 ExprResult Res = CheckLValueToRValueConversionOperand(E);
709 if (Res.isInvalid())
710 return Res;
711 E = Res.get();
712
713 // Loading a __weak object implicitly retains the value, so we need a cleanup to
714 // balance that.
715 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
716 Cleanup.setExprNeedsCleanups(true);
717
718 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
719 Cleanup.setExprNeedsCleanups(true);
720
721 // C++ [conv.lval]p3:
722 // If T is cv std::nullptr_t, the result is a null pointer constant.
723 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
724 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
725 CurFPFeatureOverrides());
726
727 // C11 6.3.2.1p2:
728 // ... if the lvalue has atomic type, the value has the non-atomic version
729 // of the type of the lvalue ...
730 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
731 T = Atomic->getValueType().getUnqualifiedType();
732 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
733 nullptr, VK_PRValue, FPOptionsOverride());
734 }
735
736 return Res;
737}
738
739ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
740 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
741 if (Res.isInvalid())
742 return ExprError();
743 Res = DefaultLvalueConversion(Res.get());
744 if (Res.isInvalid())
745 return ExprError();
746 return Res;
747}
748
749/// CallExprUnaryConversions - a special case of an unary conversion
750/// performed on a function designator of a call expression.
751ExprResult Sema::CallExprUnaryConversions(Expr *E) {
752 QualType Ty = E->getType();
753 ExprResult Res = E;
754 // Only do implicit cast for a function type, but not for a pointer
755 // to function type.
756 if (Ty->isFunctionType()) {
757 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
758 CK_FunctionToPointerDecay);
759 if (Res.isInvalid())
760 return ExprError();
761 }
762 Res = DefaultLvalueConversion(Res.get());
763 if (Res.isInvalid())
764 return ExprError();
765 return Res.get();
766}
767
768/// UsualUnaryConversions - Performs various conversions that are common to most
769/// operators (C99 6.3). The conversions of array and function types are
770/// sometimes suppressed. For example, the array->pointer conversion doesn't
771/// apply if the array is an argument to the sizeof or address (&) operators.
772/// In these instances, this routine should *not* be called.
773ExprResult Sema::UsualUnaryConversions(Expr *E) {
774 // First, convert to an r-value.
775 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
776 if (Res.isInvalid())
777 return ExprError();
778 E = Res.get();
779
780 QualType Ty = E->getType();
781 assert(!Ty.isNull() && "UsualUnaryConversions - missing type")(static_cast <bool> (!Ty.isNull() && "UsualUnaryConversions - missing type"
) ? void (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\""
, "clang/lib/Sema/SemaExpr.cpp", 781, __extension__ __PRETTY_FUNCTION__
))
;
782
783 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
784 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
785 (getLangOpts().getFPEvalMethod() !=
786 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
787 PP.getLastFPEvalPragmaLocation().isValid())) {
788 switch (EvalMethod) {
789 default:
790 llvm_unreachable("Unrecognized float evaluation method")::llvm::llvm_unreachable_internal("Unrecognized float evaluation method"
, "clang/lib/Sema/SemaExpr.cpp", 790)
;
791 break;
792 case LangOptions::FEM_UnsetOnCommandLine:
793 llvm_unreachable("Float evaluation method should be set by now")::llvm::llvm_unreachable_internal("Float evaluation method should be set by now"
, "clang/lib/Sema/SemaExpr.cpp", 793)
;
794 break;
795 case LangOptions::FEM_Double:
796 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
797 // Widen the expression to double.
798 return Ty->isComplexType()
799 ? ImpCastExprToType(E,
800 Context.getComplexType(Context.DoubleTy),
801 CK_FloatingComplexCast)
802 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
803 break;
804 case LangOptions::FEM_Extended:
805 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
806 // Widen the expression to long double.
807 return Ty->isComplexType()
808 ? ImpCastExprToType(
809 E, Context.getComplexType(Context.LongDoubleTy),
810 CK_FloatingComplexCast)
811 : ImpCastExprToType(E, Context.LongDoubleTy,
812 CK_FloatingCast);
813 break;
814 }
815 }
816
817 // Half FP have to be promoted to float unless it is natively supported
818 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
819 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
820
821 // Try to perform integral promotions if the object has a theoretically
822 // promotable type.
823 if (Ty->isIntegralOrUnscopedEnumerationType()) {
824 // C99 6.3.1.1p2:
825 //
826 // The following may be used in an expression wherever an int or
827 // unsigned int may be used:
828 // - an object or expression with an integer type whose integer
829 // conversion rank is less than or equal to the rank of int
830 // and unsigned int.
831 // - A bit-field of type _Bool, int, signed int, or unsigned int.
832 //
833 // If an int can represent all values of the original type, the
834 // value is converted to an int; otherwise, it is converted to an
835 // unsigned int. These are called the integer promotions. All
836 // other types are unchanged by the integer promotions.
837
838 QualType PTy = Context.isPromotableBitField(E);
839 if (!PTy.isNull()) {
840 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
841 return E;
842 }
843 if (Context.isPromotableIntegerType(Ty)) {
844 QualType PT = Context.getPromotedIntegerType(Ty);
845 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
846 return E;
847 }
848 }
849 return E;
850}
851
852/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
853/// do not have a prototype. Arguments that have type float or __fp16
854/// are promoted to double. All other argument types are converted by
855/// UsualUnaryConversions().
856ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
857 QualType Ty = E->getType();
858 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultArgumentPromotion - missing type"
) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\""
, "clang/lib/Sema/SemaExpr.cpp", 858, __extension__ __PRETTY_FUNCTION__
))
;
859
860 ExprResult Res = UsualUnaryConversions(E);
861 if (Res.isInvalid())
862 return ExprError();
863 E = Res.get();
864
865 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
866 // promote to double.
867 // Note that default argument promotion applies only to float (and
868 // half/fp16); it does not apply to _Float16.
869 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
870 if (BTy && (BTy->getKind() == BuiltinType::Half ||
871 BTy->getKind() == BuiltinType::Float)) {
872 if (getLangOpts().OpenCL &&
873 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
874 if (BTy->getKind() == BuiltinType::Half) {
875 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
876 }
877 } else {
878 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
879 }
880 }
881 if (BTy &&
882 getLangOpts().getExtendIntArgs() ==
883 LangOptions::ExtendArgsKind::ExtendTo64 &&
884 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
885 Context.getTypeSizeInChars(BTy) <
886 Context.getTypeSizeInChars(Context.LongLongTy)) {
887 E = (Ty->isUnsignedIntegerType())
888 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
889 .get()
890 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
891 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&(static_cast <bool> (8 == Context.getTypeSizeInChars(Context
.LongLongTy).getQuantity() && "Unexpected typesize for LongLongTy"
) ? void (0) : __assert_fail ("8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && \"Unexpected typesize for LongLongTy\""
, "clang/lib/Sema/SemaExpr.cpp", 892, __extension__ __PRETTY_FUNCTION__
))
892 "Unexpected typesize for LongLongTy")(static_cast <bool> (8 == Context.getTypeSizeInChars(Context
.LongLongTy).getQuantity() && "Unexpected typesize for LongLongTy"
) ? void (0) : __assert_fail ("8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && \"Unexpected typesize for LongLongTy\""
, "clang/lib/Sema/SemaExpr.cpp", 892, __extension__ __PRETTY_FUNCTION__
))
;
893 }
894
895 // C++ performs lvalue-to-rvalue conversion as a default argument
896 // promotion, even on class types, but note:
897 // C++11 [conv.lval]p2:
898 // When an lvalue-to-rvalue conversion occurs in an unevaluated
899 // operand or a subexpression thereof the value contained in the
900 // referenced object is not accessed. Otherwise, if the glvalue
901 // has a class type, the conversion copy-initializes a temporary
902 // of type T from the glvalue and the result of the conversion
903 // is a prvalue for the temporary.
904 // FIXME: add some way to gate this entire thing for correctness in
905 // potentially potentially evaluated contexts.
906 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
907 ExprResult Temp = PerformCopyInitialization(
908 InitializedEntity::InitializeTemporary(E->getType()),
909 E->getExprLoc(), E);
910 if (Temp.isInvalid())
911 return ExprError();
912 E = Temp.get();
913 }
914
915 return E;
916}
917
918/// Determine the degree of POD-ness for an expression.
919/// Incomplete types are considered POD, since this check can be performed
920/// when we're in an unevaluated context.
921Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
922 if (Ty->isIncompleteType()) {
923 // C++11 [expr.call]p7:
924 // After these conversions, if the argument does not have arithmetic,
925 // enumeration, pointer, pointer to member, or class type, the program
926 // is ill-formed.
927 //
928 // Since we've already performed array-to-pointer and function-to-pointer
929 // decay, the only such type in C++ is cv void. This also handles
930 // initializer lists as variadic arguments.
931 if (Ty->isVoidType())
932 return VAK_Invalid;
933
934 if (Ty->isObjCObjectType())
935 return VAK_Invalid;
936 return VAK_Valid;
937 }
938
939 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
940 return VAK_Invalid;
941
942 if (Context.getTargetInfo().getTriple().isWasm() &&
943 Ty->isWebAssemblyReferenceType()) {
944 return VAK_Invalid;
945 }
946
947 if (Ty.isCXX98PODType(Context))
948 return VAK_Valid;
949
950 // C++11 [expr.call]p7:
951 // Passing a potentially-evaluated argument of class type (Clause 9)
952 // having a non-trivial copy constructor, a non-trivial move constructor,
953 // or a non-trivial destructor, with no corresponding parameter,
954 // is conditionally-supported with implementation-defined semantics.
955 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
956 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
957 if (!Record->hasNonTrivialCopyConstructor() &&
958 !Record->hasNonTrivialMoveConstructor() &&
959 !Record->hasNonTrivialDestructor())
960 return VAK_ValidInCXX11;
961
962 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
963 return VAK_Valid;
964
965 if (Ty->isObjCObjectType())
966 return VAK_Invalid;
967
968 if (getLangOpts().MSVCCompat)
969 return VAK_MSVCUndefined;
970
971 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
972 // permitted to reject them. We should consider doing so.
973 return VAK_Undefined;
974}
975
976void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
977 // Don't allow one to pass an Objective-C interface to a vararg.
978 const QualType &Ty = E->getType();
979 VarArgKind VAK = isValidVarArgType(Ty);
980
981 // Complain about passing non-POD types through varargs.
982 switch (VAK) {
983 case VAK_ValidInCXX11:
984 DiagRuntimeBehavior(
985 E->getBeginLoc(), nullptr,
986 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
987 [[fallthrough]];
988 case VAK_Valid:
989 if (Ty->isRecordType()) {
990 // This is unlikely to be what the user intended. If the class has a
991 // 'c_str' member function, the user probably meant to call that.
992 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
993 PDiag(diag::warn_pass_class_arg_to_vararg)
994 << Ty << CT << hasCStrMethod(E) << ".c_str()");
995 }
996 break;
997
998 case VAK_Undefined:
999 case VAK_MSVCUndefined:
1000 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1001 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1002 << getLangOpts().CPlusPlus11 << Ty << CT);
1003 break;
1004
1005 case VAK_Invalid:
1006 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1007 Diag(E->getBeginLoc(),
1008 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1009 << Ty << CT;
1010 else if (Ty->isObjCObjectType())
1011 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1012 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1013 << Ty << CT);
1014 else
1015 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1016 << isa<InitListExpr>(E) << Ty << CT;
1017 break;
1018 }
1019}
1020
1021/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1022/// will create a trap if the resulting type is not a POD type.
1023ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1024 FunctionDecl *FDecl) {
1025 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1026 // Strip the unbridged-cast placeholder expression off, if applicable.
1027 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1028 (CT == VariadicMethod ||
1029 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1030 E = stripARCUnbridgedCast(E);
1031
1032 // Otherwise, do normal placeholder checking.
1033 } else {
1034 ExprResult ExprRes = CheckPlaceholderExpr(E);
1035 if (ExprRes.isInvalid())
1036 return ExprError();
1037 E = ExprRes.get();
1038 }
1039 }
1040
1041 ExprResult ExprRes = DefaultArgumentPromotion(E);
1042 if (ExprRes.isInvalid())
1043 return ExprError();
1044
1045 // Copy blocks to the heap.
1046 if (ExprRes.get()->getType()->isBlockPointerType())
1047 maybeExtendBlockObject(ExprRes);
1048
1049 E = ExprRes.get();
1050
1051 // Diagnostics regarding non-POD argument types are
1052 // emitted along with format string checking in Sema::CheckFunctionCall().
1053 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1054 // Turn this into a trap.
1055 CXXScopeSpec SS;
1056 SourceLocation TemplateKWLoc;
1057 UnqualifiedId Name;
1058 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1059 E->getBeginLoc());
1060 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1061 /*HasTrailingLParen=*/true,
1062 /*IsAddressOfOperand=*/false);
1063 if (TrapFn.isInvalid())
1064 return ExprError();
1065
1066 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1067 std::nullopt, E->getEndLoc());
1068 if (Call.isInvalid())
1069 return ExprError();
1070
1071 ExprResult Comma =
1072 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1073 if (Comma.isInvalid())
1074 return ExprError();
1075 return Comma.get();
1076 }
1077
1078 if (!getLangOpts().CPlusPlus &&
1079 RequireCompleteType(E->getExprLoc(), E->getType(),
1080 diag::err_call_incomplete_argument))
1081 return ExprError();
1082
1083 return E;
1084}
1085
1086/// Converts an integer to complex float type. Helper function of
1087/// UsualArithmeticConversions()
1088///
1089/// \return false if the integer expression is an integer type and is
1090/// successfully converted to the complex type.
1091static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1092 ExprResult &ComplexExpr,
1093 QualType IntTy,
1094 QualType ComplexTy,
1095 bool SkipCast) {
1096 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1097 if (SkipCast) return false;
1098 if (IntTy->isIntegerType()) {
1099 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1100 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1101 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1102 CK_FloatingRealToComplex);
1103 } else {
1104 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "clang/lib/Sema/SemaExpr.cpp", 1104, __extension__ __PRETTY_FUNCTION__
))
;
1105 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1106 CK_IntegralComplexToFloatingComplex);
1107 }
1108 return false;
1109}
1110
1111// This handles complex/complex, complex/float, or float/complex.
1112// When both operands are complex, the shorter operand is converted to the
1113// type of the longer, and that is the type of the result. This corresponds
1114// to what is done when combining two real floating-point operands.
1115// The fun begins when size promotion occur across type domains.
1116// From H&S 6.3.4: When one operand is complex and the other is a real
1117// floating-point type, the less precise type is converted, within it's
1118// real or complex domain, to the precision of the other type. For example,
1119// when combining a "long double" with a "double _Complex", the
1120// "double _Complex" is promoted to "long double _Complex".
1121static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1122 QualType ShorterType,
1123 QualType LongerType,
1124 bool PromotePrecision) {
1125 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1126 QualType Result =
1127 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1128
1129 if (PromotePrecision) {
1130 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1131 Shorter =
1132 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1133 } else {
1134 if (LongerIsComplex)
1135 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1136 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1137 }
1138 }
1139 return Result;
1140}
1141
1142/// Handle arithmetic conversion with complex types. Helper function of
1143/// UsualArithmeticConversions()
1144static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1145 ExprResult &RHS, QualType LHSType,
1146 QualType RHSType, bool IsCompAssign) {
1147 // if we have an integer operand, the result is the complex type.
1148 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1149 /*SkipCast=*/false))
1150 return LHSType;
1151 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1152 /*SkipCast=*/IsCompAssign))
1153 return RHSType;
1154
1155 // Compute the rank of the two types, regardless of whether they are complex.
1156 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1157 if (Order < 0)
1158 // Promote the precision of the LHS if not an assignment.
1159 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1160 /*PromotePrecision=*/!IsCompAssign);
1161 // Promote the precision of the RHS unless it is already the same as the LHS.
1162 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1163 /*PromotePrecision=*/Order > 0);
1164}
1165
1166/// Handle arithmetic conversion from integer to float. Helper function
1167/// of UsualArithmeticConversions()
1168static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1169 ExprResult &IntExpr,
1170 QualType FloatTy, QualType IntTy,
1171 bool ConvertFloat, bool ConvertInt) {
1172 if (IntTy->isIntegerType()) {
1173 if (ConvertInt)
1174 // Convert intExpr to the lhs floating point type.
1175 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1176 CK_IntegralToFloating);
1177 return FloatTy;
1178 }
1179
1180 // Convert both sides to the appropriate complex float.
1181 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "clang/lib/Sema/SemaExpr.cpp", 1181, __extension__ __PRETTY_FUNCTION__
))
;
1182 QualType result = S.Context.getComplexType(FloatTy);
1183
1184 // _Complex int -> _Complex float
1185 if (ConvertInt)
1186 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1187 CK_IntegralComplexToFloatingComplex);
1188
1189 // float -> _Complex float
1190 if (ConvertFloat)
1191 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1192 CK_FloatingRealToComplex);
1193
1194 return result;
1195}
1196
1197/// Handle arithmethic conversion with floating point types. Helper
1198/// function of UsualArithmeticConversions()
1199static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1200 ExprResult &RHS, QualType LHSType,
1201 QualType RHSType, bool IsCompAssign) {
1202 bool LHSFloat = LHSType->isRealFloatingType();
1203 bool RHSFloat = RHSType->isRealFloatingType();
1204
1205 // N1169 4.1.4: If one of the operands has a floating type and the other
1206 // operand has a fixed-point type, the fixed-point operand
1207 // is converted to the floating type [...]
1208 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1209 if (LHSFloat)
1210 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1211 else if (!IsCompAssign)
1212 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1213 return LHSFloat ? LHSType : RHSType;
1214 }
1215
1216 // If we have two real floating types, convert the smaller operand
1217 // to the bigger result.
1218 if (LHSFloat && RHSFloat) {
1219 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1220 if (order > 0) {
1221 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1222 return LHSType;
1223 }
1224
1225 assert(order < 0 && "illegal float comparison")(static_cast <bool> (order < 0 && "illegal float comparison"
) ? void (0) : __assert_fail ("order < 0 && \"illegal float comparison\""
, "clang/lib/Sema/SemaExpr.cpp", 1225, __extension__ __PRETTY_FUNCTION__
))
;
1226 if (!IsCompAssign)
1227 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1228 return RHSType;
1229 }
1230
1231 if (LHSFloat) {
1232 // Half FP has to be promoted to float unless it is natively supported
1233 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1234 LHSType = S.Context.FloatTy;
1235
1236 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1237 /*ConvertFloat=*/!IsCompAssign,
1238 /*ConvertInt=*/ true);
1239 }
1240 assert(RHSFloat)(static_cast <bool> (RHSFloat) ? void (0) : __assert_fail
("RHSFloat", "clang/lib/Sema/SemaExpr.cpp", 1240, __extension__
__PRETTY_FUNCTION__))
;
1241 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1242 /*ConvertFloat=*/ true,
1243 /*ConvertInt=*/!IsCompAssign);
1244}
1245
1246/// Diagnose attempts to convert between __float128, __ibm128 and
1247/// long double if there is no support for such conversion.
1248/// Helper function of UsualArithmeticConversions().
1249static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1250 QualType RHSType) {
1251 // No issue if either is not a floating point type.
1252 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1253 return false;
1254
1255 // No issue if both have the same 128-bit float semantics.
1256 auto *LHSComplex = LHSType->getAs<ComplexType>();
1257 auto *RHSComplex = RHSType->getAs<ComplexType>();
1258
1259 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1260 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1261
1262 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1263 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1264
1265 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1266 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1267 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1268 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1269 return false;
1270
1271 return true;
1272}
1273
1274typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1275
1276namespace {
1277/// These helper callbacks are placed in an anonymous namespace to
1278/// permit their use as function template parameters.
1279ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1280 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1281}
1282
1283ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1284 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1285 CK_IntegralComplexCast);
1286}
1287}
1288
1289/// Handle integer arithmetic conversions. Helper function of
1290/// UsualArithmeticConversions()
1291template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1292static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1293 ExprResult &RHS, QualType LHSType,
1294 QualType RHSType, bool IsCompAssign) {
1295 // The rules for this case are in C99 6.3.1.8
1296 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1297 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1298 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1299 if (LHSSigned == RHSSigned) {
1300 // Same signedness; use the higher-ranked type
1301 if (order >= 0) {
1302 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1303 return LHSType;
1304 } else if (!IsCompAssign)
1305 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1306 return RHSType;
1307 } else if (order != (LHSSigned ? 1 : -1)) {
1308 // The unsigned type has greater than or equal rank to the
1309 // signed type, so use the unsigned type
1310 if (RHSSigned) {
1311 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1312 return LHSType;
1313 } else if (!IsCompAssign)
1314 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1315 return RHSType;
1316 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1317 // The two types are different widths; if we are here, that
1318 // means the signed type is larger than the unsigned type, so
1319 // use the signed type.
1320 if (LHSSigned) {
1321 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1322 return LHSType;
1323 } else if (!IsCompAssign)
1324 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1325 return RHSType;
1326 } else {
1327 // The signed type is higher-ranked than the unsigned type,
1328 // but isn't actually any bigger (like unsigned int and long
1329 // on most 32-bit systems). Use the unsigned type corresponding
1330 // to the signed type.
1331 QualType result =
1332 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1333 RHS = (*doRHSCast)(S, RHS.get(), result);
1334 if (!IsCompAssign)
1335 LHS = (*doLHSCast)(S, LHS.get(), result);
1336 return result;
1337 }
1338}
1339
1340/// Handle conversions with GCC complex int extension. Helper function
1341/// of UsualArithmeticConversions()
1342static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1343 ExprResult &RHS, QualType LHSType,
1344 QualType RHSType,
1345 bool IsCompAssign) {
1346 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1347 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1348
1349 if (LHSComplexInt && RHSComplexInt) {
1350 QualType LHSEltType = LHSComplexInt->getElementType();
1351 QualType RHSEltType = RHSComplexInt->getElementType();
1352 QualType ScalarType =
1353 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1354 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1355
1356 return S.Context.getComplexType(ScalarType);
1357 }
1358
1359 if (LHSComplexInt) {
1360 QualType LHSEltType = LHSComplexInt->getElementType();
1361 QualType ScalarType =
1362 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1363 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1364 QualType ComplexType = S.Context.getComplexType(ScalarType);
1365 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1366 CK_IntegralRealToComplex);
1367
1368 return ComplexType;
1369 }
1370
1371 assert(RHSComplexInt)(static_cast <bool> (RHSComplexInt) ? void (0) : __assert_fail
("RHSComplexInt", "clang/lib/Sema/SemaExpr.cpp", 1371, __extension__
__PRETTY_FUNCTION__))
;
1372
1373 QualType RHSEltType = RHSComplexInt->getElementType();
1374 QualType ScalarType =
1375 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1376 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1377 QualType ComplexType = S.Context.getComplexType(ScalarType);
1378
1379 if (!IsCompAssign)
1380 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1381 CK_IntegralRealToComplex);
1382 return ComplexType;
1383}
1384
1385/// Return the rank of a given fixed point or integer type. The value itself
1386/// doesn't matter, but the values must be increasing with proper increasing
1387/// rank as described in N1169 4.1.1.
1388static unsigned GetFixedPointRank(QualType Ty) {
1389 const auto *BTy = Ty->getAs<BuiltinType>();
1390 assert(BTy && "Expected a builtin type.")(static_cast <bool> (BTy && "Expected a builtin type."
) ? void (0) : __assert_fail ("BTy && \"Expected a builtin type.\""
, "clang/lib/Sema/SemaExpr.cpp", 1390, __extension__ __PRETTY_FUNCTION__
))
;
1391
1392 switch (BTy->getKind()) {
1393 case BuiltinType::ShortFract:
1394 case BuiltinType::UShortFract:
1395 case BuiltinType::SatShortFract:
1396 case BuiltinType::SatUShortFract:
1397 return 1;
1398 case BuiltinType::Fract:
1399 case BuiltinType::UFract:
1400 case BuiltinType::SatFract:
1401 case BuiltinType::SatUFract:
1402 return 2;
1403 case BuiltinType::LongFract:
1404 case BuiltinType::ULongFract:
1405 case BuiltinType::SatLongFract:
1406 case BuiltinType::SatULongFract:
1407 return 3;
1408 case BuiltinType::ShortAccum:
1409 case BuiltinType::UShortAccum:
1410 case BuiltinType::SatShortAccum:
1411 case BuiltinType::SatUShortAccum:
1412 return 4;
1413 case BuiltinType::Accum:
1414 case BuiltinType::UAccum:
1415 case BuiltinType::SatAccum:
1416 case BuiltinType::SatUAccum:
1417 return 5;
1418 case BuiltinType::LongAccum:
1419 case BuiltinType::ULongAccum:
1420 case BuiltinType::SatLongAccum:
1421 case BuiltinType::SatULongAccum:
1422 return 6;
1423 default:
1424 if (BTy->isInteger())
1425 return 0;
1426 llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type"
, "clang/lib/Sema/SemaExpr.cpp", 1426)
;
1427 }
1428}
1429
1430/// handleFixedPointConversion - Fixed point operations between fixed
1431/// point types and integers or other fixed point types do not fall under
1432/// usual arithmetic conversion since these conversions could result in loss
1433/// of precsision (N1169 4.1.4). These operations should be calculated with
1434/// the full precision of their result type (N1169 4.1.6.2.1).
1435static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1436 QualType RHSTy) {
1437 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(static_cast <bool> ((LHSTy->isFixedPointType() || RHSTy
->isFixedPointType()) && "Expected at least one of the operands to be a fixed point type"
) ? void (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "clang/lib/Sema/SemaExpr.cpp", 1438, __extension__ __PRETTY_FUNCTION__
))
1438 "Expected at least one of the operands to be a fixed point type")(static_cast <bool> ((LHSTy->isFixedPointType() || RHSTy
->isFixedPointType()) && "Expected at least one of the operands to be a fixed point type"
) ? void (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "clang/lib/Sema/SemaExpr.cpp", 1438, __extension__ __PRETTY_FUNCTION__
))
;
1439 assert((LHSTy->isFixedPointOrIntegerType() ||(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType
() || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? void (0) : __assert_fail
("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "clang/lib/Sema/SemaExpr.cpp", 1442, __extension__ __PRETTY_FUNCTION__
))
1440 RHSTy->isFixedPointOrIntegerType()) &&(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType
() || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? void (0) : __assert_fail
("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "clang/lib/Sema/SemaExpr.cpp", 1442, __extension__ __PRETTY_FUNCTION__
))
1441 "Special fixed point arithmetic operation conversions are only "(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType
() || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? void (0) : __assert_fail
("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "clang/lib/Sema/SemaExpr.cpp", 1442, __extension__ __PRETTY_FUNCTION__
))
1442 "applied to ints or other fixed point types")(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType
() || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? void (0) : __assert_fail
("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "clang/lib/Sema/SemaExpr.cpp", 1442, __extension__ __PRETTY_FUNCTION__
))
;
1443
1444 // If one operand has signed fixed-point type and the other operand has
1445 // unsigned fixed-point type, then the unsigned fixed-point operand is
1446 // converted to its corresponding signed fixed-point type and the resulting
1447 // type is the type of the converted operand.
1448 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1449 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1450 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1451 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1452
1453 // The result type is the type with the highest rank, whereby a fixed-point
1454 // conversion rank is always greater than an integer conversion rank; if the
1455 // type of either of the operands is a saturating fixedpoint type, the result
1456 // type shall be the saturating fixed-point type corresponding to the type
1457 // with the highest rank; the resulting value is converted (taking into
1458 // account rounding and overflow) to the precision of the resulting type.
1459 // Same ranks between signed and unsigned types are resolved earlier, so both
1460 // types are either signed or both unsigned at this point.
1461 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1462 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1463
1464 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1465
1466 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1467 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1468
1469 return ResultTy;
1470}
1471
1472/// Check that the usual arithmetic conversions can be performed on this pair of
1473/// expressions that might be of enumeration type.
1474static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1475 SourceLocation Loc,
1476 Sema::ArithConvKind ACK) {
1477 // C++2a [expr.arith.conv]p1:
1478 // If one operand is of enumeration type and the other operand is of a
1479 // different enumeration type or a floating-point type, this behavior is
1480 // deprecated ([depr.arith.conv.enum]).
1481 //
1482 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1483 // Eventually we will presumably reject these cases (in C++23 onwards?).
1484 QualType L = LHS->getType(), R = RHS->getType();
1485 bool LEnum = L->isUnscopedEnumerationType(),
1486 REnum = R->isUnscopedEnumerationType();
1487 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1488 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1489 (REnum && L->isFloatingType())) {
1490 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1491 ? diag::warn_arith_conv_enum_float_cxx20
1492 : diag::warn_arith_conv_enum_float)
1493 << LHS->getSourceRange() << RHS->getSourceRange()
1494 << (int)ACK << LEnum << L << R;
1495 } else if (!IsCompAssign && LEnum && REnum &&
1496 !S.Context.hasSameUnqualifiedType(L, R)) {
1497 unsigned DiagID;
1498 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1499 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1500 // If either enumeration type is unnamed, it's less likely that the
1501 // user cares about this, but this situation is still deprecated in
1502 // C++2a. Use a different warning group.
1503 DiagID = S.getLangOpts().CPlusPlus20
1504 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1505 : diag::warn_arith_conv_mixed_anon_enum_types;
1506 } else if (ACK == Sema::ACK_Conditional) {
1507 // Conditional expressions are separated out because they have
1508 // historically had a different warning flag.
1509 DiagID = S.getLangOpts().CPlusPlus20
1510 ? diag::warn_conditional_mixed_enum_types_cxx20
1511 : diag::warn_conditional_mixed_enum_types;
1512 } else if (ACK == Sema::ACK_Comparison) {
1513 // Comparison expressions are separated out because they have
1514 // historically had a different warning flag.
1515 DiagID = S.getLangOpts().CPlusPlus20
1516 ? diag::warn_comparison_mixed_enum_types_cxx20
1517 : diag::warn_comparison_mixed_enum_types;
1518 } else {
1519 DiagID = S.getLangOpts().CPlusPlus20
1520 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1521 : diag::warn_arith_conv_mixed_enum_types;
1522 }
1523 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1524 << (int)ACK << L << R;
1525 }
1526}
1527
1528/// UsualArithmeticConversions - Performs various conversions that are common to
1529/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1530/// routine returns the first non-arithmetic type found. The client is
1531/// responsible for emitting appropriate error diagnostics.
1532QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1533 SourceLocation Loc,
1534 ArithConvKind ACK) {
1535 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1536
1537 if (ACK != ACK_CompAssign) {
1538 LHS = UsualUnaryConversions(LHS.get());
1539 if (LHS.isInvalid())
1540 return QualType();
1541 }
1542
1543 RHS = UsualUnaryConversions(RHS.get());
1544 if (RHS.isInvalid())
1545 return QualType();
1546
1547 // For conversion purposes, we ignore any qualifiers.
1548 // For example, "const float" and "float" are equivalent.
1549 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1550 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1551
1552 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1553 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1554 LHSType = AtomicLHS->getValueType();
1555
1556 // If both types are identical, no conversion is needed.
1557 if (Context.hasSameType(LHSType, RHSType))
1558 return Context.getCommonSugaredType(LHSType, RHSType);
1559
1560 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1561 // The caller can deal with this (e.g. pointer + int).
1562 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1563 return QualType();
1564
1565 // Apply unary and bitfield promotions to the LHS's type.
1566 QualType LHSUnpromotedType = LHSType;
1567 if (Context.isPromotableIntegerType(LHSType))
1568 LHSType = Context.getPromotedIntegerType(LHSType);
1569 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1570 if (!LHSBitfieldPromoteTy.isNull())
1571 LHSType = LHSBitfieldPromoteTy;
1572 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1573 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1574
1575 // If both types are identical, no conversion is needed.
1576 if (Context.hasSameType(LHSType, RHSType))
1577 return Context.getCommonSugaredType(LHSType, RHSType);
1578
1579 // At this point, we have two different arithmetic types.
1580
1581 // Diagnose attempts to convert between __ibm128, __float128 and long double
1582 // where such conversions currently can't be handled.
1583 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1584 return QualType();
1585
1586 // Handle complex types first (C99 6.3.1.8p1).
1587 if (LHSType->isComplexType() || RHSType->isComplexType())
1588 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1589 ACK == ACK_CompAssign);
1590
1591 // Now handle "real" floating types (i.e. float, double, long double).
1592 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1593 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1594 ACK == ACK_CompAssign);
1595
1596 // Handle GCC complex int extension.
1597 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1598 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1599 ACK == ACK_CompAssign);
1600
1601 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1602 return handleFixedPointConversion(*this, LHSType, RHSType);
1603
1604 // Finally, we have two differing integer types.
1605 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1606 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1607}
1608
1609//===----------------------------------------------------------------------===//
1610// Semantic Analysis for various Expression Types
1611//===----------------------------------------------------------------------===//
1612
1613
1614ExprResult
1615Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1616 SourceLocation DefaultLoc,
1617 SourceLocation RParenLoc,
1618 Expr *ControllingExpr,
1619 ArrayRef<ParsedType> ArgTypes,
1620 ArrayRef<Expr *> ArgExprs) {
1621 unsigned NumAssocs = ArgTypes.size();
1622 assert(NumAssocs == ArgExprs.size())(static_cast <bool> (NumAssocs == ArgExprs.size()) ? void
(0) : __assert_fail ("NumAssocs == ArgExprs.size()", "clang/lib/Sema/SemaExpr.cpp"
, 1622, __extension__ __PRETTY_FUNCTION__))
;
1623
1624 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1625 for (unsigned i = 0; i < NumAssocs; ++i) {
1626 if (ArgTypes[i])
1627 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1628 else
1629 Types[i] = nullptr;
1630 }
1631
1632 ExprResult ER =
1633 CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, ControllingExpr,
1634 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1635 delete [] Types;
1636 return ER;
1637}
1638
1639ExprResult
1640Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1641 SourceLocation DefaultLoc,
1642 SourceLocation RParenLoc,
1643 Expr *ControllingExpr,
1644 ArrayRef<TypeSourceInfo *> Types,
1645 ArrayRef<Expr *> Exprs) {
1646 unsigned NumAssocs = Types.size();
1647 assert(NumAssocs == Exprs.size())(static_cast <bool> (NumAssocs == Exprs.size()) ? void (
0) : __assert_fail ("NumAssocs == Exprs.size()", "clang/lib/Sema/SemaExpr.cpp"
, 1647, __extension__ __PRETTY_FUNCTION__))
;
1648
1649 // Decay and strip qualifiers for the controlling expression type, and handle
1650 // placeholder type replacement. See committee discussion from WG14 DR423.
1651 {
1652 EnterExpressionEvaluationContext Unevaluated(
1653 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1654 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1655 if (R.isInvalid())
1656 return ExprError();
1657 ControllingExpr = R.get();
1658 }
1659
1660 bool TypeErrorFound = false,
1661 IsResultDependent = ControllingExpr->isTypeDependent(),
1662 ContainsUnexpandedParameterPack
1663 = ControllingExpr->containsUnexpandedParameterPack();
1664
1665 // The controlling expression is an unevaluated operand, so side effects are
1666 // likely unintended.
1667 if (!inTemplateInstantiation() && !IsResultDependent &&
1668 ControllingExpr->HasSideEffects(Context, false))
1669 Diag(ControllingExpr->getExprLoc(),
1670 diag::warn_side_effects_unevaluated_context);
1671
1672 for (unsigned i = 0; i < NumAssocs; ++i) {
1673 if (Exprs[i]->containsUnexpandedParameterPack())
1674 ContainsUnexpandedParameterPack = true;
1675
1676 if (Types[i]) {
1677 if (Types[i]->getType()->containsUnexpandedParameterPack())
1678 ContainsUnexpandedParameterPack = true;
1679
1680 if (Types[i]->getType()->isDependentType()) {
1681 IsResultDependent = true;
1682 } else {
1683 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1684 // complete object type other than a variably modified type."
1685 unsigned D = 0;
1686 if (Types[i]->getType()->isIncompleteType())
1687 D = diag::err_assoc_type_incomplete;
1688 else if (!Types[i]->getType()->isObjectType())
1689 D = diag::err_assoc_type_nonobject;
1690 else if (Types[i]->getType()->isVariablyModifiedType())
1691 D = diag::err_assoc_type_variably_modified;
1692 else {
1693 // Because the controlling expression undergoes lvalue conversion,
1694 // array conversion, and function conversion, an association which is
1695 // of array type, function type, or is qualified can never be
1696 // reached. We will warn about this so users are less surprised by
1697 // the unreachable association. However, we don't have to handle
1698 // function types; that's not an object type, so it's handled above.
1699 //
1700 // The logic is somewhat different for C++ because C++ has different
1701 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1702 // If T is a non-class type, the type of the prvalue is the cv-
1703 // unqualified version of T. Otherwise, the type of the prvalue is T.
1704 // The result of these rules is that all qualified types in an
1705 // association in C are unreachable, and in C++, only qualified non-
1706 // class types are unreachable.
1707 unsigned Reason = 0;
1708 QualType QT = Types[i]->getType();
1709 if (QT->isArrayType())
1710 Reason = 1;
1711 else if (QT.hasQualifiers() &&
1712 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1713 Reason = 2;
1714
1715 if (Reason)
1716 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1717 diag::warn_unreachable_association)
1718 << QT << (Reason - 1);
1719 }
1720
1721 if (D != 0) {
1722 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1723 << Types[i]->getTypeLoc().getSourceRange()
1724 << Types[i]->getType();
1725 TypeErrorFound = true;
1726 }
1727
1728 // C11 6.5.1.1p2 "No two generic associations in the same generic
1729 // selection shall specify compatible types."
1730 for (unsigned j = i+1; j < NumAssocs; ++j)
1731 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1732 Context.typesAreCompatible(Types[i]->getType(),
1733 Types[j]->getType())) {
1734 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1735 diag::err_assoc_compatible_types)
1736 << Types[j]->getTypeLoc().getSourceRange()
1737 << Types[j]->getType()
1738 << Types[i]->getType();
1739 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1740 diag::note_compat_assoc)
1741 << Types[i]->getTypeLoc().getSourceRange()
1742 << Types[i]->getType();
1743 TypeErrorFound = true;
1744 }
1745 }
1746 }
1747 }
1748 if (TypeErrorFound)
1749 return ExprError();
1750
1751 // If we determined that the generic selection is result-dependent, don't
1752 // try to compute the result expression.
1753 if (IsResultDependent)
1754 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1755 Exprs, DefaultLoc, RParenLoc,
1756 ContainsUnexpandedParameterPack);
1757
1758 SmallVector<unsigned, 1> CompatIndices;
1759 unsigned DefaultIndex = -1U;
1760 // Look at the canonical type of the controlling expression in case it was a
1761 // deduced type like __auto_type. However, when issuing diagnostics, use the
1762 // type the user wrote in source rather than the canonical one.
1763 for (unsigned i = 0; i < NumAssocs; ++i) {
1764 if (!Types[i])
1765 DefaultIndex = i;
1766 else if (Context.typesAreCompatible(
1767 ControllingExpr->getType().getCanonicalType(),
1768 Types[i]->getType()))
1769 CompatIndices.push_back(i);
1770 }
1771
1772 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1773 // type compatible with at most one of the types named in its generic
1774 // association list."
1775 if (CompatIndices.size() > 1) {
1776 // We strip parens here because the controlling expression is typically
1777 // parenthesized in macro definitions.
1778 ControllingExpr = ControllingExpr->IgnoreParens();
1779 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1780 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1781 << (unsigned)CompatIndices.size();
1782 for (unsigned I : CompatIndices) {
1783 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1784 diag::note_compat_assoc)
1785 << Types[I]->getTypeLoc().getSourceRange()
1786 << Types[I]->getType();
1787 }
1788 return ExprError();
1789 }
1790
1791 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1792 // its controlling expression shall have type compatible with exactly one of
1793 // the types named in its generic association list."
1794 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1795 // We strip parens here because the controlling expression is typically
1796 // parenthesized in macro definitions.
1797 ControllingExpr = ControllingExpr->IgnoreParens();
1798 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1799 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1800 return ExprError();
1801 }
1802
1803 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1804 // type name that is compatible with the type of the controlling expression,
1805 // then the result expression of the generic selection is the expression
1806 // in that generic association. Otherwise, the result expression of the
1807 // generic selection is the expression in the default generic association."
1808 unsigned ResultIndex =
1809 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1810
1811 return GenericSelectionExpr::Create(
1812 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1813 ContainsUnexpandedParameterPack, ResultIndex);
1814}
1815
1816/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1817/// location of the token and the offset of the ud-suffix within it.
1818static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1819 unsigned Offset) {
1820 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1821 S.getLangOpts());
1822}
1823
1824/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1825/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1826static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1827 IdentifierInfo *UDSuffix,
1828 SourceLocation UDSuffixLoc,
1829 ArrayRef<Expr*> Args,
1830 SourceLocation LitEndLoc) {
1831 assert(Args.size() <= 2 && "too many arguments for literal operator")(static_cast <bool> (Args.size() <= 2 && "too many arguments for literal operator"
) ? void (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\""
, "clang/lib/Sema/SemaExpr.cpp", 1831, __extension__ __PRETTY_FUNCTION__
))
;
1832
1833 QualType ArgTy[2];
1834 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1835 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1836 if (ArgTy[ArgIdx]->isArrayType())
1837 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1838 }
1839
1840 DeclarationName OpName =
1841 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1842 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1843 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1844
1845 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1846 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1847 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1848 /*AllowStringTemplatePack*/ false,
1849 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1850 return ExprError();
1851
1852 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1853}
1854
1855/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1856/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1857/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1858/// multiple tokens. However, the common case is that StringToks points to one
1859/// string.
1860///
1861ExprResult
1862Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1863 assert(!StringToks.empty() && "Must have at least one string!")(static_cast <bool> (!StringToks.empty() && "Must have at least one string!"
) ? void (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\""
, "clang/lib/Sema/SemaExpr.cpp", 1863, __extension__ __PRETTY_FUNCTION__
))
;
1864
1865 StringLiteralParser Literal(StringToks, PP);
1866 if (Literal.hadError)
1867 return ExprError();
1868
1869 SmallVector<SourceLocation, 4> StringTokLocs;
1870 for (const Token &Tok : StringToks)
1871 StringTokLocs.push_back(Tok.getLocation());
1872
1873 QualType CharTy = Context.CharTy;
1874 StringLiteral::StringKind Kind = StringLiteral::Ordinary;
1875 if (Literal.isWide()) {
1876 CharTy = Context.getWideCharType();
1877 Kind = StringLiteral::Wide;
1878 } else if (Literal.isUTF8()) {
1879 if (getLangOpts().Char8)
1880 CharTy = Context.Char8Ty;
1881 Kind = StringLiteral::UTF8;
1882 } else if (Literal.isUTF16()) {
1883 CharTy = Context.Char16Ty;
1884 Kind = StringLiteral::UTF16;
1885 } else if (Literal.isUTF32()) {
1886 CharTy = Context.Char32Ty;
1887 Kind = StringLiteral::UTF32;
1888 } else if (Literal.isPascal()) {
1889 CharTy = Context.UnsignedCharTy;
1890 }
1891
1892 // Warn on initializing an array of char from a u8 string literal; this
1893 // becomes ill-formed in C++2a.
1894 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1895 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1896 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1897
1898 // Create removals for all 'u8' prefixes in the string literal(s). This
1899 // ensures C++2a compatibility (but may change the program behavior when
1900 // built by non-Clang compilers for which the execution character set is
1901 // not always UTF-8).
1902 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1903 SourceLocation RemovalDiagLoc;
1904 for (const Token &Tok : StringToks) {
1905 if (Tok.getKind() == tok::utf8_string_literal) {
1906 if (RemovalDiagLoc.isInvalid())
1907 RemovalDiagLoc = Tok.getLocation();
1908 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1909 Tok.getLocation(),
1910 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1911 getSourceManager(), getLangOpts())));
1912 }
1913 }
1914 Diag(RemovalDiagLoc, RemovalDiag);
1915 }
1916
1917 QualType StrTy =
1918 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1919
1920 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1921 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1922 Kind, Literal.Pascal, StrTy,
1923 &StringTokLocs[0],
1924 StringTokLocs.size());
1925 if (Literal.getUDSuffix().empty())
1926 return Lit;
1927
1928 // We're building a user-defined literal.
1929 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1930 SourceLocation UDSuffixLoc =
1931 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1932 Literal.getUDSuffixOffset());
1933
1934 // Make sure we're allowed user-defined literals here.
1935 if (!UDLScope)
1936 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1937
1938 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1939 // operator "" X (str, len)
1940 QualType SizeType = Context.getSizeType();
1941
1942 DeclarationName OpName =
1943 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1944 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1945 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1946
1947 QualType ArgTy[] = {
1948 Context.getArrayDecayedType(StrTy), SizeType
1949 };
1950
1951 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1952 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1953 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1954 /*AllowStringTemplatePack*/ true,
1955 /*DiagnoseMissing*/ true, Lit)) {
1956
1957 case LOLR_Cooked: {
1958 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1959 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1960 StringTokLocs[0]);
1961 Expr *Args[] = { Lit, LenArg };
1962
1963 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1964 }
1965
1966 case LOLR_Template: {
1967 TemplateArgumentListInfo ExplicitArgs;
1968 TemplateArgument Arg(Lit);
1969 TemplateArgumentLocInfo ArgInfo(Lit);
1970 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1971 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
1972 StringTokLocs.back(), &ExplicitArgs);
1973 }
1974
1975 case LOLR_StringTemplatePack: {
1976 TemplateArgumentListInfo ExplicitArgs;
1977
1978 unsigned CharBits = Context.getIntWidth(CharTy);
1979 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1980 llvm::APSInt Value(CharBits, CharIsUnsigned);
1981
1982 TemplateArgument TypeArg(CharTy);
1983 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1984 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1985
1986 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1987 Value = Lit->getCodeUnit(I);
1988 TemplateArgument Arg(Context, Value, CharTy);
1989 TemplateArgumentLocInfo ArgInfo;
1990 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1991 }
1992 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
1993 StringTokLocs.back(), &ExplicitArgs);
1994 }
1995 case LOLR_Raw:
1996 case LOLR_ErrorNoDiagnostic:
1997 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 1997)
;
1998 case LOLR_Error:
1999 return ExprError();
2000 }
2001 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 2001)
;
2002}
2003
2004DeclRefExpr *
2005Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2006 SourceLocation Loc,
2007 const CXXScopeSpec *SS) {
2008 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2009 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2010}
2011
2012DeclRefExpr *
2013Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2014 const DeclarationNameInfo &NameInfo,
2015 const CXXScopeSpec *SS, NamedDecl *FoundD,
2016 SourceLocation TemplateKWLoc,
2017 const TemplateArgumentListInfo *TemplateArgs) {
2018 NestedNameSpecifierLoc NNS =
2019 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2020 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2021 TemplateArgs);
2022}
2023
2024// CUDA/HIP: Check whether a captured reference variable is referencing a
2025// host variable in a device or host device lambda.
2026static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2027 VarDecl *VD) {
2028 if (!S.getLangOpts().CUDA || !VD->hasInit())
2029 return false;
2030 assert(VD->getType()->isReferenceType())(static_cast <bool> (VD->getType()->isReferenceType
()) ? void (0) : __assert_fail ("VD->getType()->isReferenceType()"
, "clang/lib/Sema/SemaExpr.cpp", 2030, __extension__ __PRETTY_FUNCTION__
))
;
2031
2032 // Check whether the reference variable is referencing a host variable.
2033 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2034 if (!DRE)
2035 return false;
2036 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2037 if (!Referee || !Referee->hasGlobalStorage() ||
2038 Referee->hasAttr<CUDADeviceAttr>())
2039 return false;
2040
2041 // Check whether the current function is a device or host device lambda.
2042 // Check whether the reference variable is a capture by getDeclContext()
2043 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2044 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2045 if (MD && MD->getParent()->isLambda() &&
2046 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2047 VD->getDeclContext() != MD)
2048 return true;
2049
2050 return false;
2051}
2052
2053NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2054 // A declaration named in an unevaluated operand never constitutes an odr-use.
2055 if (isUnevaluatedContext())
2056 return NOUR_Unevaluated;
2057
2058 // C++2a [basic.def.odr]p4:
2059 // A variable x whose name appears as a potentially-evaluated expression e
2060 // is odr-used by e unless [...] x is a reference that is usable in
2061 // constant expressions.
2062 // CUDA/HIP:
2063 // If a reference variable referencing a host variable is captured in a
2064 // device or host device lambda, the value of the referee must be copied
2065 // to the capture and the reference variable must be treated as odr-use
2066 // since the value of the referee is not known at compile time and must
2067 // be loaded from the captured.
2068 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2069 if (VD->getType()->isReferenceType() &&
2070 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2071 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2072 VD->isUsableInConstantExpressions(Context))
2073 return NOUR_Constant;
2074 }
2075
2076 // All remaining non-variable cases constitute an odr-use. For variables, we
2077 // need to wait and see how the expression is used.
2078 return NOUR_None;
2079}
2080
2081/// BuildDeclRefExpr - Build an expression that references a
2082/// declaration that does not require a closure capture.
2083DeclRefExpr *
2084Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2085 const DeclarationNameInfo &NameInfo,
2086 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2087 SourceLocation TemplateKWLoc,
2088 const TemplateArgumentListInfo *TemplateArgs) {
2089 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2090 NeedToCaptureVariable(D, NameInfo.getLoc());
2091
2092 DeclRefExpr *E = DeclRefExpr::Create(
2093 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2094 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2095 MarkDeclRefReferenced(E);
2096
2097 // C++ [except.spec]p17:
2098 // An exception-specification is considered to be needed when:
2099 // - in an expression, the function is the unique lookup result or
2100 // the selected member of a set of overloaded functions.
2101 //
2102 // We delay doing this until after we've built the function reference and
2103 // marked it as used so that:
2104 // a) if the function is defaulted, we get errors from defining it before /
2105 // instead of errors from computing its exception specification, and
2106 // b) if the function is a defaulted comparison, we can use the body we
2107 // build when defining it as input to the exception specification
2108 // computation rather than computing a new body.
2109 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2110 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2111 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2112 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2113 }
2114 }
2115
2116 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2117 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2118 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2119 getCurFunction()->recordUseOfWeak(E);
2120
2121 const auto *FD = dyn_cast<FieldDecl>(D);
2122 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2123 FD = IFD->getAnonField();
2124 if (FD) {
2125 UnusedPrivateFields.remove(FD);
2126 // Just in case we're building an illegal pointer-to-member.
2127 if (FD->isBitField())
2128 E->setObjectKind(OK_BitField);
2129 }
2130
2131 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2132 // designates a bit-field.
2133 if (const auto *BD = dyn_cast<BindingDecl>(D))
2134 if (const auto *BE = BD->getBinding())
2135 E->setObjectKind(BE->getObjectKind());
2136
2137 return E;
2138}
2139
2140/// Decomposes the given name into a DeclarationNameInfo, its location, and
2141/// possibly a list of template arguments.
2142///
2143/// If this produces template arguments, it is permitted to call
2144/// DecomposeTemplateName.
2145///
2146/// This actually loses a lot of source location information for
2147/// non-standard name kinds; we should consider preserving that in
2148/// some way.
2149void
2150Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2151 TemplateArgumentListInfo &Buffer,
2152 DeclarationNameInfo &NameInfo,
2153 const TemplateArgumentListInfo *&TemplateArgs) {
2154 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2155 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2156 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2157
2158 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2159 Id.TemplateId->NumArgs);
2160 translateTemplateArguments(TemplateArgsPtr, Buffer);
2161
2162 TemplateName TName = Id.TemplateId->Template.get();
2163 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2164 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2165 TemplateArgs = &Buffer;
2166 } else {
2167 NameInfo = GetNameFromUnqualifiedId(Id);
2168 TemplateArgs = nullptr;
2169 }
2170}
2171
2172static void emitEmptyLookupTypoDiagnostic(
2173 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2174 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2175 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2176 DeclContext *Ctx =
2177 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2178 if (!TC) {
2179 // Emit a special diagnostic for failed member lookups.
2180 // FIXME: computing the declaration context might fail here (?)
2181 if (Ctx)
2182 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2183 << SS.getRange();
2184 else
2185 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2186 return;
2187 }
2188
2189 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2190 bool DroppedSpecifier =
2191 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2192 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2193 ? diag::note_implicit_param_decl
2194 : diag::note_previous_decl;
2195 if (!Ctx)
2196 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2197 SemaRef.PDiag(NoteID));
2198 else
2199 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2200 << Typo << Ctx << DroppedSpecifier
2201 << SS.getRange(),
2202 SemaRef.PDiag(NoteID));
2203}
2204
2205/// Diagnose a lookup that found results in an enclosing class during error
2206/// recovery. This usually indicates that the results were found in a dependent
2207/// base class that could not be searched as part of a template definition.
2208/// Always issues a diagnostic (though this may be only a warning in MS
2209/// compatibility mode).
2210///
2211/// Return \c true if the error is unrecoverable, or \c false if the caller
2212/// should attempt to recover using these lookup results.
2213bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2214 // During a default argument instantiation the CurContext points
2215 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2216 // function parameter list, hence add an explicit check.
2217 bool isDefaultArgument =
2218 !CodeSynthesisContexts.empty() &&
2219 CodeSynthesisContexts.back().Kind ==
2220 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2221 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2222 bool isInstance = CurMethod && CurMethod->isInstance() &&
2223 R.getNamingClass() == CurMethod->getParent() &&
2224 !isDefaultArgument;
2225
2226 // There are two ways we can find a class-scope declaration during template
2227 // instantiation that we did not find in the template definition: if it is a
2228 // member of a dependent base class, or if it is declared after the point of
2229 // use in the same class. Distinguish these by comparing the class in which
2230 // the member was found to the naming class of the lookup.
2231 unsigned DiagID = diag::err_found_in_dependent_base;
2232 unsigned NoteID = diag::note_member_declared_at;
2233 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2234 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2235 : diag::err_found_later_in_class;
2236 } else if (getLangOpts().MSVCCompat) {
2237 DiagID = diag::ext_found_in_dependent_base;
2238 NoteID = diag::note_dependent_member_use;
2239 }
2240
2241 if (isInstance) {
2242 // Give a code modification hint to insert 'this->'.
2243 Diag(R.getNameLoc(), DiagID)
2244 << R.getLookupName()
2245 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2246 CheckCXXThisCapture(R.getNameLoc());
2247 } else {
2248 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2249 // they're not shadowed).
2250 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2251 }
2252
2253 for (const NamedDecl *D : R)
2254 Diag(D->getLocation(), NoteID);
2255
2256 // Return true if we are inside a default argument instantiation
2257 // and the found name refers to an instance member function, otherwise
2258 // the caller will try to create an implicit member call and this is wrong
2259 // for default arguments.
2260 //
2261 // FIXME: Is this special case necessary? We could allow the caller to
2262 // diagnose this.
2263 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2264 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2265 return true;
2266 }
2267
2268 // Tell the callee to try to recover.
2269 return false;
2270}
2271
2272/// Diagnose an empty lookup.
2273///
2274/// \return false if new lookup candidates were found
2275bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2276 CorrectionCandidateCallback &CCC,
2277 TemplateArgumentListInfo *ExplicitTemplateArgs,
2278 ArrayRef<Expr *> Args, TypoExpr **Out) {
2279 DeclarationName Name = R.getLookupName();
2280
2281 unsigned diagnostic = diag::err_undeclared_var_use;
2282 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2283 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2284 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2285 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2286 diagnostic = diag::err_undeclared_use;
2287 diagnostic_suggest = diag::err_undeclared_use_suggest;
2288 }
2289
2290 // If the original lookup was an unqualified lookup, fake an
2291 // unqualified lookup. This is useful when (for example) the
2292 // original lookup would not have found something because it was a
2293 // dependent name.
2294 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2295 while (DC) {
2296 if (isa<CXXRecordDecl>(DC)) {
2297 LookupQualifiedName(R, DC);
2298
2299 if (!R.empty()) {
2300 // Don't give errors about ambiguities in this lookup.
2301 R.suppressDiagnostics();
2302
2303 // If there's a best viable function among the results, only mention
2304 // that one in the notes.
2305 OverloadCandidateSet Candidates(R.getNameLoc(),
2306 OverloadCandidateSet::CSK_Normal);
2307 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2308 OverloadCandidateSet::iterator Best;
2309 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2310 OR_Success) {
2311 R.clear();
2312 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2313 R.resolveKind();
2314 }
2315
2316 return DiagnoseDependentMemberLookup(R);
2317 }
2318
2319 R.clear();
2320 }
2321
2322 DC = DC->getLookupParent();
2323 }
2324
2325 // We didn't find anything, so try to correct for a typo.
2326 TypoCorrection Corrected;
2327 if (S && Out) {
2328 SourceLocation TypoLoc = R.getNameLoc();
2329 assert(!ExplicitTemplateArgs &&(static_cast <bool> (!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? void (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "clang/lib/Sema/SemaExpr.cpp", 2330, __extension__ __PRETTY_FUNCTION__
))
2330 "Diagnosing an empty lookup with explicit template args!")(static_cast <bool> (!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? void (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "clang/lib/Sema/SemaExpr.cpp", 2330, __extension__ __PRETTY_FUNCTION__
))
;
2331 *Out = CorrectTypoDelayed(
2332 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2333 [=](const TypoCorrection &TC) {
2334 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2335 diagnostic, diagnostic_suggest);
2336 },
2337 nullptr, CTK_ErrorRecovery);
2338 if (*Out)
2339 return true;
2340 } else if (S &&
2341 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2342 S, &SS, CCC, CTK_ErrorRecovery))) {
2343 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2344 bool DroppedSpecifier =
2345 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2346 R.setLookupName(Corrected.getCorrection());
2347
2348 bool AcceptableWithRecovery = false;
2349 bool AcceptableWithoutRecovery = false;
2350 NamedDecl *ND = Corrected.getFoundDecl();
2351 if (ND) {
2352 if (Corrected.isOverloaded()) {
2353 OverloadCandidateSet OCS(R.getNameLoc(),
2354 OverloadCandidateSet::CSK_Normal);
2355 OverloadCandidateSet::iterator Best;
2356 for (NamedDecl *CD : Corrected) {
2357 if (FunctionTemplateDecl *FTD =
2358 dyn_cast<FunctionTemplateDecl>(CD))
2359 AddTemplateOverloadCandidate(
2360 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2361 Args, OCS);
2362 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2363 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2364 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2365 Args, OCS);
2366 }
2367 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2368 case OR_Success:
2369 ND = Best->FoundDecl;
2370 Corrected.setCorrectionDecl(ND);
2371 break;
2372 default:
2373 // FIXME: Arbitrarily pick the first declaration for the note.
2374 Corrected.setCorrectionDecl(ND);
2375 break;
2376 }
2377 }
2378 R.addDecl(ND);
2379 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2380 CXXRecordDecl *Record = nullptr;
2381 if (Corrected.getCorrectionSpecifier()) {
2382 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2383 Record = Ty->getAsCXXRecordDecl();
2384 }
2385 if (!Record)
2386 Record = cast<CXXRecordDecl>(
2387 ND->getDeclContext()->getRedeclContext());
2388 R.setNamingClass(Record);
2389 }
2390
2391 auto *UnderlyingND = ND->getUnderlyingDecl();
2392 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2393 isa<FunctionTemplateDecl>(UnderlyingND);
2394 // FIXME: If we ended up with a typo for a type name or
2395 // Objective-C class name, we're in trouble because the parser
2396 // is in the wrong place to recover. Suggest the typo
2397 // correction, but don't make it a fix-it since we're not going
2398 // to recover well anyway.
2399 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2400 getAsTypeTemplateDecl(UnderlyingND) ||
2401 isa<ObjCInterfaceDecl>(UnderlyingND);
2402 } else {
2403 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2404 // because we aren't able to recover.
2405 AcceptableWithoutRecovery = true;
2406 }
2407
2408 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2409 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2410 ? diag::note_implicit_param_decl
2411 : diag::note_previous_decl;
2412 if (SS.isEmpty())
2413 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2414 PDiag(NoteID), AcceptableWithRecovery);
2415 else
2416 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2417 << Name << computeDeclContext(SS, false)
2418 << DroppedSpecifier << SS.getRange(),
2419 PDiag(NoteID), AcceptableWithRecovery);
2420
2421 // Tell the callee whether to try to recover.
2422 return !AcceptableWithRecovery;
2423 }
2424 }
2425 R.clear();
2426
2427 // Emit a special diagnostic for failed member lookups.
2428 // FIXME: computing the declaration context might fail here (?)
2429 if (!SS.isEmpty()) {
2430 Diag(R.getNameLoc(), diag::err_no_member)
2431 << Name << computeDeclContext(SS, false)
2432 << SS.getRange();
2433 return true;
2434 }
2435
2436 // Give up, we can't recover.
2437 Diag(R.getNameLoc(), diagnostic) << Name;
2438 return true;
2439}
2440
2441/// In Microsoft mode, if we are inside a template class whose parent class has
2442/// dependent base classes, and we can't resolve an unqualified identifier, then
2443/// assume the identifier is a member of a dependent base class. We can only
2444/// recover successfully in static methods, instance methods, and other contexts
2445/// where 'this' is available. This doesn't precisely match MSVC's
2446/// instantiation model, but it's close enough.
2447static Expr *
2448recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2449 DeclarationNameInfo &NameInfo,
2450 SourceLocation TemplateKWLoc,
2451 const TemplateArgumentListInfo *TemplateArgs) {
2452 // Only try to recover from lookup into dependent bases in static methods or
2453 // contexts where 'this' is available.
2454 QualType ThisType = S.getCurrentThisType();
2455 const CXXRecordDecl *RD = nullptr;
2456 if (!ThisType.isNull())
2457 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2458 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2459 RD = MD->getParent();
2460 if (!RD || !RD->hasAnyDependentBases())
2461 return nullptr;
2462
2463 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2464 // is available, suggest inserting 'this->' as a fixit.
2465 SourceLocation Loc = NameInfo.getLoc();
2466 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2467 DB << NameInfo.getName() << RD;
2468
2469 if (!ThisType.isNull()) {
2470 DB << FixItHint::CreateInsertion(Loc, "this->");
2471 return CXXDependentScopeMemberExpr::Create(
2472 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2473 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2474 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2475 }
2476
2477 // Synthesize a fake NNS that points to the derived class. This will
2478 // perform name lookup during template instantiation.
2479 CXXScopeSpec SS;
2480 auto *NNS =
2481 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2482 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2483 return DependentScopeDeclRefExpr::Create(
2484 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2485 TemplateArgs);
2486}
2487
2488ExprResult
2489Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2490 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2491 bool HasTrailingLParen, bool IsAddressOfOperand,
2492 CorrectionCandidateCallback *CCC,
2493 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2494 assert(!(IsAddressOfOperand && HasTrailingLParen) &&(static_cast <bool> (!(IsAddressOfOperand && HasTrailingLParen
) && "cannot be direct & operand and have a trailing lparen"
) ? void (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "clang/lib/Sema/SemaExpr.cpp", 2495, __extension__ __PRETTY_FUNCTION__
))
2495 "cannot be direct & operand and have a trailing lparen")(static_cast <bool> (!(IsAddressOfOperand && HasTrailingLParen
) && "cannot be direct & operand and have a trailing lparen"
) ? void (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "clang/lib/Sema/SemaExpr.cpp", 2495, __extension__ __PRETTY_FUNCTION__
))
;
2496 if (SS.isInvalid())
2497 return ExprError();
2498
2499 TemplateArgumentListInfo TemplateArgsBuffer;
2500
2501 // Decompose the UnqualifiedId into the following data.
2502 DeclarationNameInfo NameInfo;
2503 const TemplateArgumentListInfo *TemplateArgs;
2504 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2505
2506 DeclarationName Name = NameInfo.getName();
2507 IdentifierInfo *II = Name.getAsIdentifierInfo();
2508 SourceLocation NameLoc = NameInfo.getLoc();
2509
2510 if (II && II->isEditorPlaceholder()) {
2511 // FIXME: When typed placeholders are supported we can create a typed
2512 // placeholder expression node.
2513 return ExprError();
2514 }
2515
2516 // C++ [temp.dep.expr]p3:
2517 // An id-expression is type-dependent if it contains:
2518 // -- an identifier that was declared with a dependent type,
2519 // (note: handled after lookup)
2520 // -- a template-id that is dependent,
2521 // (note: handled in BuildTemplateIdExpr)
2522 // -- a conversion-function-id that specifies a dependent type,
2523 // -- a nested-name-specifier that contains a class-name that
2524 // names a dependent type.
2525 // Determine whether this is a member of an unknown specialization;
2526 // we need to handle these differently.
2527 bool DependentID = false;
2528 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2529 Name.getCXXNameType()->isDependentType()) {
2530 DependentID = true;
2531 } else if (SS.isSet()) {
2532 if (DeclContext *DC = computeDeclContext(SS, false)) {
2533 if (RequireCompleteDeclContext(SS, DC))
2534 return ExprError();
2535 } else {
2536 DependentID = true;
2537 }
2538 }
2539
2540 if (DependentID)
2541 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2542 IsAddressOfOperand, TemplateArgs);
2543
2544 // Perform the required lookup.
2545 LookupResult R(*this, NameInfo,
2546 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2547 ? LookupObjCImplicitSelfParam
2548 : LookupOrdinaryName);
2549 if (TemplateKWLoc.isValid() || TemplateArgs) {
2550 // Lookup the template name again to correctly establish the context in
2551 // which it was found. This is really unfortunate as we already did the
2552 // lookup to determine that it was a template name in the first place. If
2553 // this becomes a performance hit, we can work harder to preserve those
2554 // results until we get here but it's likely not worth it.
2555 bool MemberOfUnknownSpecialization;
2556 AssumedTemplateKind AssumedTemplate;
2557 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2558 MemberOfUnknownSpecialization, TemplateKWLoc,
2559 &AssumedTemplate))
2560 return ExprError();
2561
2562 if (MemberOfUnknownSpecialization ||
2563 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2564 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2565 IsAddressOfOperand, TemplateArgs);
2566 } else {
2567 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2568 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2569
2570 // If the result might be in a dependent base class, this is a dependent
2571 // id-expression.
2572 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2573 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2574 IsAddressOfOperand, TemplateArgs);
2575
2576 // If this reference is in an Objective-C method, then we need to do
2577 // some special Objective-C lookup, too.
2578 if (IvarLookupFollowUp) {
2579 ExprResult E(LookupInObjCMethod(R, S, II, true));
2580 if (E.isInvalid())
2581 return ExprError();
2582
2583 if (Expr *Ex = E.getAs<Expr>())
2584 return Ex;
2585 }
2586 }
2587
2588 if (R.isAmbiguous())
2589 return ExprError();
2590
2591 // This could be an implicitly declared function reference if the language
2592 // mode allows it as a feature.
2593 if (R.empty() && HasTrailingLParen && II &&
2594 getLangOpts().implicitFunctionsAllowed()) {
2595 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2596 if (D) R.addDecl(D);
2597 }
2598
2599 // Determine whether this name might be a candidate for
2600 // argument-dependent lookup.
2601 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2602
2603 if (R.empty() && !ADL) {
2604 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2605 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2606 TemplateKWLoc, TemplateArgs))
2607 return E;
2608 }
2609
2610 // Don't diagnose an empty lookup for inline assembly.
2611 if (IsInlineAsmIdentifier)
2612 return ExprError();
2613
2614 // If this name wasn't predeclared and if this is not a function
2615 // call, diagnose the problem.
2616 TypoExpr *TE = nullptr;
2617 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2618 : nullptr);
2619 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2620 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(static_cast <bool> ((!CCC || CCC->IsAddressOfOperand
== IsAddressOfOperand) && "Typo correction callback misconfigured"
) ? void (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "clang/lib/Sema/SemaExpr.cpp", 2621, __extension__ __PRETTY_FUNCTION__
))
2621 "Typo correction callback misconfigured")(static_cast <bool> ((!CCC || CCC->IsAddressOfOperand
== IsAddressOfOperand) && "Typo correction callback misconfigured"
) ? void (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "clang/lib/Sema/SemaExpr.cpp", 2621, __extension__ __PRETTY_FUNCTION__
))
;
2622 if (CCC) {
2623 // Make sure the callback knows what the typo being diagnosed is.
2624 CCC->setTypoName(II);
2625 if (SS.isValid())
2626 CCC->setTypoNNS(SS.getScopeRep());
2627 }
2628 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2629 // a template name, but we happen to have always already looked up the name
2630 // before we get here if it must be a template name.
2631 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2632 std::nullopt, &TE)) {
2633 if (TE && KeywordReplacement) {
2634 auto &State = getTypoExprState(TE);
2635 auto BestTC = State.Consumer->getNextCorrection();
2636 if (BestTC.isKeyword()) {
2637 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2638 if (State.DiagHandler)
2639 State.DiagHandler(BestTC);
2640 KeywordReplacement->startToken();
2641 KeywordReplacement->setKind(II->getTokenID());
2642 KeywordReplacement->setIdentifierInfo(II);
2643 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2644 // Clean up the state associated with the TypoExpr, since it has
2645 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2646 clearDelayedTypo(TE);
2647 // Signal that a correction to a keyword was performed by returning a
2648 // valid-but-null ExprResult.
2649 return (Expr*)nullptr;
2650 }
2651 State.Consumer->resetCorrectionStream();
2652 }
2653 return TE ? TE : ExprError();
2654 }
2655
2656 assert(!R.empty() &&(static_cast <bool> (!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? void (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "clang/lib/Sema/SemaExpr.cpp", 2657, __extension__ __PRETTY_FUNCTION__
))
2657 "DiagnoseEmptyLookup returned false but added no results")(static_cast <bool> (!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? void (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "clang/lib/Sema/SemaExpr.cpp", 2657, __extension__ __PRETTY_FUNCTION__
))
;
2658
2659 // If we found an Objective-C instance variable, let
2660 // LookupInObjCMethod build the appropriate expression to
2661 // reference the ivar.
2662 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2663 R.clear();
2664 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2665 // In a hopelessly buggy code, Objective-C instance variable
2666 // lookup fails and no expression will be built to reference it.
2667 if (!E.isInvalid() && !E.get())
2668 return ExprError();
2669 return E;
2670 }
2671 }
2672
2673 // This is guaranteed from this point on.
2674 assert(!R.empty() || ADL)(static_cast <bool> (!R.empty() || ADL) ? void (0) : __assert_fail
("!R.empty() || ADL", "clang/lib/Sema/SemaExpr.cpp", 2674, __extension__
__PRETTY_FUNCTION__))
;
2675
2676 // Check whether this might be a C++ implicit instance member access.
2677 // C++ [class.mfct.non-static]p3:
2678 // When an id-expression that is not part of a class member access
2679 // syntax and not used to form a pointer to member is used in the
2680 // body of a non-static member function of class X, if name lookup
2681 // resolves the name in the id-expression to a non-static non-type
2682 // member of some class C, the id-expression is transformed into a
2683 // class member access expression using (*this) as the
2684 // postfix-expression to the left of the . operator.
2685 //
2686 // But we don't actually need to do this for '&' operands if R
2687 // resolved to a function or overloaded function set, because the
2688 // expression is ill-formed if it actually works out to be a
2689 // non-static member function:
2690 //
2691 // C++ [expr.ref]p4:
2692 // Otherwise, if E1.E2 refers to a non-static member function. . .
2693 // [t]he expression can be used only as the left-hand operand of a
2694 // member function call.
2695 //
2696 // There are other safeguards against such uses, but it's important
2697 // to get this right here so that we don't end up making a
2698 // spuriously dependent expression if we're inside a dependent
2699 // instance method.
2700 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2701 bool MightBeImplicitMember;
2702 if (!IsAddressOfOperand)
2703 MightBeImplicitMember = true;
2704 else if (!SS.isEmpty())
2705 MightBeImplicitMember = false;
2706 else if (R.isOverloadedResult())
2707 MightBeImplicitMember = false;
2708 else if (R.isUnresolvableResult())
2709 MightBeImplicitMember = true;
2710 else
2711 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2712 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2713 isa<MSPropertyDecl>(R.getFoundDecl());
2714
2715 if (MightBeImplicitMember)
2716 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2717 R, TemplateArgs, S);
2718 }
2719
2720 if (TemplateArgs || TemplateKWLoc.isValid()) {
2721
2722 // In C++1y, if this is a variable template id, then check it
2723 // in BuildTemplateIdExpr().
2724 // The single lookup result must be a variable template declaration.
2725 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2726 Id.TemplateId->Kind == TNK_Var_template) {
2727 assert(R.getAsSingle<VarTemplateDecl>() &&(static_cast <bool> (R.getAsSingle<VarTemplateDecl>
() && "There should only be one declaration found.") ?
void (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "clang/lib/Sema/SemaExpr.cpp", 2728, __extension__ __PRETTY_FUNCTION__
))
2728 "There should only be one declaration found.")(static_cast <bool> (R.getAsSingle<VarTemplateDecl>
() && "There should only be one declaration found.") ?
void (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "clang/lib/Sema/SemaExpr.cpp", 2728, __extension__ __PRETTY_FUNCTION__
))
;
2729 }
2730
2731 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2732 }
2733
2734 return BuildDeclarationNameExpr(SS, R, ADL);
2735}
2736
2737/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2738/// declaration name, generally during template instantiation.
2739/// There's a large number of things which don't need to be done along
2740/// this path.
2741ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2742 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2743 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2744 if (NameInfo.getName().isDependentName())
2745 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2746 NameInfo, /*TemplateArgs=*/nullptr);
2747
2748 DeclContext *DC = computeDeclContext(SS, false);
2749 if (!DC)
2750 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2751 NameInfo, /*TemplateArgs=*/nullptr);
2752
2753 if (RequireCompleteDeclContext(SS, DC))
2754 return ExprError();
2755
2756 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2757 LookupQualifiedName(R, DC);
2758
2759 if (R.isAmbiguous())
2760 return ExprError();
2761
2762 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2763 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2764 NameInfo, /*TemplateArgs=*/nullptr);
2765
2766 if (R.empty()) {
2767 // Don't diagnose problems with invalid record decl, the secondary no_member
2768 // diagnostic during template instantiation is likely bogus, e.g. if a class
2769 // is invalid because it's derived from an invalid base class, then missing
2770 // members were likely supposed to be inherited.
2771 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2772 if (CD->isInvalidDecl())
2773 return ExprError();
2774 Diag(NameInfo.getLoc(), diag::err_no_member)
2775 << NameInfo.getName() << DC << SS.getRange();
2776 return ExprError();
2777 }
2778
2779 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2780 // Diagnose a missing typename if this resolved unambiguously to a type in
2781 // a dependent context. If we can recover with a type, downgrade this to
2782 // a warning in Microsoft compatibility mode.
2783 unsigned DiagID = diag::err_typename_missing;
2784 if (RecoveryTSI && getLangOpts().MSVCCompat)
2785 DiagID = diag::ext_typename_missing;
2786 SourceLocation Loc = SS.getBeginLoc();
2787 auto D = Diag(Loc, DiagID);
2788 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2789 << SourceRange(Loc, NameInfo.getEndLoc());
2790
2791 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2792 // context.
2793 if (!RecoveryTSI)
2794 return ExprError();
2795
2796 // Only issue the fixit if we're prepared to recover.
2797 D << FixItHint::CreateInsertion(Loc, "typename ");
2798
2799 // Recover by pretending this was an elaborated type.
2800 QualType Ty = Context.getTypeDeclType(TD);
2801 TypeLocBuilder TLB;
2802 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2803
2804 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2805 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2806 QTL.setElaboratedKeywordLoc(SourceLocation());
2807 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2808
2809 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2810
2811 return ExprEmpty();
2812 }
2813
2814 // Defend against this resolving to an implicit member access. We usually
2815 // won't get here if this might be a legitimate a class member (we end up in
2816 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2817 // a pointer-to-member or in an unevaluated context in C++11.
2818 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2819 return BuildPossibleImplicitMemberExpr(SS,
2820 /*TemplateKWLoc=*/SourceLocation(),
2821 R, /*TemplateArgs=*/nullptr, S);
2822
2823 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2824}
2825
2826/// The parser has read a name in, and Sema has detected that we're currently
2827/// inside an ObjC method. Perform some additional checks and determine if we
2828/// should form a reference to an ivar.
2829///
2830/// Ideally, most of this would be done by lookup, but there's
2831/// actually quite a lot of extra work involved.
2832DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2833 IdentifierInfo *II) {
2834 SourceLocation Loc = Lookup.getNameLoc();
2835 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2836
2837 // Check for error condition which is already reported.
2838 if (!CurMethod)
2839 return DeclResult(true);
2840
2841 // There are two cases to handle here. 1) scoped lookup could have failed,
2842 // in which case we should look for an ivar. 2) scoped lookup could have
2843 // found a decl, but that decl is outside the current instance method (i.e.
2844 // a global variable). In these two cases, we do a lookup for an ivar with
2845 // this name, if the lookup sucedes, we replace it our current decl.
2846
2847 // If we're in a class method, we don't normally want to look for
2848 // ivars. But if we don't find anything else, and there's an
2849 // ivar, that's an error.
2850 bool IsClassMethod = CurMethod->isClassMethod();
2851
2852 bool LookForIvars;
2853 if (Lookup.empty())
2854 LookForIvars = true;
2855 else if (IsClassMethod)
2856 LookForIvars = false;
2857 else
2858 LookForIvars = (Lookup.isSingleResult() &&
2859 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2860 ObjCInterfaceDecl *IFace = nullptr;
2861 if (LookForIvars) {
2862 IFace = CurMethod->getClassInterface();
2863 ObjCInterfaceDecl *ClassDeclared;
2864 ObjCIvarDecl *IV = nullptr;
2865 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2866 // Diagnose using an ivar in a class method.
2867 if (IsClassMethod) {
2868 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2869 return DeclResult(true);
2870 }
2871
2872 // Diagnose the use of an ivar outside of the declaring class.
2873 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2874 !declaresSameEntity(ClassDeclared, IFace) &&
2875 !getLangOpts().DebuggerSupport)
2876 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2877
2878 // Success.
2879 return IV;
2880 }
2881 } else if (CurMethod->isInstanceMethod()) {
2882 // We should warn if a local variable hides an ivar.
2883 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2884 ObjCInterfaceDecl *ClassDeclared;
2885 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2886 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2887 declaresSameEntity(IFace, ClassDeclared))
2888 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2889 }
2890 }
2891 } else if (Lookup.isSingleResult() &&
2892 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2893 // If accessing a stand-alone ivar in a class method, this is an error.
2894 if (const ObjCIvarDecl *IV =
2895 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2896 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2897 return DeclResult(true);
2898 }
2899 }
2900
2901 // Didn't encounter an error, didn't find an ivar.
2902 return DeclResult(false);
2903}
2904
2905ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2906 ObjCIvarDecl *IV) {
2907 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2908 assert(CurMethod && CurMethod->isInstanceMethod() &&(static_cast <bool> (CurMethod && CurMethod->
isInstanceMethod() && "should not reference ivar from this context"
) ? void (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "clang/lib/Sema/SemaExpr.cpp", 2909, __extension__ __PRETTY_FUNCTION__
))
2909 "should not reference ivar from this context")(static_cast <bool> (CurMethod && CurMethod->
isInstanceMethod() && "should not reference ivar from this context"
) ? void (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "clang/lib/Sema/SemaExpr.cpp", 2909, __extension__ __PRETTY_FUNCTION__
))
;
2910
2911 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2912 assert(IFace && "should not reference ivar from this context")(static_cast <bool> (IFace && "should not reference ivar from this context"
) ? void (0) : __assert_fail ("IFace && \"should not reference ivar from this context\""
, "clang/lib/Sema/SemaExpr.cpp", 2912, __extension__ __PRETTY_FUNCTION__
))
;
2913
2914 // If we're referencing an invalid decl, just return this as a silent
2915 // error node. The error diagnostic was already emitted on the decl.
2916 if (IV->isInvalidDecl())
2917 return ExprError();
2918
2919 // Check if referencing a field with __attribute__((deprecated)).
2920 if (DiagnoseUseOfDecl(IV, Loc))
2921 return ExprError();
2922
2923 // FIXME: This should use a new expr for a direct reference, don't
2924 // turn this into Self->ivar, just return a BareIVarExpr or something.
2925 IdentifierInfo &II = Context.Idents.get("self");
2926 UnqualifiedId SelfName;
2927 SelfName.setImplicitSelfParam(&II);
2928 CXXScopeSpec SelfScopeSpec;
2929 SourceLocation TemplateKWLoc;
2930 ExprResult SelfExpr =
2931 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2932 /*HasTrailingLParen=*/false,
2933 /*IsAddressOfOperand=*/false);
2934 if (SelfExpr.isInvalid())
2935 return ExprError();
2936
2937 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2938 if (SelfExpr.isInvalid())
2939 return ExprError();
2940
2941 MarkAnyDeclReferenced(Loc, IV, true);
2942
2943 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2944 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2945 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2946 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2947
2948 ObjCIvarRefExpr *Result = new (Context)
2949 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2950 IV->getLocation(), SelfExpr.get(), true, true);
2951
2952 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2953 if (!isUnevaluatedContext() &&
2954 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2955 getCurFunction()->recordUseOfWeak(Result);
2956 }
2957 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
2958 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2959 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2960
2961 return Result;
2962}
2963
2964/// The parser has read a name in, and Sema has detected that we're currently
2965/// inside an ObjC method. Perform some additional checks and determine if we
2966/// should form a reference to an ivar. If so, build an expression referencing
2967/// that ivar.
2968ExprResult
2969Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2970 IdentifierInfo *II, bool AllowBuiltinCreation) {
2971 // FIXME: Integrate this lookup step into LookupParsedName.
2972 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2973 if (Ivar.isInvalid())
2974 return ExprError();
2975 if (Ivar.isUsable())
2976 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2977 cast<ObjCIvarDecl>(Ivar.get()));
2978
2979 if (Lookup.empty() && II && AllowBuiltinCreation)
2980 LookupBuiltin(Lookup);
2981
2982 // Sentinel value saying that we didn't do anything special.
2983 return ExprResult(false);
2984}
2985
2986/// Cast a base object to a member's actual type.
2987///
2988/// There are two relevant checks:
2989///
2990/// C++ [class.access.base]p7:
2991///
2992/// If a class member access operator [...] is used to access a non-static
2993/// data member or non-static member function, the reference is ill-formed if
2994/// the left operand [...] cannot be implicitly converted to a pointer to the
2995/// naming class of the right operand.
2996///
2997/// C++ [expr.ref]p7:
2998///
2999/// If E2 is a non-static data member or a non-static member function, the
3000/// program is ill-formed if the class of which E2 is directly a member is an
3001/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3002///
3003/// Note that the latter check does not consider access; the access of the
3004/// "real" base class is checked as appropriate when checking the access of the
3005/// member name.
3006ExprResult
3007Sema::PerformObjectMemberConversion(Expr *From,
3008 NestedNameSpecifier *Qualifier,
3009 NamedDecl *FoundDecl,
3010 NamedDecl *Member) {
3011 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3012 if (!RD)
3013 return From;
3014
3015 QualType DestRecordType;
3016 QualType DestType;
3017 QualType FromRecordType;
3018 QualType FromType = From->getType();
3019 bool PointerConversions = false;
3020 if (isa<FieldDecl>(Member)) {
3021 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3022 auto FromPtrType = FromType->getAs<PointerType>();
3023 DestRecordType = Context.getAddrSpaceQualType(
3024 DestRecordType, FromPtrType
3025 ? FromType->getPointeeType().getAddressSpace()
3026 : FromType.getAddressSpace());
3027
3028 if (FromPtrType) {
3029 DestType = Context.getPointerType(DestRecordType);
3030 FromRecordType = FromPtrType->getPointeeType();
3031 PointerConversions = true;
3032 } else {
3033 DestType = DestRecordType;
3034 FromRecordType = FromType;
3035 }
3036 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3037 if (Method->isStatic())
3038 return From;
3039
3040 DestType = Method->getThisType();
3041 DestRecordType = DestType->getPointeeType();
3042
3043 if (FromType->getAs<PointerType>()) {
3044 FromRecordType = FromType->getPointeeType();
3045 PointerConversions = true;
3046 } else {
3047 FromRecordType = FromType;
3048 DestType = DestRecordType;
3049 }
3050
3051 LangAS FromAS = FromRecordType.getAddressSpace();
3052 LangAS DestAS = DestRecordType.getAddressSpace();
3053 if (FromAS != DestAS) {
3054 QualType FromRecordTypeWithoutAS =
3055 Context.removeAddrSpaceQualType(FromRecordType);
3056 QualType FromTypeWithDestAS =
3057 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3058 if (PointerConversions)
3059 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3060 From = ImpCastExprToType(From, FromTypeWithDestAS,
3061 CK_AddressSpaceConversion, From->getValueKind())
3062 .get();
3063 }
3064 } else {
3065 // No conversion necessary.
3066 return From;
3067 }
3068
3069 if (DestType->isDependentType() || FromType->isDependentType())
3070 return From;
3071
3072 // If the unqualified types are the same, no conversion is necessary.
3073 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3074 return From;
3075
3076 SourceRange FromRange = From->getSourceRange();
3077 SourceLocation FromLoc = FromRange.getBegin();
3078
3079 ExprValueKind VK = From->getValueKind();
3080
3081 // C++ [class.member.lookup]p8:
3082 // [...] Ambiguities can often be resolved by qualifying a name with its
3083 // class name.
3084 //
3085 // If the member was a qualified name and the qualified referred to a
3086 // specific base subobject type, we'll cast to that intermediate type
3087 // first and then to the object in which the member is declared. That allows
3088 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3089 //
3090 // class Base { public: int x; };
3091 // class Derived1 : public Base { };
3092 // class Derived2 : public Base { };
3093 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3094 //
3095 // void VeryDerived::f() {
3096 // x = 17; // error: ambiguous base subobjects
3097 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3098 // }
3099 if (Qualifier && Qualifier->getAsType()) {
3100 QualType QType = QualType(Qualifier->getAsType(), 0);
3101 assert(QType->isRecordType() && "lookup done with non-record type")(static_cast <bool> (QType->isRecordType() &&
"lookup done with non-record type") ? void (0) : __assert_fail
("QType->isRecordType() && \"lookup done with non-record type\""
, "clang/lib/Sema/SemaExpr.cpp", 3101, __extension__ __PRETTY_FUNCTION__
))
;
3102
3103 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3104
3105 // In C++98, the qualifier type doesn't actually have to be a base
3106 // type of the object type, in which case we just ignore it.
3107 // Otherwise build the appropriate casts.
3108 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3109 CXXCastPath BasePath;
3110 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3111 FromLoc, FromRange, &BasePath))
3112 return ExprError();
3113
3114 if (PointerConversions)
3115 QType = Context.getPointerType(QType);
3116 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3117 VK, &BasePath).get();
3118
3119 FromType = QType;
3120 FromRecordType = QRecordType;
3121
3122 // If the qualifier type was the same as the destination type,
3123 // we're done.
3124 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3125 return From;
3126 }
3127 }
3128
3129 CXXCastPath BasePath;
3130 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3131 FromLoc, FromRange, &BasePath,
3132 /*IgnoreAccess=*/true))
3133 return ExprError();
3134
3135 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3136 VK, &BasePath);
3137}
3138
3139bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3140 const LookupResult &R,
3141 bool HasTrailingLParen) {
3142 // Only when used directly as the postfix-expression of a call.
3143 if (!HasTrailingLParen)
3144 return false;
3145
3146 // Never if a scope specifier was provided.
3147 if (SS.isSet())
3148 return false;
3149
3150 // Only in C++ or ObjC++.
3151 if (!getLangOpts().CPlusPlus)
3152 return false;
3153
3154 // Turn off ADL when we find certain kinds of declarations during
3155 // normal lookup:
3156 for (const NamedDecl *D : R) {
3157 // C++0x [basic.lookup.argdep]p3:
3158 // -- a declaration of a class member
3159 // Since using decls preserve this property, we check this on the
3160 // original decl.
3161 if (D->isCXXClassMember())
3162 return false;
3163
3164 // C++0x [basic.lookup.argdep]p3:
3165 // -- a block-scope function declaration that is not a
3166 // using-declaration
3167 // NOTE: we also trigger this for function templates (in fact, we
3168 // don't check the decl type at all, since all other decl types
3169 // turn off ADL anyway).
3170 if (isa<UsingShadowDecl>(D))
3171 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3172 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3173 return false;
3174
3175 // C++0x [basic.lookup.argdep]p3:
3176 // -- a declaration that is neither a function or a function
3177 // template
3178 // And also for builtin functions.
3179 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3180 // But also builtin functions.
3181 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3182 return false;
3183 } else if (!isa<FunctionTemplateDecl>(D))
3184 return false;
3185 }
3186
3187 return true;
3188}
3189
3190
3191/// Diagnoses obvious problems with the use of the given declaration
3192/// as an expression. This is only actually called for lookups that
3193/// were not overloaded, and it doesn't promise that the declaration
3194/// will in fact be used.
3195static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3196 bool AcceptInvalid) {
3197 if (D->isInvalidDecl() && !AcceptInvalid)
3198 return true;
3199
3200 if (isa<TypedefNameDecl>(D)) {
3201 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3202 return true;
3203 }
3204
3205 if (isa<ObjCInterfaceDecl>(D)) {
3206 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3207 return true;
3208 }
3209
3210 if (isa<NamespaceDecl>(D)) {
3211 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3212 return true;
3213 }
3214
3215 return false;
3216}
3217
3218// Certain multiversion types should be treated as overloaded even when there is
3219// only one result.
3220static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3221 assert(R.isSingleResult() && "Expected only a single result")(static_cast <bool> (R.isSingleResult() && "Expected only a single result"
) ? void (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\""
, "clang/lib/Sema/SemaExpr.cpp", 3221, __extension__ __PRETTY_FUNCTION__
))
;
3222 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3223 return FD &&
3224 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3225}
3226
3227ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3228 LookupResult &R, bool NeedsADL,
3229 bool AcceptInvalidDecl) {
3230 // If this is a single, fully-resolved result and we don't need ADL,
3231 // just build an ordinary singleton decl ref.
3232 if (!NeedsADL && R.isSingleResult() &&
3233 !R.getAsSingle<FunctionTemplateDecl>() &&
3234 !ShouldLookupResultBeMultiVersionOverload(R))
3235 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3236 R.getRepresentativeDecl(), nullptr,
3237 AcceptInvalidDecl);
3238
3239 // We only need to check the declaration if there's exactly one
3240 // result, because in the overloaded case the results can only be
3241 // functions and function templates.
3242 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3243 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3244 AcceptInvalidDecl))
3245 return ExprError();
3246
3247 // Otherwise, just build an unresolved lookup expression. Suppress
3248 // any lookup-related diagnostics; we'll hash these out later, when
3249 // we've picked a target.
3250 R.suppressDiagnostics();
3251
3252 UnresolvedLookupExpr *ULE
3253 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3254 SS.getWithLocInContext(Context),
3255 R.getLookupNameInfo(),
3256 NeedsADL, R.isOverloadedResult(),
3257 R.begin(), R.end());
3258
3259 return ULE;
3260}
3261
3262static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
3263 SourceLocation loc,
3264 ValueDecl *var);
3265
3266/// Complete semantic analysis for a reference to the given declaration.
3267ExprResult Sema::BuildDeclarationNameExpr(
3268 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3269 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3270 bool AcceptInvalidDecl) {
3271 assert(D && "Cannot refer to a NULL declaration")(static_cast <bool> (D && "Cannot refer to a NULL declaration"
) ? void (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\""
, "clang/lib/Sema/SemaExpr.cpp", 3271, __extension__ __PRETTY_FUNCTION__
))
;
3272 assert(!isa<FunctionTemplateDecl>(D) &&(static_cast <bool> (!isa<FunctionTemplateDecl>(D
) && "Cannot refer unambiguously to a function template"
) ? void (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "clang/lib/Sema/SemaExpr.cpp", 3273, __extension__ __PRETTY_FUNCTION__
))
3273 "Cannot refer unambiguously to a function template")(static_cast <bool> (!isa<FunctionTemplateDecl>(D
) && "Cannot refer unambiguously to a function template"
) ? void (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "clang/lib/Sema/SemaExpr.cpp", 3273, __extension__ __PRETTY_FUNCTION__
))
;
3274
3275 SourceLocation Loc = NameInfo.getLoc();
3276 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3277 // Recovery from invalid cases (e.g. D is an invalid Decl).
3278 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3279 // diagnostics, as invalid decls use int as a fallback type.
3280 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3281 }
3282
3283 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3284 // Specifically diagnose references to class templates that are missing
3285 // a template argument list.
3286 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3287 return ExprError();
3288 }
3289
3290 // Make sure that we're referring to a value.
3291 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3292 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3293 Diag(D->getLocation(), diag::note_declared_at);
3294 return ExprError();
3295 }
3296
3297 // Check whether this declaration can be used. Note that we suppress
3298 // this check when we're going to perform argument-dependent lookup
3299 // on this function name, because this might not be the function
3300 // that overload resolution actually selects.
3301 if (DiagnoseUseOfDecl(D, Loc))
3302 return ExprError();
3303
3304 auto *VD = cast<ValueDecl>(D);
3305
3306 // Only create DeclRefExpr's for valid Decl's.
3307 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3308 return ExprError();
3309
3310 // Handle members of anonymous structs and unions. If we got here,
3311 // and the reference is to a class member indirect field, then this
3312 // must be the subject of a pointer-to-member expression.
3313 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3314 IndirectField && !IndirectField->isCXXClassMember())
3315 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3316 IndirectField);
3317
3318 QualType type = VD->getType();
3319 if (type.isNull())
3320 return ExprError();
3321 ExprValueKind valueKind = VK_PRValue;
3322
3323 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3324 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3325 // is expanded by some outer '...' in the context of the use.
3326 type = type.getNonPackExpansionType();
3327
3328 switch (D->getKind()) {
3329 // Ignore all the non-ValueDecl kinds.
3330#define ABSTRACT_DECL(kind)
3331#define VALUE(type, base)
3332#define DECL(type, base) case Decl::type:
3333#include "clang/AST/DeclNodes.inc"
3334 llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "clang/lib/Sema/SemaExpr.cpp"
, 3334)
;
3335
3336 // These shouldn't make it here.
3337 case Decl::ObjCAtDefsField:
3338 llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?"
, "clang/lib/Sema/SemaExpr.cpp", 3338)
;
3339
3340 // Enum constants are always r-values and never references.
3341 // Unresolved using declarations are dependent.
3342 case Decl::EnumConstant:
3343 case Decl::UnresolvedUsingValue:
3344 case Decl::OMPDeclareReduction:
3345 case Decl::OMPDeclareMapper:
3346 valueKind = VK_PRValue;
3347 break;
3348
3349 // Fields and indirect fields that got here must be for
3350 // pointer-to-member expressions; we just call them l-values for
3351 // internal consistency, because this subexpression doesn't really
3352 // exist in the high-level semantics.
3353 case Decl::Field:
3354 case Decl::IndirectField:
3355 case Decl::ObjCIvar:
3356 assert(getLangOpts().CPlusPlus && "building reference to field in C?")(static_cast <bool> (getLangOpts().CPlusPlus &&
"building reference to field in C?") ? void (0) : __assert_fail
("getLangOpts().CPlusPlus && \"building reference to field in C?\""
, "clang/lib/Sema/SemaExpr.cpp", 3356, __extension__ __PRETTY_FUNCTION__
))
;
3357
3358 // These can't have reference type in well-formed programs, but
3359 // for internal consistency we do this anyway.
3360 type = type.getNonReferenceType();
3361 valueKind = VK_LValue;
3362 break;
3363
3364 // Non-type template parameters are either l-values or r-values
3365 // depending on the type.
3366 case Decl::NonTypeTemplateParm: {
3367 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3368 type = reftype->getPointeeType();
3369 valueKind = VK_LValue; // even if the parameter is an r-value reference
3370 break;
3371 }
3372
3373 // [expr.prim.id.unqual]p2:
3374 // If the entity is a template parameter object for a template
3375 // parameter of type T, the type of the expression is const T.
3376 // [...] The expression is an lvalue if the entity is a [...] template
3377 // parameter object.
3378 if (type->isRecordType()) {
3379 type = type.getUnqualifiedType().withConst();
3380 valueKind = VK_LValue;
3381 break;
3382 }
3383
3384 // For non-references, we need to strip qualifiers just in case
3385 // the template parameter was declared as 'const int' or whatever.
3386 valueKind = VK_PRValue;
3387 type = type.getUnqualifiedType();
3388 break;
3389 }
3390
3391 case Decl::Var:
3392 case Decl::VarTemplateSpecialization:
3393 case Decl::VarTemplatePartialSpecialization:
3394 case Decl::Decomposition:
3395 case Decl::OMPCapturedExpr:
3396 // In C, "extern void blah;" is valid and is an r-value.
3397 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3398 type->isVoidType()) {
3399 valueKind = VK_PRValue;
3400 break;
3401 }
3402 [[fallthrough]];
3403
3404 case Decl::ImplicitParam:
3405 case Decl::ParmVar: {
3406 // These are always l-values.
3407 valueKind = VK_LValue;
3408 type = type.getNonReferenceType();
3409
3410 // FIXME: Does the addition of const really only apply in
3411 // potentially-evaluated contexts? Since the variable isn't actually
3412 // captured in an unevaluated context, it seems that the answer is no.
3413 if (!isUnevaluatedContext()) {
3414 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3415 if (!CapturedType.isNull())
3416 type = CapturedType;
3417 }
3418
3419 break;
3420 }
3421
3422 case Decl::Binding:
3423 // These are always lvalues.
3424 valueKind = VK_LValue;
3425 type = type.getNonReferenceType();
3426 break;
3427
3428 case Decl::Function: {
3429 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3430 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3431 type = Context.BuiltinFnTy;
3432 valueKind = VK_PRValue;
3433 break;
3434 }
3435 }
3436
3437 const FunctionType *fty = type->castAs<FunctionType>();
3438
3439 // If we're referring to a function with an __unknown_anytype
3440 // result type, make the entire expression __unknown_anytype.
3441 if (fty->getReturnType() == Context.UnknownAnyTy) {
3442 type = Context.UnknownAnyTy;
3443 valueKind = VK_PRValue;
3444 break;
3445 }
3446
3447 // Functions are l-values in C++.
3448 if (getLangOpts().CPlusPlus) {
3449 valueKind = VK_LValue;
3450 break;
3451 }
3452
3453 // C99 DR 316 says that, if a function type comes from a
3454 // function definition (without a prototype), that type is only
3455 // used for checking compatibility. Therefore, when referencing
3456 // the function, we pretend that we don't have the full function
3457 // type.
3458 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3459 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3460 fty->getExtInfo());
3461
3462 // Functions are r-values in C.
3463 valueKind = VK_PRValue;
3464 break;
3465 }
3466
3467 case Decl::CXXDeductionGuide:
3468 llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide"
, "clang/lib/Sema/SemaExpr.cpp", 3468)
;
3469
3470 case Decl::MSProperty:
3471 case Decl::MSGuid:
3472 case Decl::TemplateParamObject:
3473 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3474 // capture in OpenMP, or duplicated between host and device?
3475 valueKind = VK_LValue;
3476 break;
3477
3478 case Decl::UnnamedGlobalConstant:
3479 valueKind = VK_LValue;
3480 break;
3481
3482 case Decl::CXXMethod:
3483 // If we're referring to a method with an __unknown_anytype
3484 // result type, make the entire expression __unknown_anytype.
3485 // This should only be possible with a type written directly.
3486 if (const FunctionProtoType *proto =
3487 dyn_cast<FunctionProtoType>(VD->getType()))
3488 if (proto->getReturnType() == Context.UnknownAnyTy) {
3489 type = Context.UnknownAnyTy;
3490 valueKind = VK_PRValue;
3491 break;
3492 }
3493
3494 // C++ methods are l-values if static, r-values if non-static.
3495 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3496 valueKind = VK_LValue;
3497 break;
3498 }
3499 [[fallthrough]];
3500
3501 case Decl::CXXConversion:
3502 case Decl::CXXDestructor:
3503 case Decl::CXXConstructor:
3504 valueKind = VK_PRValue;
3505 break;
3506 }
3507
3508 auto *E =
3509 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3510 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3511 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3512 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3513 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3514 // diagnostics).
3515 if (VD->isInvalidDecl() && E)
3516 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3517 return E;
3518}
3519
3520static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3521 SmallString<32> &Target) {
3522 Target.resize(CharByteWidth * (Source.size() + 1));
3523 char *ResultPtr = &Target[0];
3524 const llvm::UTF8 *ErrorPtr;
3525 bool success =
3526 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3527 (void)success;
3528 assert(success)(static_cast <bool> (success) ? void (0) : __assert_fail
("success", "clang/lib/Sema/SemaExpr.cpp", 3528, __extension__
__PRETTY_FUNCTION__))
;
3529 Target.resize(ResultPtr - &Target[0]);
3530}
3531
3532ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3533 PredefinedExpr::IdentKind IK) {
3534 // Pick the current block, lambda, captured statement or function.
3535 Decl *currentDecl = nullptr;
3536 if (const BlockScopeInfo *BSI = getCurBlock())
3537 currentDecl = BSI->TheDecl;
3538 else if (const LambdaScopeInfo *LSI = getCurLambda())
3539 currentDecl = LSI->CallOperator;
3540 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3541 currentDecl = CSI->TheCapturedDecl;
3542 else
3543 currentDecl = getCurFunctionOrMethodDecl();
3544
3545 if (!currentDecl) {
3546 Diag(Loc, diag::ext_predef_outside_function);
3547 currentDecl = Context.getTranslationUnitDecl();
3548 }
3549
3550 QualType ResTy;
3551 StringLiteral *SL = nullptr;
3552 if (cast<DeclContext>(currentDecl)->isDependentContext())
3553 ResTy = Context.DependentTy;
3554 else {
3555 // Pre-defined identifiers are of type char[x], where x is the length of
3556 // the string.
3557 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3558 unsigned Length = Str.length();
3559
3560 llvm::APInt LengthI(32, Length + 1);
3561 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3562 ResTy =
3563 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3564 SmallString<32> RawChars;
3565 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3566 Str, RawChars);
3567 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3568 ArrayType::Normal,
3569 /*IndexTypeQuals*/ 0);
3570 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3571 /*Pascal*/ false, ResTy, Loc);
3572 } else {
3573 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3574 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3575 ArrayType::Normal,
3576 /*IndexTypeQuals*/ 0);
3577 SL = StringLiteral::Create(Context, Str, StringLiteral::Ordinary,
3578 /*Pascal*/ false, ResTy, Loc);
3579 }
3580 }
3581
3582 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3583}
3584
3585ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3586 SourceLocation LParen,
3587 SourceLocation RParen,
3588 TypeSourceInfo *TSI) {
3589 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3590}
3591
3592ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3593 SourceLocation LParen,
3594 SourceLocation RParen,
3595 ParsedType ParsedTy) {
3596 TypeSourceInfo *TSI = nullptr;
3597 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3598
3599 if (Ty.isNull())
3600 return ExprError();
3601 if (!TSI)
3602 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3603
3604 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3605}
3606
3607ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3608 PredefinedExpr::IdentKind IK;
3609
3610 switch (Kind) {
3611 default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!"
, "clang/lib/Sema/SemaExpr.cpp", 3611)
;
3612 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3613 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3614 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3615 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3616 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3617 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3618 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3619 }
3620
3621 return BuildPredefinedExpr(Loc, IK);
3622}
3623
3624ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3625 SmallString<16> CharBuffer;
3626 bool Invalid = false;
3627 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3628 if (Invalid)
3629 return ExprError();
3630
3631 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3632 PP, Tok.getKind());
3633 if (Literal.hadError())
3634 return ExprError();
3635
3636 QualType Ty;
3637 if (Literal.isWide())
3638 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3639 else if (Literal.isUTF8() && getLangOpts().C2x)
3640 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3641 else if (Literal.isUTF8() && getLangOpts().Char8)
3642 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3643 else if (Literal.isUTF16())
3644 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3645 else if (Literal.isUTF32())
3646 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3647 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3648 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3649 else
3650 Ty = Context.CharTy; // 'x' -> char in C++;
3651 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3652
3653 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3654 if (Literal.isWide())
3655 Kind = CharacterLiteral::Wide;
3656 else if (Literal.isUTF16())
3657 Kind = CharacterLiteral::UTF16;
3658 else if (Literal.isUTF32())
3659 Kind = CharacterLiteral::UTF32;
3660 else if (Literal.isUTF8())
3661 Kind = CharacterLiteral::UTF8;
3662
3663 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3664 Tok.getLocation());
3665
3666 if (Literal.getUDSuffix().empty())
3667 return Lit;
3668
3669 // We're building a user-defined literal.
3670 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3671 SourceLocation UDSuffixLoc =
3672 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3673
3674 // Make sure we're allowed user-defined literals here.
3675 if (!UDLScope)
3676 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3677
3678 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3679 // operator "" X (ch)
3680 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3681 Lit, Tok.getLocation());
3682}
3683
3684ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3685 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3686 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3687 Context.IntTy, Loc);
3688}
3689
3690static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3691 QualType Ty, SourceLocation Loc) {
3692 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3693
3694 using llvm::APFloat;
3695 APFloat Val(Format);
3696
3697 APFloat::opStatus result = Literal.GetFloatValue(Val);
3698
3699 // Overflow is always an error, but underflow is only an error if
3700 // we underflowed to zero (APFloat reports denormals as underflow).
3701 if ((result & APFloat::opOverflow) ||
3702 ((result & APFloat::opUnderflow) && Val.isZero())) {
3703 unsigned diagnostic;
3704 SmallString<20> buffer;
3705 if (result & APFloat::opOverflow) {
3706 diagnostic = diag::warn_float_overflow;
3707 APFloat::getLargest(Format).toString(buffer);
3708 } else {
3709 diagnostic = diag::warn_float_underflow;
3710 APFloat::getSmallest(Format).toString(buffer);
3711 }
3712
3713 S.Diag(Loc, diagnostic)
3714 << Ty
3715 << StringRef(buffer.data(), buffer.size());
3716 }
3717
3718 bool isExact = (result == APFloat::opOK);
3719 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3720}
3721
3722bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3723 assert(E && "Invalid expression")(static_cast <bool> (E && "Invalid expression")
? void (0) : __assert_fail ("E && \"Invalid expression\""
, "clang/lib/Sema/SemaExpr.cpp", 3723, __extension__ __PRETTY_FUNCTION__
))
;
3724
3725 if (E->isValueDependent())
3726 return false;
3727
3728 QualType QT = E->getType();
3729 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3730 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3731 return true;
3732 }
3733
3734 llvm::APSInt ValueAPS;
3735 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3736
3737 if (R.isInvalid())
3738 return true;
3739
3740 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3741 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3742 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3743 << toString(ValueAPS, 10) << ValueIsPositive;
3744 return true;
3745 }
3746
3747 return false;
3748}
3749
3750ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3751 // Fast path for a single digit (which is quite common). A single digit
3752 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3753 if (Tok.getLength() == 1) {
3754 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3755 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3756 }
3757
3758 SmallString<128> SpellingBuffer;
3759 // NumericLiteralParser wants to overread by one character. Add padding to
3760 // the buffer in case the token is copied to the buffer. If getSpelling()
3761 // returns a StringRef to the memory buffer, it should have a null char at
3762 // the EOF, so it is also safe.
3763 SpellingBuffer.resize(Tok.getLength() + 1);
3764
3765 // Get the spelling of the token, which eliminates trigraphs, etc.
3766 bool Invalid = false;
3767 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3768 if (Invalid)
3769 return ExprError();
3770
3771 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3772 PP.getSourceManager(), PP.getLangOpts(),
3773 PP.getTargetInfo(), PP.getDiagnostics());
3774 if (Literal.hadError)
3775 return ExprError();
3776
3777 if (Literal.hasUDSuffix()) {
3778 // We're building a user-defined literal.
3779 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3780 SourceLocation UDSuffixLoc =
3781 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3782
3783 // Make sure we're allowed user-defined literals here.
3784 if (!UDLScope)
3785 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3786
3787 QualType CookedTy;
3788 if (Literal.isFloatingLiteral()) {
3789 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3790 // long double, the literal is treated as a call of the form
3791 // operator "" X (f L)
3792 CookedTy = Context.LongDoubleTy;
3793 } else {
3794 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3795 // unsigned long long, the literal is treated as a call of the form
3796 // operator "" X (n ULL)
3797 CookedTy = Context.UnsignedLongLongTy;
3798 }
3799
3800 DeclarationName OpName =
3801 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3802 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3803 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3804
3805 SourceLocation TokLoc = Tok.getLocation();
3806
3807 // Perform literal operator lookup to determine if we're building a raw
3808 // literal or a cooked one.
3809 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3810 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3811 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3812 /*AllowStringTemplatePack*/ false,
3813 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3814 case LOLR_ErrorNoDiagnostic:
3815 // Lookup failure for imaginary constants isn't fatal, there's still the
3816 // GNU extension producing _Complex types.
3817 break;
3818 case LOLR_Error:
3819 return ExprError();
3820 case LOLR_Cooked: {
3821 Expr *Lit;
3822 if (Literal.isFloatingLiteral()) {
3823 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3824 } else {
3825 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3826 if (Literal.GetIntegerValue(ResultVal))
3827 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3828 << /* Unsigned */ 1;
3829 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3830 Tok.getLocation());
3831 }
3832 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3833 }
3834
3835 case LOLR_Raw: {
3836 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3837 // literal is treated as a call of the form
3838 // operator "" X ("n")
3839 unsigned Length = Literal.getUDSuffixOffset();
3840 QualType StrTy = Context.getConstantArrayType(
3841 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3842 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3843 Expr *Lit =
3844 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3845 StringLiteral::Ordinary,
3846 /*Pascal*/ false, StrTy, &TokLoc, 1);
3847 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3848 }
3849
3850 case LOLR_Template: {
3851 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3852 // template), L is treated as a call fo the form
3853 // operator "" X <'c1', 'c2', ... 'ck'>()
3854 // where n is the source character sequence c1 c2 ... ck.
3855 TemplateArgumentListInfo ExplicitArgs;
3856 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3857 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3858 llvm::APSInt Value(CharBits, CharIsUnsigned);
3859 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3860 Value = TokSpelling[I];
3861 TemplateArgument Arg(Context, Value, Context.CharTy);
3862 TemplateArgumentLocInfo ArgInfo;
3863 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3864 }
3865 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
3866 &ExplicitArgs);
3867 }
3868 case LOLR_StringTemplatePack:
3869 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 3869)
;
3870 }
3871 }
3872
3873 Expr *Res;
3874
3875 if (Literal.isFixedPointLiteral()) {
3876 QualType Ty;
3877
3878 if (Literal.isAccum) {
3879 if (Literal.isHalf) {
3880 Ty = Context.ShortAccumTy;
3881 } else if (Literal.isLong) {
3882 Ty = Context.LongAccumTy;
3883 } else {
3884 Ty = Context.AccumTy;
3885 }
3886 } else if (Literal.isFract) {
3887 if (Literal.isHalf) {
3888 Ty = Context.ShortFractTy;
3889 } else if (Literal.isLong) {
3890 Ty = Context.LongFractTy;
3891 } else {
3892 Ty = Context.FractTy;
3893 }
3894 }
3895
3896 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3897
3898 bool isSigned = !Literal.isUnsigned;
3899 unsigned scale = Context.getFixedPointScale(Ty);
3900 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3901
3902 llvm::APInt Val(bit_width, 0, isSigned);
3903 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3904 bool ValIsZero = Val.isZero() && !Overflowed;
3905
3906 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3907 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3908 // Clause 6.4.4 - The value of a constant shall be in the range of
3909 // representable values for its type, with exception for constants of a
3910 // fract type with a value of exactly 1; such a constant shall denote
3911 // the maximal value for the type.
3912 --Val;
3913 else if (Val.ugt(MaxVal) || Overflowed)
3914 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3915
3916 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3917 Tok.getLocation(), scale);
3918 } else if (Literal.isFloatingLiteral()) {
3919 QualType Ty;
3920 if (Literal.isHalf){
3921 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3922 Ty = Context.HalfTy;
3923 else {
3924 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3925 return ExprError();
3926 }
3927 } else if (Literal.isFloat)
3928 Ty = Context.FloatTy;
3929 else if (Literal.isLong)
3930 Ty = Context.LongDoubleTy;
3931 else if (Literal.isFloat16)
3932 Ty = Context.Float16Ty;
3933 else if (Literal.isFloat128)
3934 Ty = Context.Float128Ty;
3935 else
3936 Ty = Context.DoubleTy;
3937
3938 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3939
3940 if (Ty == Context.DoubleTy) {
3941 if (getLangOpts().SinglePrecisionConstants) {
3942 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3943 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3944 }
3945 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3946 "cl_khr_fp64", getLangOpts())) {
3947 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3948 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3949 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3950 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3951 }
3952 }
3953 } else if (!Literal.isIntegerLiteral()) {
3954 return ExprError();
3955 } else {
3956 QualType Ty;
3957
3958 // 'z/uz' literals are a C++23 feature.
3959 if (Literal.isSizeT)
3960 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3961 ? getLangOpts().CPlusPlus23
3962 ? diag::warn_cxx20_compat_size_t_suffix
3963 : diag::ext_cxx23_size_t_suffix
3964 : diag::err_cxx23_size_t_suffix);
3965
3966 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3967 // but we do not currently support the suffix in C++ mode because it's not
3968 // entirely clear whether WG21 will prefer this suffix to return a library
3969 // type such as std::bit_int instead of returning a _BitInt.
3970 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3971 PP.Diag(Tok.getLocation(), getLangOpts().C2x
3972 ? diag::warn_c2x_compat_bitint_suffix
3973 : diag::ext_c2x_bitint_suffix);
3974
3975 // Get the value in the widest-possible width. What is "widest" depends on
3976 // whether the literal is a bit-precise integer or not. For a bit-precise
3977 // integer type, try to scan the source to determine how many bits are
3978 // needed to represent the value. This may seem a bit expensive, but trying
3979 // to get the integer value from an overly-wide APInt is *extremely*
3980 // expensive, so the naive approach of assuming
3981 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3982 unsigned BitsNeeded =
3983 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3984 Literal.getLiteralDigits(), Literal.getRadix())
3985 : Context.getTargetInfo().getIntMaxTWidth();
3986 llvm::APInt ResultVal(BitsNeeded, 0);
3987
3988 if (Literal.GetIntegerValue(ResultVal)) {
3989 // If this value didn't fit into uintmax_t, error and force to ull.
3990 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3991 << /* Unsigned */ 1;
3992 Ty = Context.UnsignedLongLongTy;
3993 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&(static_cast <bool> (Context.getTypeSize(Ty) == ResultVal
.getBitWidth() && "long long is not intmax_t?") ? void
(0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "clang/lib/Sema/SemaExpr.cpp", 3994, __extension__ __PRETTY_FUNCTION__
))
3994 "long long is not intmax_t?")(static_cast <bool> (Context.getTypeSize(Ty) == ResultVal
.getBitWidth() && "long long is not intmax_t?") ? void
(0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "clang/lib/Sema/SemaExpr.cpp", 3994, __extension__ __PRETTY_FUNCTION__
))
;
3995 } else {
3996 // If this value fits into a ULL, try to figure out what else it fits into
3997 // according to the rules of C99 6.4.4.1p5.
3998
3999 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4000 // be an unsigned int.
4001 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4002
4003 // Check from smallest to largest, picking the smallest type we can.
4004 unsigned Width = 0;
4005
4006 // Microsoft specific integer suffixes are explicitly sized.
4007 if (Literal.MicrosoftInteger) {
4008 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4009 Width = 8;
4010 Ty = Context.CharTy;
4011 } else {
4012 Width = Literal.MicrosoftInteger;
4013 Ty = Context.getIntTypeForBitwidth(Width,
4014 /*Signed=*/!Literal.isUnsigned);
4015 }
4016 }
4017
4018 // Bit-precise integer literals are automagically-sized based on the
4019 // width required by the literal.
4020 if (Literal.isBitInt) {
4021 // The signed version has one more bit for the sign value. There are no
4022 // zero-width bit-precise integers, even if the literal value is 0.
4023 Width = std::max(ResultVal.getActiveBits(), 1u) +
4024 (Literal.isUnsigned ? 0u : 1u);
4025
4026 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4027 // and reset the type to the largest supported width.
4028 unsigned int MaxBitIntWidth =
4029 Context.getTargetInfo().getMaxBitIntWidth();
4030 if (Width > MaxBitIntWidth) {
4031 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4032 << Literal.isUnsigned;
4033 Width = MaxBitIntWidth;
4034 }
4035
4036 // Reset the result value to the smaller APInt and select the correct
4037 // type to be used. Note, we zext even for signed values because the
4038 // literal itself is always an unsigned value (a preceeding - is a
4039 // unary operator, not part of the literal).
4040 ResultVal = ResultVal.zextOrTrunc(Width);
4041 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4042 }
4043
4044 // Check C++23 size_t literals.
4045 if (Literal.isSizeT) {
4046 assert(!Literal.MicrosoftInteger &&(static_cast <bool> (!Literal.MicrosoftInteger &&
"size_t literals can't be Microsoft literals") ? void (0) : __assert_fail
("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\""
, "clang/lib/Sema/SemaExpr.cpp", 4047, __extension__ __PRETTY_FUNCTION__
))
4047 "size_t literals can't be Microsoft literals")(static_cast <bool> (!Literal.MicrosoftInteger &&
"size_t literals can't be Microsoft literals") ? void (0) : __assert_fail
("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\""
, "clang/lib/Sema/SemaExpr.cpp", 4047, __extension__ __PRETTY_FUNCTION__
))
;
4048 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4049 Context.getTargetInfo().getSizeType());
4050
4051 // Does it fit in size_t?
4052 if (ResultVal.isIntN(SizeTSize)) {
4053 // Does it fit in ssize_t?
4054 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4055 Ty = Context.getSignedSizeType();
4056 else if (AllowUnsigned)
4057 Ty = Context.getSizeType();
4058 Width = SizeTSize;
4059 }
4060 }
4061
4062 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4063 !Literal.isSizeT) {
4064 // Are int/unsigned possibilities?
4065 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4066
4067 // Does it fit in a unsigned int?
4068 if (ResultVal.isIntN(IntSize)) {
4069 // Does it fit in a signed int?
4070 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4071 Ty = Context.IntTy;
4072 else if (AllowUnsigned)
4073 Ty = Context.UnsignedIntTy;
4074 Width = IntSize;
4075 }
4076 }
4077
4078 // Are long/unsigned long possibilities?
4079 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4080 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4081
4082 // Does it fit in a unsigned long?
4083 if (ResultVal.isIntN(LongSize)) {
4084 // Does it fit in a signed long?
4085 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4086 Ty = Context.LongTy;
4087 else if (AllowUnsigned)
4088 Ty = Context.UnsignedLongTy;
4089 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4090 // is compatible.
4091 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4092 const unsigned LongLongSize =
4093 Context.getTargetInfo().getLongLongWidth();
4094 Diag(Tok.getLocation(),
4095 getLangOpts().CPlusPlus
4096 ? Literal.isLong
4097 ? diag::warn_old_implicitly_unsigned_long_cxx
4098 : /*C++98 UB*/ diag::
4099 ext_old_implicitly_unsigned_long_cxx
4100 : diag::warn_old_implicitly_unsigned_long)
4101 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4102 : /*will be ill-formed*/ 1);
4103 Ty = Context.UnsignedLongTy;
4104 }
4105 Width = LongSize;
4106 }
4107 }
4108
4109 // Check long long if needed.
4110 if (Ty.isNull() && !Literal.isSizeT) {
4111 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4112
4113 // Does it fit in a unsigned long long?
4114 if (ResultVal.isIntN(LongLongSize)) {
4115 // Does it fit in a signed long long?
4116 // To be compatible with MSVC, hex integer literals ending with the
4117 // LL or i64 suffix are always signed in Microsoft mode.
4118 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4119 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4120 Ty = Context.LongLongTy;
4121 else if (AllowUnsigned)
4122 Ty = Context.UnsignedLongLongTy;
4123 Width = LongLongSize;
4124
4125 // 'long long' is a C99 or C++11 feature, whether the literal
4126 // explicitly specified 'long long' or we needed the extra width.
4127 if (getLangOpts().CPlusPlus)
4128 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4129 ? diag::warn_cxx98_compat_longlong
4130 : diag::ext_cxx11_longlong);
4131 else if (!getLangOpts().C99)
4132 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4133 }
4134 }
4135
4136 // If we still couldn't decide a type, we either have 'size_t' literal
4137 // that is out of range, or a decimal literal that does not fit in a
4138 // signed long long and has no U suffix.
4139 if (Ty.isNull()) {
4140 if (Literal.isSizeT)
4141 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4142 << Literal.isUnsigned;
4143 else
4144 Diag(Tok.getLocation(),
4145 diag::ext_integer_literal_too_large_for_signed);
4146 Ty = Context.UnsignedLongLongTy;
4147 Width = Context.getTargetInfo().getLongLongWidth();
4148 }
4149
4150 if (ResultVal.getBitWidth() != Width)
4151 ResultVal = ResultVal.trunc(Width);
4152 }
4153 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4154 }
4155
4156 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4157 if (Literal.isImaginary) {
4158 Res = new (Context) ImaginaryLiteral(Res,
4159 Context.getComplexType(Res->getType()));
4160
4161 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4162 }
4163 return Res;
4164}
4165
4166ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4167 assert(E && "ActOnParenExpr() missing expr")(static_cast <bool> (E && "ActOnParenExpr() missing expr"
) ? void (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\""
, "clang/lib/Sema/SemaExpr.cpp", 4167, __extension__ __PRETTY_FUNCTION__
))
;
4168 QualType ExprTy = E->getType();
4169 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4170 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4171 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4172 return new (Context) ParenExpr(L, R, E);
4173}
4174
4175static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4176 SourceLocation Loc,
4177 SourceRange ArgRange) {
4178 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4179 // scalar or vector data type argument..."
4180 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4181 // type (C99 6.2.5p18) or void.
4182 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4183 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4184 << T << ArgRange;
4185 return true;
4186 }
4187
4188 assert((T->isVoidType() || !T->isIncompleteType()) &&(static_cast <bool> ((T->isVoidType() || !T->isIncompleteType
()) && "Scalar types should always be complete") ? void
(0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "clang/lib/Sema/SemaExpr.cpp", 4189, __extension__ __PRETTY_FUNCTION__
))
4189 "Scalar types should always be complete")(static_cast <bool> ((T->isVoidType() || !T->isIncompleteType
()) && "Scalar types should always be complete") ? void
(0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "clang/lib/Sema/SemaExpr.cpp", 4189, __extension__ __PRETTY_FUNCTION__
))
;
4190 return false;
4191}
4192
4193static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4194 SourceLocation Loc,
4195 SourceRange ArgRange,
4196 UnaryExprOrTypeTrait TraitKind) {
4197 // Invalid types must be hard errors for SFINAE in C++.
4198 if (S.LangOpts.CPlusPlus)
4199 return true;
4200
4201 // C99 6.5.3.4p1:
4202 if (T->isFunctionType() &&
4203 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4204 TraitKind == UETT_PreferredAlignOf)) {
4205 // sizeof(function)/alignof(function) is allowed as an extension.
4206 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4207 << getTraitSpelling(TraitKind) << ArgRange;
4208 return false;
4209 }
4210
4211 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4212 // this is an error (OpenCL v1.1 s6.3.k)
4213 if (T->isVoidType()) {
4214 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4215 : diag::ext_sizeof_alignof_void_type;
4216 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4217 return false;
4218 }
4219
4220 return true;
4221}
4222
4223static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4224 SourceLocation Loc,
4225 SourceRange ArgRange,
4226 UnaryExprOrTypeTrait TraitKind) {
4227 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4228 // runtime doesn't allow it.
4229 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4230 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4231 << T << (TraitKind == UETT_SizeOf)
4232 << ArgRange;
4233 return true;
4234 }
4235
4236 return false;
4237}
4238
4239/// Check whether E is a pointer from a decayed array type (the decayed
4240/// pointer type is equal to T) and emit a warning if it is.
4241static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4242 const Expr *E) {
4243 // Don't warn if the operation changed the type.
4244 if (T != E->getType())
4245 return;
4246
4247 // Now look for array decays.
4248 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4249 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4250 return;
4251
4252 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4253 << ICE->getType()
4254 << ICE->getSubExpr()->getType();
4255}
4256
4257/// Check the constraints on expression operands to unary type expression
4258/// and type traits.
4259///
4260/// Completes any types necessary and validates the constraints on the operand
4261/// expression. The logic mostly mirrors the type-based overload, but may modify
4262/// the expression as it completes the type for that expression through template
4263/// instantiation, etc.
4264bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4265 UnaryExprOrTypeTrait ExprKind) {
4266 QualType ExprTy = E->getType();
4267 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp"
, 4267, __extension__ __PRETTY_FUNCTION__))
;
4268
4269 bool IsUnevaluatedOperand =
4270 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4271 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4272 if (IsUnevaluatedOperand) {
4273 ExprResult Result = CheckUnevaluatedOperand(E);
4274 if (Result.isInvalid())
4275 return true;
4276 E = Result.get();
4277 }
4278
4279 // The operand for sizeof and alignof is in an unevaluated expression context,
4280 // so side effects could result in unintended consequences.
4281 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4282 // used to build SFINAE gadgets.
4283 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4284 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4285 !E->isInstantiationDependent() &&
4286 !E->getType()->isVariableArrayType() &&
4287 E->HasSideEffects(Context, false))
4288 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4289
4290 if (ExprKind == UETT_VecStep)
4291 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4292 E->getSourceRange());
4293
4294 // Explicitly list some types as extensions.
4295 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4296 E->getSourceRange(), ExprKind))
4297 return false;
4298
4299 // 'alignof' applied to an expression only requires the base element type of
4300 // the expression to be complete. 'sizeof' requires the expression's type to
4301 // be complete (and will attempt to complete it if it's an array of unknown
4302 // bound).
4303 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4304 if (RequireCompleteSizedType(
4305 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4306 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4307 getTraitSpelling(ExprKind), E->getSourceRange()))
4308 return true;
4309 } else {
4310 if (RequireCompleteSizedExprType(
4311 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4312 getTraitSpelling(ExprKind), E->getSourceRange()))
4313 return true;
4314 }
4315
4316 // Completing the expression's type may have changed it.
4317 ExprTy = E->getType();
4318 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp"
, 4318, __extension__ __PRETTY_FUNCTION__))
;
4319
4320 if (ExprTy->isFunctionType()) {
4321 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4322 << getTraitSpelling(ExprKind) << E->getSourceRange();
4323 return true;
4324 }
4325
4326 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4327 E->getSourceRange(), ExprKind))
4328 return true;
4329
4330 if (ExprKind == UETT_SizeOf) {
4331 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4332 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4333 QualType OType = PVD->getOriginalType();
4334 QualType Type = PVD->getType();
4335 if (Type->isPointerType() && OType->isArrayType()) {
4336 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4337 << Type << OType;
4338 Diag(PVD->getLocation(), diag::note_declared_at);
4339 }
4340 }
4341 }
4342
4343 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4344 // decays into a pointer and returns an unintended result. This is most
4345 // likely a typo for "sizeof(array) op x".
4346 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4347 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4348 BO->getLHS());
4349 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4350 BO->getRHS());
4351 }
4352 }
4353
4354 return false;
4355}
4356
4357/// Check the constraints on operands to unary expression and type
4358/// traits.
4359///
4360/// This will complete any types necessary, and validate the various constraints
4361/// on those operands.
4362///
4363/// The UsualUnaryConversions() function is *not* called by this routine.
4364/// C99 6.3.2.1p[2-4] all state:
4365/// Except when it is the operand of the sizeof operator ...
4366///
4367/// C++ [expr.sizeof]p4
4368/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4369/// standard conversions are not applied to the operand of sizeof.
4370///
4371/// This policy is followed for all of the unary trait expressions.
4372bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4373 SourceLocation OpLoc,
4374 SourceRange ExprRange,
4375 UnaryExprOrTypeTrait ExprKind) {
4376 if (ExprType->isDependentType())
4377 return false;
4378
4379 // C++ [expr.sizeof]p2:
4380 // When applied to a reference or a reference type, the result
4381 // is the size of the referenced type.
4382 // C++11 [expr.alignof]p3:
4383 // When alignof is applied to a reference type, the result
4384 // shall be the alignment of the referenced type.
4385 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4386 ExprType = Ref->getPointeeType();
4387
4388 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4389 // When alignof or _Alignof is applied to an array type, the result
4390 // is the alignment of the element type.
4391 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4392 ExprKind == UETT_OpenMPRequiredSimdAlign)
4393 ExprType = Context.getBaseElementType(ExprType);
4394
4395 if (ExprKind == UETT_VecStep)
4396 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4397
4398 // Explicitly list some types as extensions.
4399 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4400 ExprKind))
4401 return false;
4402
4403 if (RequireCompleteSizedType(
4404 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4405 getTraitSpelling(ExprKind), ExprRange))
4406 return true;
4407
4408 if (ExprType->isFunctionType()) {
4409 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4410 << getTraitSpelling(ExprKind) << ExprRange;
4411 return true;
4412 }
4413
4414 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4415 ExprKind))
4416 return true;
4417
4418 return false;
4419}
4420
4421static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4422 // Cannot know anything else if the expression is dependent.
4423 if (E->isTypeDependent())
4424 return false;
4425
4426 if (E->getObjectKind() == OK_BitField) {
4427 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4428 << 1 << E->getSourceRange();
4429 return true;
4430 }
4431
4432 ValueDecl *D = nullptr;
4433 Expr *Inner = E->IgnoreParens();
4434 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4435 D = DRE->getDecl();
4436 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4437 D = ME->getMemberDecl();
4438 }
4439
4440 // If it's a field, require the containing struct to have a
4441 // complete definition so that we can compute the layout.
4442 //
4443 // This can happen in C++11 onwards, either by naming the member
4444 // in a way that is not transformed into a member access expression
4445 // (in an unevaluated operand, for instance), or by naming the member
4446 // in a trailing-return-type.
4447 //
4448 // For the record, since __alignof__ on expressions is a GCC
4449 // extension, GCC seems to permit this but always gives the
4450 // nonsensical answer 0.
4451 //
4452 // We don't really need the layout here --- we could instead just
4453 // directly check for all the appropriate alignment-lowing
4454 // attributes --- but that would require duplicating a lot of
4455 // logic that just isn't worth duplicating for such a marginal
4456 // use-case.
4457 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4458 // Fast path this check, since we at least know the record has a
4459 // definition if we can find a member of it.
4460 if (!FD->getParent()->isCompleteDefinition()) {
4461 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4462 << E->getSourceRange();
4463 return true;
4464 }
4465
4466 // Otherwise, if it's a field, and the field doesn't have
4467 // reference type, then it must have a complete type (or be a
4468 // flexible array member, which we explicitly want to
4469 // white-list anyway), which makes the following checks trivial.
4470 if (!FD->getType()->isReferenceType())
4471 return false;
4472 }
4473
4474 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4475}
4476
4477bool Sema::CheckVecStepExpr(Expr *E) {
4478 E = E->IgnoreParens();
4479
4480 // Cannot know anything else if the expression is dependent.
4481 if (E->isTypeDependent())
4482 return false;
4483
4484 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4485}
4486
4487static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4488 CapturingScopeInfo *CSI) {
4489 assert(T->isVariablyModifiedType())(static_cast <bool> (T->isVariablyModifiedType()) ? void
(0) : __assert_fail ("T->isVariablyModifiedType()", "clang/lib/Sema/SemaExpr.cpp"
, 4489, __extension__ __PRETTY_FUNCTION__))
;
4490 assert(CSI != nullptr)(static_cast <bool> (CSI != nullptr) ? void (0) : __assert_fail
("CSI != nullptr", "clang/lib/Sema/SemaExpr.cpp", 4490, __extension__
__PRETTY_FUNCTION__))
;
4491
4492 // We're going to walk down into the type and look for VLA expressions.
4493 do {
4494 const Type *Ty = T.getTypePtr();
4495 switch (Ty->getTypeClass()) {
4496#define TYPE(Class, Base)
4497#define ABSTRACT_TYPE(Class, Base)
4498#define NON_CANONICAL_TYPE(Class, Base)
4499#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4500#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4501#include "clang/AST/TypeNodes.inc"
4502 T = QualType();
4503 break;
4504 // These types are never variably-modified.
4505 case Type::Builtin:
4506 case Type::Complex:
4507 case Type::Vector:
4508 case Type::ExtVector:
4509 case Type::ConstantMatrix:
4510 case Type::Record:
4511 case Type::Enum:
4512 case Type::TemplateSpecialization:
4513 case Type::ObjCObject:
4514 case Type::ObjCInterface:
4515 case Type::ObjCObjectPointer:
4516 case Type::ObjCTypeParam:
4517 case Type::Pipe:
4518 case Type::BitInt:
4519 llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!"
, "clang/lib/Sema/SemaExpr.cpp", 4519)
;
4520 case Type::Elaborated:
4521 T = cast<ElaboratedType>(Ty)->getNamedType();
4522 break;
4523 case Type::Adjusted:
4524 T = cast<AdjustedType>(Ty)->getOriginalType();
4525 break;
4526 case Type::Decayed:
4527 T = cast<DecayedType>(Ty)->getPointeeType();
4528 break;
4529 case Type::Pointer:
4530 T = cast<PointerType>(Ty)->getPointeeType();
4531 break;
4532 case Type::BlockPointer:
4533 T = cast<BlockPointerType>(Ty)->getPointeeType();
4534 break;
4535 case Type::LValueReference:
4536 case Type::RValueReference:
4537 T = cast<ReferenceType>(Ty)->getPointeeType();
4538 break;
4539 case Type::MemberPointer:
4540 T = cast<MemberPointerType>(Ty)->getPointeeType();
4541 break;
4542 case Type::ConstantArray:
4543 case Type::IncompleteArray:
4544 // Losing element qualification here is fine.
4545 T = cast<ArrayType>(Ty)->getElementType();
4546 break;
4547 case Type::VariableArray: {
4548 // Losing element qualification here is fine.
4549 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4550
4551 // Unknown size indication requires no size computation.
4552 // Otherwise, evaluate and record it.
4553 auto Size = VAT->getSizeExpr();
4554 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4555 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4556 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4557
4558 T = VAT->getElementType();
4559 break;
4560 }
4561 case Type::FunctionProto:
4562 case Type::FunctionNoProto:
4563 T = cast<FunctionType>(Ty)->getReturnType();
4564 break;
4565 case Type::Paren:
4566 case Type::TypeOf:
4567 case Type::UnaryTransform:
4568 case Type::Attributed:
4569 case Type::BTFTagAttributed:
4570 case Type::SubstTemplateTypeParm:
4571 case Type::MacroQualified:
4572 // Keep walking after single level desugaring.
4573 T = T.getSingleStepDesugaredType(Context);
4574 break;
4575 case Type::Typedef:
4576 T = cast<TypedefType>(Ty)->desugar();
4577 break;
4578 case Type::Decltype:
4579 T = cast<DecltypeType>(Ty)->desugar();
4580 break;
4581 case Type::Using:
4582 T = cast<UsingType>(Ty)->desugar();
4583 break;
4584 case Type::Auto:
4585 case Type::DeducedTemplateSpecialization:
4586 T = cast<DeducedType>(Ty)->getDeducedType();
4587 break;
4588 case Type::TypeOfExpr:
4589 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4590 break;
4591 case Type::Atomic:
4592 T = cast<AtomicType>(Ty)->getValueType();
4593 break;
4594 }
4595 } while (!T.isNull() && T->isVariablyModifiedType());
4596}
4597
4598/// Build a sizeof or alignof expression given a type operand.
4599ExprResult
4600Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4601 SourceLocation OpLoc,
4602 UnaryExprOrTypeTrait ExprKind,
4603 SourceRange R) {
4604 if (!TInfo)
4605 return ExprError();
4606
4607 QualType T = TInfo->getType();
4608
4609 if (!T->isDependentType() &&
4610 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4611 return ExprError();
4612
4613 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4614 if (auto *TT = T->getAs<TypedefType>()) {
4615 for (auto I = FunctionScopes.rbegin(),
4616 E = std::prev(FunctionScopes.rend());
4617 I != E; ++I) {
4618 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4619 if (CSI == nullptr)
4620 break;
4621 DeclContext *DC = nullptr;
4622 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4623 DC = LSI->CallOperator;
4624 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4625 DC = CRSI->TheCapturedDecl;
4626 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4627 DC = BSI->TheDecl;
4628 if (DC) {
4629 if (DC->containsDecl(TT->getDecl()))
4630 break;
4631 captureVariablyModifiedType(Context, T, CSI);
4632 }
4633 }
4634 }
4635 }
4636
4637 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4638 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4639 TInfo->getType()->isVariablyModifiedType())
4640 TInfo = TransformToPotentiallyEvaluated(TInfo);
4641
4642 return new (Context) UnaryExprOrTypeTraitExpr(
4643 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4644}
4645
4646/// Build a sizeof or alignof expression given an expression
4647/// operand.
4648ExprResult
4649Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4650 UnaryExprOrTypeTrait ExprKind) {
4651 ExprResult PE = CheckPlaceholderExpr(E);
4652 if (PE.isInvalid())
4653 return ExprError();
4654
4655 E = PE.get();
4656
4657 // Verify that the operand is valid.
4658 bool isInvalid = false;
4659 if (E->isTypeDependent()) {
4660 // Delay type-checking for type-dependent expressions.
4661 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4662 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4663 } else if (ExprKind == UETT_VecStep) {
4664 isInvalid = CheckVecStepExpr(E);
4665 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4666 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4667 isInvalid = true;
4668 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4669 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4670 isInvalid = true;
4671 } else {
4672 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4673 }
4674
4675 if (isInvalid)
4676 return ExprError();
4677
4678 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4679 PE = TransformToPotentiallyEvaluated(E);
4680 if (PE.isInvalid()) return ExprError();
4681 E = PE.get();
4682 }
4683
4684 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4685 return new (Context) UnaryExprOrTypeTraitExpr(
4686 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4687}
4688
4689/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4690/// expr and the same for @c alignof and @c __alignof
4691/// Note that the ArgRange is invalid if isType is false.
4692ExprResult
4693Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4694 UnaryExprOrTypeTrait ExprKind, bool IsType,
4695 void *TyOrEx, SourceRange ArgRange) {
4696 // If error parsing type, ignore.
4697 if (!TyOrEx) return ExprError();
4698
4699 if (IsType) {
4700 TypeSourceInfo *TInfo;
4701 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4702 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4703 }
4704
4705 Expr *ArgEx = (Expr *)TyOrEx;
4706 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4707 return Result;
4708}
4709
4710static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4711 bool IsReal) {
4712 if (V.get()->isTypeDependent())
4713 return S.Context.DependentTy;
4714
4715 // _Real and _Imag are only l-values for normal l-values.
4716 if (V.get()->getObjectKind() != OK_Ordinary) {
4717 V = S.DefaultLvalueConversion(V.get());
4718 if (V.isInvalid())
4719 return QualType();
4720 }
4721
4722 // These operators return the element type of a complex type.
4723 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4724 return CT->getElementType();
4725
4726 // Otherwise they pass through real integer and floating point types here.
4727 if (V.get()->getType()->isArithmeticType())
4728 return V.get()->getType();
4729
4730 // Test for placeholders.
4731 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4732 if (PR.isInvalid()) return QualType();
4733 if (PR.get() != V.get()) {
4734 V = PR;
4735 return CheckRealImagOperand(S, V, Loc, IsReal);
4736 }
4737
4738 // Reject anything else.
4739 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4740 << (IsReal ? "__real" : "__imag");
4741 return QualType();
4742}
4743
4744
4745
4746ExprResult
4747Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4748 tok::TokenKind Kind, Expr *Input) {
4749 UnaryOperatorKind Opc;
4750 switch (Kind) {
4751 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp"
, 4751)
;
4752 case tok::plusplus: Opc = UO_PostInc; break;
4753 case tok::minusminus: Opc = UO_PostDec; break;
4754 }
4755
4756 // Since this might is a postfix expression, get rid of ParenListExprs.
4757 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4758 if (Result.isInvalid()) return ExprError();
4759 Input = Result.get();
4760
4761 return BuildUnaryOp(S, OpLoc, Opc, Input);
4762}
4763
4764/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4765///
4766/// \return true on error
4767static bool checkArithmeticOnObjCPointer(Sema &S,
4768 SourceLocation opLoc,
4769 Expr *op) {
4770 assert(op->getType()->isObjCObjectPointerType())(static_cast <bool> (op->getType()->isObjCObjectPointerType
()) ? void (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 4770, __extension__ __PRETTY_FUNCTION__
))
;
4771 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4772 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4773 return false;
4774
4775 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4776 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4777 << op->getSourceRange();
4778 return true;
4779}
4780
4781static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4782 auto *BaseNoParens = Base->IgnoreParens();
4783 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4784 return MSProp->getPropertyDecl()->getType()->isArrayType();
4785 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4786}
4787
4788// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4789// Typically this is DependentTy, but can sometimes be more precise.
4790//
4791// There are cases when we could determine a non-dependent type:
4792// - LHS and RHS may have non-dependent types despite being type-dependent
4793// (e.g. unbounded array static members of the current instantiation)
4794// - one may be a dependent-sized array with known element type
4795// - one may be a dependent-typed valid index (enum in current instantiation)
4796//
4797// We *always* return a dependent type, in such cases it is DependentTy.
4798// This avoids creating type-dependent expressions with non-dependent types.
4799// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4800static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4801 const ASTContext &Ctx) {
4802 assert(LHS->isTypeDependent() || RHS->isTypeDependent())(static_cast <bool> (LHS->isTypeDependent() || RHS->
isTypeDependent()) ? void (0) : __assert_fail ("LHS->isTypeDependent() || RHS->isTypeDependent()"
, "clang/lib/Sema/SemaExpr.cpp", 4802, __extension__ __PRETTY_FUNCTION__
))
;
4803 QualType LTy = LHS->getType(), RTy = RHS->getType();
4804 QualType Result = Ctx.DependentTy;
4805 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4806 if (const PointerType *PT = LTy->getAs<PointerType>())
4807 Result = PT->getPointeeType();
4808 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4809 Result = AT->getElementType();
4810 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4811 if (const PointerType *PT = RTy->getAs<PointerType>())
4812 Result = PT->getPointeeType();
4813 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4814 Result = AT->getElementType();
4815 }
4816 // Ensure we return a dependent type.
4817 return Result->isDependentType() ? Result : Ctx.DependentTy;
4818}
4819
4820static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4821
4822ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4823 SourceLocation lbLoc,
4824 MultiExprArg ArgExprs,
4825 SourceLocation rbLoc) {
4826
4827 if (base && !base->getType().isNull() &&
19
Assuming 'base' is null
20
Taking false branch
4828 base->hasPlaceholderType(BuiltinType::OMPArraySection))
4829 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4830 SourceLocation(), /*Length*/ nullptr,
4831 /*Stride=*/nullptr, rbLoc);
4832
4833 // Since this might be a postfix expression, get rid of ParenListExprs.
4834 if (isa<ParenListExpr>(base)) {
21
Assuming 'base' is not a 'ParenListExpr'
22
Taking false branch
4835 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4836 if (result.isInvalid())
4837 return ExprError();
4838 base = result.get();
4839 }
4840
4841 // Check if base and idx form a MatrixSubscriptExpr.
4842 //
4843 // Helper to check for comma expressions, which are not allowed as indices for
4844 // matrix subscript expressions.
4845 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4846 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4847 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4848 << SourceRange(base->getBeginLoc(), rbLoc);
4849 return true;
4850 }
4851 return false;
4852 };
4853 // The matrix subscript operator ([][])is considered a single operator.
4854 // Separating the index expressions by parenthesis is not allowed.
4855 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
23
Called C++ object pointer is null
4856 !isa<MatrixSubscriptExpr>(base)) {
4857 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4858 << SourceRange(base->getBeginLoc(), rbLoc);
4859 return ExprError();
4860 }
4861 // If the base is a MatrixSubscriptExpr, try to create a new
4862 // MatrixSubscriptExpr.
4863 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4864 if (matSubscriptE) {
4865 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4865, __extension__ __PRETTY_FUNCTION__))
;
4866 if (CheckAndReportCommaError(ArgExprs.front()))
4867 return ExprError();
4868
4869 assert(matSubscriptE->isIncomplete() &&(static_cast <bool> (matSubscriptE->isIncomplete() &&
"base has to be an incomplete matrix subscript") ? void (0) :
__assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\""
, "clang/lib/Sema/SemaExpr.cpp", 4870, __extension__ __PRETTY_FUNCTION__
))
4870 "base has to be an incomplete matrix subscript")(static_cast <bool> (matSubscriptE->isIncomplete() &&
"base has to be an incomplete matrix subscript") ? void (0) :
__assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\""
, "clang/lib/Sema/SemaExpr.cpp", 4870, __extension__ __PRETTY_FUNCTION__
))
;
4871 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4872 matSubscriptE->getRowIdx(),
4873 ArgExprs.front(), rbLoc);
4874 }
4875
4876 // Handle any non-overload placeholder types in the base and index
4877 // expressions. We can't handle overloads here because the other
4878 // operand might be an overloadable type, in which case the overload
4879 // resolution for the operator overload should get the first crack
4880 // at the overload.
4881 bool IsMSPropertySubscript = false;
4882 if (base->getType()->isNonOverloadPlaceholderType()) {
4883 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4884 if (!IsMSPropertySubscript) {
4885 ExprResult result = CheckPlaceholderExpr(base);
4886 if (result.isInvalid())
4887 return ExprError();
4888 base = result.get();
4889 }
4890 }
4891
4892 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4893 if (base->getType()->isMatrixType()) {
4894 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4894, __extension__ __PRETTY_FUNCTION__))
;
4895 if (CheckAndReportCommaError(ArgExprs.front()))
4896 return ExprError();
4897
4898 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4899 rbLoc);
4900 }
4901
4902 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4903 Expr *idx = ArgExprs[0];
4904 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4905 (isa<CXXOperatorCallExpr>(idx) &&
4906 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4907 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4908 << SourceRange(base->getBeginLoc(), rbLoc);
4909 }
4910 }
4911
4912 if (ArgExprs.size() == 1 &&
4913 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4914 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4915 if (result.isInvalid())
4916 return ExprError();
4917 ArgExprs[0] = result.get();
4918 } else {
4919 if (checkArgsForPlaceholders(*this, ArgExprs))
4920 return ExprError();
4921 }
4922
4923 // Build an unanalyzed expression if either operand is type-dependent.
4924 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4925 (base->isTypeDependent() ||
4926 Expr::hasAnyTypeDependentArguments(ArgExprs)) &&
4927 !isa<PackExpansionExpr>(ArgExprs[0])) {
4928 return new (Context) ArraySubscriptExpr(
4929 base, ArgExprs.front(),
4930 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4931 VK_LValue, OK_Ordinary, rbLoc);
4932 }
4933
4934 // MSDN, property (C++)
4935 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4936 // This attribute can also be used in the declaration of an empty array in a
4937 // class or structure definition. For example:
4938 // __declspec(property(get=GetX, put=PutX)) int x[];
4939 // The above statement indicates that x[] can be used with one or more array
4940 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4941 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4942 if (IsMSPropertySubscript) {
4943 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4943, __extension__ __PRETTY_FUNCTION__))
;
4944 // Build MS property subscript expression if base is MS property reference
4945 // or MS property subscript.
4946 return new (Context)
4947 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4948 VK_LValue, OK_Ordinary, rbLoc);
4949 }
4950
4951 // Use C++ overloaded-operator rules if either operand has record
4952 // type. The spec says to do this if either type is *overloadable*,
4953 // but enum types can't declare subscript operators or conversion
4954 // operators, so there's nothing interesting for overload resolution
4955 // to do if there aren't any record types involved.
4956 //
4957 // ObjC pointers have their own subscripting logic that is not tied
4958 // to overload resolution and so should not take this path.
4959 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4960 ((base->getType()->isRecordType() ||
4961 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
4962 ArgExprs[0]->getType()->isRecordType())))) {
4963 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4964 }
4965
4966 ExprResult Res =
4967 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4968
4969 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4970 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4971
4972 return Res;
4973}
4974
4975ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4976 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4977 InitializationKind Kind =
4978 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4979 InitializationSequence InitSeq(*this, Entity, Kind, E);
4980 return InitSeq.Perform(*this, Entity, Kind, E);
4981}
4982
4983ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4984 Expr *ColumnIdx,
4985 SourceLocation RBLoc) {
4986 ExprResult BaseR = CheckPlaceholderExpr(Base);
4987 if (BaseR.isInvalid())
4988 return BaseR;
4989 Base = BaseR.get();
4990
4991 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4992 if (RowR.isInvalid())
4993 return RowR;
4994 RowIdx = RowR.get();
4995
4996 if (!ColumnIdx)
4997 return new (Context) MatrixSubscriptExpr(
4998 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4999
5000 // Build an unanalyzed expression if any of the operands is type-dependent.
5001 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5002 ColumnIdx->isTypeDependent())
5003 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5004 Context.DependentTy, RBLoc);
5005
5006 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5007 if (ColumnR.isInvalid())
5008 return ColumnR;
5009 ColumnIdx = ColumnR.get();
5010
5011 // Check that IndexExpr is an integer expression. If it is a constant
5012 // expression, check that it is less than Dim (= the number of elements in the
5013 // corresponding dimension).
5014 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5015 bool IsColumnIdx) -> Expr * {
5016 if (!IndexExpr->getType()->isIntegerType() &&
5017 !IndexExpr->isTypeDependent()) {
5018 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5019 << IsColumnIdx;
5020 return nullptr;
5021 }
5022
5023 if (std::optional<llvm::APSInt> Idx =
5024 IndexExpr->getIntegerConstantExpr(Context)) {
5025 if ((*Idx < 0 || *Idx >= Dim)) {
5026 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5027 << IsColumnIdx << Dim;
5028 return nullptr;
5029 }
5030 }
5031
5032 ExprResult ConvExpr =
5033 tryConvertExprToType(IndexExpr, Context.getSizeType());
5034 assert(!ConvExpr.isInvalid() &&(static_cast <bool> (!ConvExpr.isInvalid() && "should be able to convert any integer type to size type"
) ? void (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\""
, "clang/lib/Sema/SemaExpr.cpp", 5035, __extension__ __PRETTY_FUNCTION__
))
5035 "should be able to convert any integer type to size type")(static_cast <bool> (!ConvExpr.isInvalid() && "should be able to convert any integer type to size type"
) ? void (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\""
, "clang/lib/Sema/SemaExpr.cpp", 5035, __extension__ __PRETTY_FUNCTION__
))
;
5036 return ConvExpr.get();
5037 };
5038
5039 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5040 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5041 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5042 if (!RowIdx || !ColumnIdx)
5043 return ExprError();
5044
5045 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5046 MTy->getElementType(), RBLoc);
5047}
5048
5049void Sema::CheckAddressOfNoDeref(const Expr *E) {
5050 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5051 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5052
5053 // For expressions like `&(*s).b`, the base is recorded and what should be
5054 // checked.
5055 const MemberExpr *Member = nullptr;
5056 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5057 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5058
5059 LastRecord.PossibleDerefs.erase(StrippedExpr);
5060}
5061
5062void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5063 if (isUnevaluatedContext())
5064 return;
5065
5066 QualType ResultTy = E->getType();
5067 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5068
5069 // Bail if the element is an array since it is not memory access.
5070 if (isa<ArrayType>(ResultTy))
5071 return;
5072
5073 if (ResultTy->hasAttr(attr::NoDeref)) {
5074 LastRecord.PossibleDerefs.insert(E);
5075 return;
5076 }
5077
5078 // Check if the base type is a pointer to a member access of a struct
5079 // marked with noderef.
5080 const Expr *Base = E->getBase();
5081 QualType BaseTy = Base->getType();
5082 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5083 // Not a pointer access
5084 return;
5085
5086 const MemberExpr *Member = nullptr;
5087 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5088 Member->isArrow())
5089 Base = Member->getBase();
5090
5091 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5092 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5093 LastRecord.PossibleDerefs.insert(E);
5094 }
5095}
5096
5097ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5098 Expr *LowerBound,
5099 SourceLocation ColonLocFirst,
5100 SourceLocation ColonLocSecond,
5101 Expr *Length, Expr *Stride,
5102 SourceLocation RBLoc) {
5103 if (Base->hasPlaceholderType() &&
5104 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5105 ExprResult Result = CheckPlaceholderExpr(Base);
5106 if (Result.isInvalid())
5107 return ExprError();
5108 Base = Result.get();
5109 }
5110 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5111 ExprResult Result = CheckPlaceholderExpr(LowerBound);
5112 if (Result.isInvalid())
5113 return ExprError();
5114 Result = DefaultLvalueConversion(Result.get());
5115 if (Result.isInvalid())
5116 return ExprError();
5117 LowerBound = Result.get();
5118 }
5119 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5120 ExprResult Result = CheckPlaceholderExpr(Length);
5121 if (Result.isInvalid())
5122 return ExprError();
5123 Result = DefaultLvalueConversion(Result.get());
5124 if (Result.isInvalid())
5125 return ExprError();
5126 Length = Result.get();
5127 }
5128 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5129 ExprResult Result = CheckPlaceholderExpr(Stride);
5130 if (Result.isInvalid())
5131 return ExprError();
5132 Result = DefaultLvalueConversion(Result.get());
5133 if (Result.isInvalid())
5134 return ExprError();
5135 Stride = Result.get();
5136 }
5137
5138 // Build an unanalyzed expression if either operand is type-dependent.
5139 if (Base->isTypeDependent() ||
5140 (LowerBound &&
5141 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5142 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5143 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5144 return new (Context) OMPArraySectionExpr(
5145 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5146 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5147 }
5148
5149 // Perform default conversions.
5150 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5151 QualType ResultTy;
5152 if (OriginalTy->isAnyPointerType()) {
5153 ResultTy = OriginalTy->getPointeeType();
5154 } else if (OriginalTy->isArrayType()) {
5155 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5156 } else {
5157 return ExprError(
5158 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5159 << Base->getSourceRange());
5160 }
5161 // C99 6.5.2.1p1
5162 if (LowerBound) {
5163 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5164 LowerBound);
5165 if (Res.isInvalid())
5166 return ExprError(Diag(LowerBound->getExprLoc(),
5167 diag::err_omp_typecheck_section_not_integer)
5168 << 0 << LowerBound->getSourceRange());
5169 LowerBound = Res.get();
5170
5171 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5172 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5173 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5174 << 0 << LowerBound->getSourceRange();
5175 }
5176 if (Length) {
5177 auto Res =
5178 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5179 if (Res.isInvalid())
5180 return ExprError(Diag(Length->getExprLoc(),
5181 diag::err_omp_typecheck_section_not_integer)
5182 << 1 << Length->getSourceRange());
5183 Length = Res.get();
5184
5185 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5186 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5187 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5188 << 1 << Length->getSourceRange();
5189 }
5190 if (Stride) {
5191 ExprResult Res =
5192 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5193 if (Res.isInvalid())
5194 return ExprError(Diag(Stride->getExprLoc(),
5195 diag::err_omp_typecheck_section_not_integer)
5196 << 1 << Stride->getSourceRange());
5197 Stride = Res.get();
5198
5199 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5200 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5201 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5202 << 1 << Stride->getSourceRange();
5203 }
5204
5205 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5206 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5207 // type. Note that functions are not objects, and that (in C99 parlance)
5208 // incomplete types are not object types.
5209 if (ResultTy->isFunctionType()) {
5210 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5211 << ResultTy << Base->getSourceRange();
5212 return ExprError();
5213 }
5214
5215 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5216 diag::err_omp_section_incomplete_type, Base))
5217 return ExprError();
5218
5219 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5220 Expr::EvalResult Result;
5221 if (LowerBound->EvaluateAsInt(Result, Context)) {
5222 // OpenMP 5.0, [2.1.5 Array Sections]
5223 // The array section must be a subset of the original array.
5224 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5225 if (LowerBoundValue.isNegative()) {
5226 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5227 << LowerBound->getSourceRange();
5228 return ExprError();
5229 }
5230 }
5231 }
5232
5233 if (Length) {
5234 Expr::EvalResult Result;
5235 if (Length->EvaluateAsInt(Result, Context)) {
5236 // OpenMP 5.0, [2.1.5 Array Sections]
5237 // The length must evaluate to non-negative integers.
5238 llvm::APSInt LengthValue = Result.Val.getInt();
5239 if (LengthValue.isNegative()) {
5240 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5241 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5242 << Length->getSourceRange();
5243 return ExprError();
5244 }
5245 }
5246 } else if (ColonLocFirst.isValid() &&
5247 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5248 !OriginalTy->isVariableArrayType()))) {
5249 // OpenMP 5.0, [2.1.5 Array Sections]
5250 // When the size of the array dimension is not known, the length must be
5251 // specified explicitly.
5252 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5253 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5254 return ExprError();
5255 }
5256
5257 if (Stride) {
5258 Expr::EvalResult Result;
5259 if (Stride->EvaluateAsInt(Result, Context)) {
5260 // OpenMP 5.0, [2.1.5 Array Sections]
5261 // The stride must evaluate to a positive integer.
5262 llvm::APSInt StrideValue = Result.Val.getInt();
5263 if (!StrideValue.isStrictlyPositive()) {
5264 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5265 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5266 << Stride->getSourceRange();
5267 return ExprError();
5268 }
5269 }
5270 }
5271
5272 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5273 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5274 if (Result.isInvalid())
5275 return ExprError();
5276 Base = Result.get();
5277 }
5278 return new (Context) OMPArraySectionExpr(
5279 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5280 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5281}
5282
5283ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5284 SourceLocation RParenLoc,
5285 ArrayRef<Expr *> Dims,
5286 ArrayRef<SourceRange> Brackets) {
5287 if (Base->hasPlaceholderType()) {
5288 ExprResult Result = CheckPlaceholderExpr(Base);
5289 if (Result.isInvalid())
5290 return ExprError();
5291 Result = DefaultLvalueConversion(Result.get());
5292 if (Result.isInvalid())
5293 return ExprError();
5294 Base = Result.get();
5295 }
5296 QualType BaseTy = Base->getType();
5297 // Delay analysis of the types/expressions if instantiation/specialization is
5298 // required.
5299 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5300 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5301 LParenLoc, RParenLoc, Dims, Brackets);
5302 if (!BaseTy->isPointerType() ||
5303 (!Base->isTypeDependent() &&
5304 BaseTy->getPointeeType()->isIncompleteType()))
5305 return ExprError(Diag(Base->getExprLoc(),
5306 diag::err_omp_non_pointer_type_array_shaping_base)
5307 << Base->getSourceRange());
5308
5309 SmallVector<Expr *, 4> NewDims;
5310 bool ErrorFound = false;
5311 for (Expr *Dim : Dims) {
5312 if (Dim->hasPlaceholderType()) {
5313 ExprResult Result = CheckPlaceholderExpr(Dim);
5314 if (Result.isInvalid()) {
5315 ErrorFound = true;
5316 continue;
5317 }
5318 Result = DefaultLvalueConversion(Result.get());
5319 if (Result.isInvalid()) {
5320 ErrorFound = true;
5321 continue;
5322 }
5323 Dim = Result.get();
5324 }
5325 if (!Dim->isTypeDependent()) {
5326 ExprResult Result =
5327 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5328 if (Result.isInvalid()) {
5329 ErrorFound = true;
5330 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5331 << Dim->getSourceRange();
5332 continue;
5333 }
5334 Dim = Result.get();
5335 Expr::EvalResult EvResult;
5336 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5337 // OpenMP 5.0, [2.1.4 Array Shaping]
5338 // Each si is an integral type expression that must evaluate to a
5339 // positive integer.
5340 llvm::APSInt Value = EvResult.Val.getInt();
5341 if (!Value.isStrictlyPositive()) {
5342 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5343 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5344 << Dim->getSourceRange();
5345 ErrorFound = true;
5346 continue;
5347 }
5348 }
5349 }
5350 NewDims.push_back(Dim);
5351 }
5352 if (ErrorFound)
5353 return ExprError();
5354 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5355 LParenLoc, RParenLoc, NewDims, Brackets);
5356}
5357
5358ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5359 SourceLocation LLoc, SourceLocation RLoc,
5360 ArrayRef<OMPIteratorData> Data) {
5361 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5362 bool IsCorrect = true;
5363 for (const OMPIteratorData &D : Data) {
5364 TypeSourceInfo *TInfo = nullptr;
5365 SourceLocation StartLoc;
5366 QualType DeclTy;
5367 if (!D.Type.getAsOpaquePtr()) {
5368 // OpenMP 5.0, 2.1.6 Iterators
5369 // In an iterator-specifier, if the iterator-type is not specified then
5370 // the type of that iterator is of int type.
5371 DeclTy = Context.IntTy;
5372 StartLoc = D.DeclIdentLoc;
5373 } else {
5374 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5375 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5376 }
5377
5378 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5379 DeclTy->containsUnexpandedParameterPack() ||
5380 DeclTy->isInstantiationDependentType();
5381 if (!IsDeclTyDependent) {
5382 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5383 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5384 // The iterator-type must be an integral or pointer type.
5385 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5386 << DeclTy;
5387 IsCorrect = false;
5388 continue;
5389 }
5390 if (DeclTy.isConstant(Context)) {
5391 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5392 // The iterator-type must not be const qualified.
5393 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5394 << DeclTy;
5395 IsCorrect = false;
5396 continue;
5397 }
5398 }
5399
5400 // Iterator declaration.
5401 assert(D.DeclIdent && "Identifier expected.")(static_cast <bool> (D.DeclIdent && "Identifier expected."
) ? void (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\""
, "clang/lib/Sema/SemaExpr.cpp", 5401, __extension__ __PRETTY_FUNCTION__
))
;
5402 // Always try to create iterator declarator to avoid extra error messages
5403 // about unknown declarations use.
5404 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5405 D.DeclIdent, DeclTy, TInfo, SC_None);
5406 VD->setImplicit();
5407 if (S) {
5408 // Check for conflicting previous declaration.
5409 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5410 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5411 ForVisibleRedeclaration);
5412 Previous.suppressDiagnostics();
5413 LookupName(Previous, S);
5414
5415 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5416 /*AllowInlineNamespace=*/false);
5417 if (!Previous.empty()) {
5418 NamedDecl *Old = Previous.getRepresentativeDecl();
5419 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5420 Diag(Old->getLocation(), diag::note_previous_definition);
5421 } else {
5422 PushOnScopeChains(VD, S);
5423 }
5424 } else {
5425 CurContext->addDecl(VD);
5426 }
5427
5428 /// Act on the iterator variable declaration.
5429 ActOnOpenMPIteratorVarDecl(VD);
5430
5431 Expr *Begin = D.Range.Begin;
5432 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5433 ExprResult BeginRes =
5434 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5435 Begin = BeginRes.get();
5436 }
5437 Expr *End = D.Range.End;
5438 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5439 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5440 End = EndRes.get();
5441 }
5442 Expr *Step = D.Range.Step;
5443 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5444 if (!Step->getType()->isIntegralType(Context)) {
5445 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5446 << Step << Step->getSourceRange();
5447 IsCorrect = false;
5448 continue;
5449 }
5450 std::optional<llvm::APSInt> Result =
5451 Step->getIntegerConstantExpr(Context);
5452 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5453 // If the step expression of a range-specification equals zero, the
5454 // behavior is unspecified.
5455 if (Result && Result->isZero()) {
5456 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5457 << Step << Step->getSourceRange();
5458 IsCorrect = false;
5459 continue;
5460 }
5461 }
5462 if (!Begin || !End || !IsCorrect) {
5463 IsCorrect = false;
5464 continue;
5465 }
5466 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5467 IDElem.IteratorDecl = VD;
5468 IDElem.AssignmentLoc = D.AssignLoc;
5469 IDElem.Range.Begin = Begin;
5470 IDElem.Range.End = End;
5471 IDElem.Range.Step = Step;
5472 IDElem.ColonLoc = D.ColonLoc;
5473 IDElem.SecondColonLoc = D.SecColonLoc;
5474 }
5475 if (!IsCorrect) {
5476 // Invalidate all created iterator declarations if error is found.
5477 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5478 if (Decl *ID = D.IteratorDecl)
5479 ID->setInvalidDecl();
5480 }
5481 return ExprError();
5482 }
5483 SmallVector<OMPIteratorHelperData, 4> Helpers;
5484 if (!CurContext->isDependentContext()) {
5485 // Build number of ityeration for each iteration range.
5486 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5487 // ((Begini-Stepi-1-Endi) / -Stepi);
5488 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5489 // (Endi - Begini)
5490 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5491 D.Range.Begin);
5492 if(!Res.isUsable()) {
5493 IsCorrect = false;
5494 continue;
5495 }
5496 ExprResult St, St1;
5497 if (D.Range.Step) {
5498 St = D.Range.Step;
5499 // (Endi - Begini) + Stepi
5500 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5501 if (!Res.isUsable()) {
5502 IsCorrect = false;
5503 continue;
5504 }
5505 // (Endi - Begini) + Stepi - 1
5506 Res =
5507 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5508 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5509 if (!Res.isUsable()) {
5510 IsCorrect = false;
5511 continue;
5512 }
5513 // ((Endi - Begini) + Stepi - 1) / Stepi
5514 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5515 if (!Res.isUsable()) {
5516 IsCorrect = false;
5517 continue;
5518 }
5519 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5520 // (Begini - Endi)
5521 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5522 D.Range.Begin, D.Range.End);
5523 if (!Res1.isUsable()) {
5524 IsCorrect = false;
5525 continue;
5526 }
5527 // (Begini - Endi) - Stepi
5528 Res1 =
5529 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5530 if (!Res1.isUsable()) {
5531 IsCorrect = false;
5532 continue;
5533 }
5534 // (Begini - Endi) - Stepi - 1
5535 Res1 =
5536 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5537 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5538 if (!Res1.isUsable()) {
5539 IsCorrect = false;
5540 continue;
5541 }
5542 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5543 Res1 =
5544 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5545 if (!Res1.isUsable()) {
5546 IsCorrect = false;
5547 continue;
5548 }
5549 // Stepi > 0.
5550 ExprResult CmpRes =
5551 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5552 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5553 if (!CmpRes.isUsable()) {
5554 IsCorrect = false;
5555 continue;
5556 }
5557 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5558 Res.get(), Res1.get());
5559 if (!Res.isUsable()) {
5560 IsCorrect = false;
5561 continue;
5562 }
5563 }
5564 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5565 if (!Res.isUsable()) {
5566 IsCorrect = false;
5567 continue;
5568 }
5569
5570 // Build counter update.
5571 // Build counter.
5572 auto *CounterVD =
5573 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5574 D.IteratorDecl->getBeginLoc(), nullptr,
5575 Res.get()->getType(), nullptr, SC_None);
5576 CounterVD->setImplicit();
5577 ExprResult RefRes =
5578 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5579 D.IteratorDecl->getBeginLoc());
5580 // Build counter update.
5581 // I = Begini + counter * Stepi;
5582 ExprResult UpdateRes;
5583 if (D.Range.Step) {
5584 UpdateRes = CreateBuiltinBinOp(
5585 D.AssignmentLoc, BO_Mul,
5586 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5587 } else {
5588 UpdateRes = DefaultLvalueConversion(RefRes.get());
5589 }
5590 if (!UpdateRes.isUsable()) {
5591 IsCorrect = false;
5592 continue;
5593 }
5594 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5595 UpdateRes.get());
5596 if (!UpdateRes.isUsable()) {
5597 IsCorrect = false;
5598 continue;
5599 }
5600 ExprResult VDRes =
5601 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5602 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5603 D.IteratorDecl->getBeginLoc());
5604 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5605 UpdateRes.get());
5606 if (!UpdateRes.isUsable()) {
5607 IsCorrect = false;
5608 continue;
5609 }
5610 UpdateRes =
5611 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5612 if (!UpdateRes.isUsable()) {
5613 IsCorrect = false;
5614 continue;
5615 }
5616 ExprResult CounterUpdateRes =
5617 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5618 if (!CounterUpdateRes.isUsable()) {
5619 IsCorrect = false;
5620 continue;
5621 }
5622 CounterUpdateRes =
5623 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5624 if (!CounterUpdateRes.isUsable()) {
5625 IsCorrect = false;
5626 continue;
5627 }
5628 OMPIteratorHelperData &HD = Helpers.emplace_back();
5629 HD.CounterVD = CounterVD;
5630 HD.Upper = Res.get();
5631 HD.Update = UpdateRes.get();
5632 HD.CounterUpdate = CounterUpdateRes.get();
5633 }
5634 } else {
5635 Helpers.assign(ID.size(), {});
5636 }
5637 if (!IsCorrect) {
5638 // Invalidate all created iterator declarations if error is found.
5639 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5640 if (Decl *ID = D.IteratorDecl)
5641 ID->setInvalidDecl();
5642 }
5643 return ExprError();
5644 }
5645 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5646 LLoc, RLoc, ID, Helpers);
5647}
5648
5649ExprResult
5650Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5651 Expr *Idx, SourceLocation RLoc) {
5652 Expr *LHSExp = Base;
5653 Expr *RHSExp = Idx;
5654
5655 ExprValueKind VK = VK_LValue;
5656 ExprObjectKind OK = OK_Ordinary;
5657
5658 // Per C++ core issue 1213, the result is an xvalue if either operand is
5659 // a non-lvalue array, and an lvalue otherwise.
5660 if (getLangOpts().CPlusPlus11) {
5661 for (auto *Op : {LHSExp, RHSExp}) {
5662 Op = Op->IgnoreImplicit();
5663 if (Op->getType()->isArrayType() && !Op->isLValue())
5664 VK = VK_XValue;
5665 }
5666 }
5667
5668 // Perform default conversions.
5669 if (!LHSExp->getType()->getAs<VectorType>()) {
5670 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5671 if (Result.isInvalid())
5672 return ExprError();
5673 LHSExp = Result.get();
5674 }
5675 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5676 if (Result.isInvalid())
5677 return ExprError();
5678 RHSExp = Result.get();
5679
5680 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5681
5682 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5683 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5684 // in the subscript position. As a result, we need to derive the array base
5685 // and index from the expression types.
5686 Expr *BaseExpr, *IndexExpr;
5687 QualType ResultType;
5688 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5689 BaseExpr = LHSExp;
5690 IndexExpr = RHSExp;
5691 ResultType =
5692 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5693 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5694 BaseExpr = LHSExp;
5695 IndexExpr = RHSExp;
5696 ResultType = PTy->getPointeeType();
5697 } else if (const ObjCObjectPointerType *PTy =
5698 LHSTy->getAs<ObjCObjectPointerType>()) {
5699 BaseExpr = LHSExp;
5700 IndexExpr = RHSExp;
5701
5702 // Use custom logic if this should be the pseudo-object subscript
5703 // expression.
5704 if (!LangOpts.isSubscriptPointerArithmetic())
5705 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5706 nullptr);
5707
5708 ResultType = PTy->getPointeeType();
5709 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5710 // Handle the uncommon case of "123[Ptr]".
5711 BaseExpr = RHSExp;
5712 IndexExpr = LHSExp;
5713 ResultType = PTy->getPointeeType();
5714 } else if (const ObjCObjectPointerType *PTy =
5715 RHSTy->getAs<ObjCObjectPointerType>()) {
5716 // Handle the uncommon case of "123[Ptr]".
5717 BaseExpr = RHSExp;
5718 IndexExpr = LHSExp;
5719 ResultType = PTy->getPointeeType();
5720 if (!LangOpts.isSubscriptPointerArithmetic()) {
5721 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5722 << ResultType << BaseExpr->getSourceRange();
5723 return ExprError();
5724 }
5725 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5726 BaseExpr = LHSExp; // vectors: V[123]
5727 IndexExpr = RHSExp;
5728 // We apply C++ DR1213 to vector subscripting too.
5729 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5730 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5731 if (Materialized.isInvalid())
5732 return ExprError();
5733 LHSExp = Materialized.get();
5734 }
5735 VK = LHSExp->getValueKind();
5736 if (VK != VK_PRValue)
5737 OK = OK_VectorComponent;
5738
5739 ResultType = VTy->getElementType();
5740 QualType BaseType = BaseExpr->getType();
5741 Qualifiers BaseQuals = BaseType.getQualifiers();
5742 Qualifiers MemberQuals = ResultType.getQualifiers();
5743 Qualifiers Combined = BaseQuals + MemberQuals;
5744 if (Combined != MemberQuals)
5745 ResultType = Context.getQualifiedType(ResultType, Combined);
5746 } else if (LHSTy->isBuiltinType() &&
5747 LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) {
5748 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5749 if (BTy->isSVEBool())
5750 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5751 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5752
5753 BaseExpr = LHSExp;
5754 IndexExpr = RHSExp;
5755 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5756 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5757 if (Materialized.isInvalid())
5758 return ExprError();
5759 LHSExp = Materialized.get();
5760 }
5761 VK = LHSExp->getValueKind();
5762 if (VK != VK_PRValue)
5763 OK = OK_VectorComponent;
5764
5765 ResultType = BTy->getSveEltType(Context);
5766
5767 QualType BaseType = BaseExpr->getType();
5768 Qualifiers BaseQuals = BaseType.getQualifiers();
5769 Qualifiers MemberQuals = ResultType.getQualifiers();
5770 Qualifiers Combined = BaseQuals + MemberQuals;
5771 if (Combined != MemberQuals)
5772 ResultType = Context.getQualifiedType(ResultType, Combined);
5773 } else if (LHSTy->isArrayType()) {
5774 // If we see an array that wasn't promoted by
5775 // DefaultFunctionArrayLvalueConversion, it must be an array that
5776 // wasn't promoted because of the C90 rule that doesn't
5777 // allow promoting non-lvalue arrays. Warn, then
5778 // force the promotion here.
5779 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5780 << LHSExp->getSourceRange();
5781 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5782 CK_ArrayToPointerDecay).get();
5783 LHSTy = LHSExp->getType();
5784
5785 BaseExpr = LHSExp;
5786 IndexExpr = RHSExp;
5787 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5788 } else if (RHSTy->isArrayType()) {
5789 // Same as previous, except for 123[f().a] case
5790 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5791 << RHSExp->getSourceRange();
5792 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5793 CK_ArrayToPointerDecay).get();
5794 RHSTy = RHSExp->getType();
5795
5796 BaseExpr = RHSExp;
5797 IndexExpr = LHSExp;
5798 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5799 } else {
5800 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5801 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5802 }
5803 // C99 6.5.2.1p1
5804 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5805 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5806 << IndexExpr->getSourceRange());
5807
5808 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5809 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5810 && !IndexExpr->isTypeDependent())
5811 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5812
5813 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5814 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5815 // type. Note that Functions are not objects, and that (in C99 parlance)
5816 // incomplete types are not object types.
5817 if (ResultType->isFunctionType()) {
5818 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5819 << ResultType << BaseExpr->getSourceRange();
5820 return ExprError();
5821 }
5822
5823 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5824 // GNU extension: subscripting on pointer to void
5825 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5826 << BaseExpr->getSourceRange();
5827
5828 // C forbids expressions of unqualified void type from being l-values.
5829 // See IsCForbiddenLValueType.
5830 if (!ResultType.hasQualifiers())
5831 VK = VK_PRValue;
5832 } else if (!ResultType->isDependentType() &&
5833 RequireCompleteSizedType(
5834 LLoc, ResultType,
5835 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5836 return ExprError();
5837
5838 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||(static_cast <bool> (VK == VK_PRValue || LangOpts.CPlusPlus
|| !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail
("VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "clang/lib/Sema/SemaExpr.cpp", 5839, __extension__ __PRETTY_FUNCTION__
))
5839 !ResultType.isCForbiddenLValueType())(static_cast <bool> (VK == VK_PRValue || LangOpts.CPlusPlus
|| !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail
("VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "clang/lib/Sema/SemaExpr.cpp", 5839, __extension__ __PRETTY_FUNCTION__
))
;
5840
5841 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5842 FunctionScopes.size() > 1) {
5843 if (auto *TT =
5844 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5845 for (auto I = FunctionScopes.rbegin(),
5846 E = std::prev(FunctionScopes.rend());
5847 I != E; ++I) {
5848 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5849 if (CSI == nullptr)
5850 break;
5851 DeclContext *DC = nullptr;
5852 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5853 DC = LSI->CallOperator;
5854 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5855 DC = CRSI->TheCapturedDecl;
5856 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5857 DC = BSI->TheDecl;
5858 if (DC) {
5859 if (DC->containsDecl(TT->getDecl()))
5860 break;
5861 captureVariablyModifiedType(
5862 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5863 }
5864 }
5865 }
5866 }
5867
5868 return new (Context)
5869 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5870}
5871
5872bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5873 ParmVarDecl *Param, Expr *RewrittenInit,
5874 bool SkipImmediateInvocations) {
5875 if (Param->hasUnparsedDefaultArg()) {
5876 assert(!RewrittenInit && "Should not have a rewritten init expression yet")(static_cast <bool> (!RewrittenInit && "Should not have a rewritten init expression yet"
) ? void (0) : __assert_fail ("!RewrittenInit && \"Should not have a rewritten init expression yet\""
, "clang/lib/Sema/SemaExpr.cpp", 5876, __extension__ __PRETTY_FUNCTION__
))
;
5877 // If we've already cleared out the location for the default argument,
5878 // that means we're parsing it right now.
5879 if (!UnparsedDefaultArgLocs.count(Param)) {
5880 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5881 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5882 Param->setInvalidDecl();
5883 return true;
5884 }
5885
5886 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5887 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5888 Diag(UnparsedDefaultArgLocs[Param],
5889 diag::note_default_argument_declared_here);
5890 return true;
5891 }
5892
5893 if (Param->hasUninstantiatedDefaultArg()) {
5894 assert(!RewrittenInit && "Should not have a rewitten init expression yet")(static_cast <bool> (!RewrittenInit && "Should not have a rewitten init expression yet"
) ? void (0) : __assert_fail ("!RewrittenInit && \"Should not have a rewitten init expression yet\""
, "clang/lib/Sema/SemaExpr.cpp", 5894, __extension__ __PRETTY_FUNCTION__
))
;
5895 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5896 return true;
5897 }
5898
5899 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5900 assert(Init && "default argument but no initializer?")(static_cast <bool> (Init && "default argument but no initializer?"
) ? void (0) : __assert_fail ("Init && \"default argument but no initializer?\""
, "clang/lib/Sema/SemaExpr.cpp", 5900, __extension__ __PRETTY_FUNCTION__
))
;
5901
5902 // If the default expression creates temporaries, we need to
5903 // push them to the current stack of expression temporaries so they'll
5904 // be properly destroyed.
5905 // FIXME: We should really be rebuilding the default argument with new
5906 // bound temporaries; see the comment in PR5810.
5907 // We don't need to do that with block decls, though, because
5908 // blocks in default argument expression can never capture anything.
5909 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5910 // Set the "needs cleanups" bit regardless of whether there are
5911 // any explicit objects.
5912 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5913 // Append all the objects to the cleanup list. Right now, this
5914 // should always be a no-op, because blocks in default argument
5915 // expressions should never be able to capture anything.
5916 assert(!InitWithCleanup->getNumObjects() &&(static_cast <bool> (!InitWithCleanup->getNumObjects
() && "default argument expression has capturing blocks?"
) ? void (0) : __assert_fail ("!InitWithCleanup->getNumObjects() && \"default argument expression has capturing blocks?\""
, "clang/lib/Sema/SemaExpr.cpp", 5917, __extension__ __PRETTY_FUNCTION__
))
5917 "default argument expression has capturing blocks?")(static_cast <bool> (!InitWithCleanup->getNumObjects
() && "default argument expression has capturing blocks?"
) ? void (0) : __assert_fail ("!InitWithCleanup->getNumObjects() && \"default argument expression has capturing blocks?\""
, "clang/lib/Sema/SemaExpr.cpp", 5917, __extension__ __PRETTY_FUNCTION__
))
;
5918 }
5919 // C++ [expr.const]p15.1:
5920 // An expression or conversion is in an immediate function context if it is
5921 // potentially evaluated and [...] its innermost enclosing non-block scope
5922 // is a function parameter scope of an immediate function.
5923 EnterExpressionEvaluationContext EvalContext(
5924 *this,
5925 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
5926 : ExpressionEvaluationContext::PotentiallyEvaluated,
5927 Param);
5928 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5929 SkipImmediateInvocations;
5930 runWithSufficientStackSpace(CallLoc, [&] {
5931 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5932 });
5933 return false;
5934}
5935
5936struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
5937 bool HasImmediateCalls = false;
5938
5939 bool shouldVisitImplicitCode() const { return true; }
5940
5941 bool VisitCallExpr(CallExpr *E) {
5942 if (const FunctionDecl *FD = E->getDirectCallee())
5943 HasImmediateCalls |= FD->isConsteval();
5944 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
5945 }
5946
5947 // SourceLocExpr are not immediate invocations
5948 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5949 // need to be rebuilt so that they refer to the correct SourceLocation and
5950 // DeclContext.
5951 bool VisitSourceLocExpr(SourceLocExpr *E) {
5952 HasImmediateCalls = true;
5953 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
5954 }
5955
5956 // A nested lambda might have parameters with immediate invocations
5957 // in their default arguments.
5958 // The compound statement is not visited (as it does not constitute a
5959 // subexpression).
5960 // FIXME: We should consider visiting and transforming captures
5961 // with init expressions.
5962 bool VisitLambdaExpr(LambdaExpr *E) {
5963 return VisitCXXMethodDecl(E->getCallOperator());
5964 }
5965
5966 // Blocks don't support default parameters, and, as for lambdas,
5967 // we don't consider their body a subexpression.
5968 bool VisitBlockDecl(BlockDecl *B) { return false; }
5969
5970 bool VisitCompoundStmt(CompoundStmt *B) { return false; }
5971
5972 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
5973 return TraverseStmt(E->getExpr());
5974 }
5975
5976 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
5977 return TraverseStmt(E->getExpr());
5978 }
5979};
5980
5981struct EnsureImmediateInvocationInDefaultArgs
5982 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5983 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5984 : TreeTransform(SemaRef) {}
5985
5986 // Lambda can only have immediate invocations in the default
5987 // args of their parameters, which is transformed upon calling the closure.
5988 // The body is not a subexpression, so we have nothing to do.
5989 // FIXME: Immediate calls in capture initializers should be transformed.
5990 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5991 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5992
5993 // Make sure we don't rebuild the this pointer as it would
5994 // cause it to incorrectly point it to the outermost class
5995 // in the case of nested struct initialization.
5996 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5997};
5998
5999ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
6000 FunctionDecl *FD, ParmVarDecl *Param,
6001 Expr *Init) {
6002 assert(Param->hasDefaultArg() && "can't build nonexistent default arg")(static_cast <bool> (Param->hasDefaultArg() &&
"can't build nonexistent default arg") ? void (0) : __assert_fail
("Param->hasDefaultArg() && \"can't build nonexistent default arg\""
, "clang/lib/Sema/SemaExpr.cpp", 6002, __extension__ __PRETTY_FUNCTION__
))
;
6003
6004 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6005
6006 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6007 InitializationContext =
6008 OutermostDeclarationWithDelayedImmediateInvocations();
6009 if (!InitializationContext.has_value())
6010 InitializationContext.emplace(CallLoc, Param, CurContext);
6011
6012 if (!Init && !Param->hasUnparsedDefaultArg()) {
6013 // Mark that we are replacing a default argument first.
6014 // If we are instantiating a template we won't have to
6015 // retransform immediate calls.
6016 // C++ [expr.const]p15.1:
6017 // An expression or conversion is in an immediate function context if it
6018 // is potentially evaluated and [...] its innermost enclosing non-block
6019 // scope is a function parameter scope of an immediate function.
6020 EnterExpressionEvaluationContext EvalContext(
6021 *this,
6022 FD->isConsteval()
6023 ? ExpressionEvaluationContext::ImmediateFunctionContext
6024 : ExpressionEvaluationContext::PotentiallyEvaluated,
6025 Param);
6026
6027 if (Param->hasUninstantiatedDefaultArg()) {
6028 if (InstantiateDefaultArgument(CallLoc, FD, Param))
6029 return ExprError();
6030 }
6031 // CWG2631
6032 // An immediate invocation that is not evaluated where it appears is
6033 // evaluated and checked for whether it is a constant expression at the
6034 // point where the enclosing initializer is used in a function call.
6035 ImmediateCallVisitor V;
6036 if (!NestedDefaultChecking)
6037 V.TraverseDecl(Param);
6038 if (V.HasImmediateCalls) {
6039 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
6040 CallLoc, Param, CurContext};
6041 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6042 ExprResult Res;
6043 runWithSufficientStackSpace(CallLoc, [&] {
6044 Res = Immediate.TransformInitializer(Param->getInit(),
6045 /*NotCopy=*/false);
6046 });
6047 if (Res.isInvalid())
6048 return ExprError();
6049 Res = ConvertParamDefaultArgument(Param, Res.get(),
6050 Res.get()->getBeginLoc());
6051 if (Res.isInvalid())
6052 return ExprError();
6053 Init = Res.get();
6054 }
6055 }
6056
6057 if (CheckCXXDefaultArgExpr(
6058 CallLoc, FD, Param, Init,
6059 /*SkipImmediateInvocations=*/NestedDefaultChecking))
6060 return ExprError();
6061
6062 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
6063 Init, InitializationContext->Context);
6064}
6065
6066ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
6067 assert(Field->hasInClassInitializer())(static_cast <bool> (Field->hasInClassInitializer())
? void (0) : __assert_fail ("Field->hasInClassInitializer()"
, "clang/lib/Sema/SemaExpr.cpp", 6067, __extension__ __PRETTY_FUNCTION__
))
;
6068
6069 // If we might have already tried and failed to instantiate, don't try again.
6070 if (Field->isInvalidDecl())
6071 return ExprError();
6072
6073 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
6074
6075 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6076 InitializationContext =
6077 OutermostDeclarationWithDelayedImmediateInvocations();
6078 if (!InitializationContext.has_value())
6079 InitializationContext.emplace(Loc, Field, CurContext);
6080
6081 Expr *Init = nullptr;
6082
6083 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6084
6085 EnterExpressionEvaluationContext EvalContext(
6086 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
6087
6088 if (!Field->getInClassInitializer()) {
6089 // Maybe we haven't instantiated the in-class initializer. Go check the
6090 // pattern FieldDecl to see if it has one.
6091 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
6092 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
6093 DeclContext::lookup_result Lookup =
6094 ClassPattern->lookup(Field->getDeclName());
6095
6096 FieldDecl *Pattern = nullptr;
6097 for (auto *L : Lookup) {
6098 if ((Pattern = dyn_cast<FieldDecl>(L)))
6099 break;
6100 }
6101 assert(Pattern && "We must have set the Pattern!")(static_cast <bool> (Pattern && "We must have set the Pattern!"
) ? void (0) : __assert_fail ("Pattern && \"We must have set the Pattern!\""
, "clang/lib/Sema/SemaExpr.cpp", 6101, __extension__ __PRETTY_FUNCTION__
))
;
6102 if (!Pattern->hasInClassInitializer() ||
6103 InstantiateInClassInitializer(Loc, Field, Pattern,
6104 getTemplateInstantiationArgs(Field))) {
6105 Field->setInvalidDecl();
6106 return ExprError();
6107 }
6108 }
6109 }
6110
6111 // CWG2631
6112 // An immediate invocation that is not evaluated where it appears is
6113 // evaluated and checked for whether it is a constant expression at the
6114 // point where the enclosing initializer is used in a [...] a constructor
6115 // definition, or an aggregate initialization.
6116 ImmediateCallVisitor V;
6117 if (!NestedDefaultChecking)
6118 V.TraverseDecl(Field);
6119 if (V.HasImmediateCalls) {
6120 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
6121 CurContext};
6122 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6123 NestedDefaultChecking;
6124
6125 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6126 ExprResult Res;
6127 runWithSufficientStackSpace(Loc, [&] {
6128 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
6129 /*CXXDirectInit=*/false);
6130 });
6131 if (!Res.isInvalid())
6132 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
6133 if (Res.isInvalid()) {
6134 Field->setInvalidDecl();
6135 return ExprError();
6136 }
6137 Init = Res.get();
6138 }
6139
6140 if (Field->getInClassInitializer()) {
6141 Expr *E = Init ? Init : Field->getInClassInitializer();
6142 if (!NestedDefaultChecking)
6143 runWithSufficientStackSpace(Loc, [&] {
6144 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
6145 });
6146 // C++11 [class.base.init]p7:
6147 // The initialization of each base and member constitutes a
6148 // full-expression.
6149 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
6150 if (Res.isInvalid()) {
6151 Field->setInvalidDecl();
6152 return ExprError();
6153 }
6154 Init = Res.get();
6155
6156 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
6157 Field, InitializationContext->Context,
6158 Init);
6159 }
6160
6161 // DR1351:
6162 // If the brace-or-equal-initializer of a non-static data member
6163 // invokes a defaulted default constructor of its class or of an
6164 // enclosing class in a potentially evaluated subexpression, the
6165 // program is ill-formed.
6166 //
6167 // This resolution is unworkable: the exception specification of the
6168 // default constructor can be needed in an unevaluated context, in
6169 // particular, in the operand of a noexcept-expression, and we can be
6170 // unable to compute an exception specification for an enclosed class.
6171 //
6172 // Any attempt to resolve the exception specification of a defaulted default
6173 // constructor before the initializer is lexically complete will ultimately
6174 // come here at which point we can diagnose it.
6175 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6176 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
6177 << OutermostClass << Field;
6178 Diag(Field->getEndLoc(),
6179 diag::note_default_member_initializer_not_yet_parsed);
6180 // Recover by marking the field invalid, unless we're in a SFINAE context.
6181 if (!isSFINAEContext())
6182 Field->setInvalidDecl();
6183 return ExprError();
6184}
6185
6186Sema::VariadicCallType
6187Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
6188 Expr *Fn) {
6189 if (Proto && Proto->isVariadic()) {
6190 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
6191 return VariadicConstructor;
6192 else if (Fn && Fn->getType()->isBlockPointerType())
6193 return VariadicBlock;
6194 else if (FDecl) {
6195 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6196 if (Method->isInstance())
6197 return VariadicMethod;
6198 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6199 return VariadicMethod;
6200 return VariadicFunction;
6201 }
6202 return VariadicDoesNotApply;
6203}
6204
6205namespace {
6206class FunctionCallCCC final : public FunctionCallFilterCCC {
6207public:
6208 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6209 unsigned NumArgs, MemberExpr *ME)
6210 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6211 FunctionName(FuncName) {}
6212
6213 bool ValidateCandidate(const TypoCorrection &candidate) override {
6214 if (!candidate.getCorrectionSpecifier() ||
6215 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6216 return false;
6217 }
6218
6219 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6220 }
6221
6222 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6223 return std::make_unique<FunctionCallCCC>(*this);
6224 }
6225
6226private:
6227 const IdentifierInfo *const FunctionName;
6228};
6229}
6230
6231static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6232 FunctionDecl *FDecl,
6233 ArrayRef<Expr *> Args) {
6234 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6235 DeclarationName FuncName = FDecl->getDeclName();
6236 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6237
6238 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6239 if (TypoCorrection Corrected = S.CorrectTypo(
6240 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
6241 S.getScopeForContext(S.CurContext), nullptr, CCC,
6242 Sema::CTK_ErrorRecovery)) {
6243 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6244 if (Corrected.isOverloaded()) {
6245 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6246 OverloadCandidateSet::iterator Best;
6247 for (NamedDecl *CD : Corrected) {
6248 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6249 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
6250 OCS);
6251 }
6252 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6253 case OR_Success:
6254 ND = Best->FoundDecl;
6255 Corrected.setCorrectionDecl(ND);
6256 break;
6257 default:
6258 break;
6259 }
6260 }
6261 ND = ND->getUnderlyingDecl();
6262 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
6263 return Corrected;
6264 }
6265 }
6266 return TypoCorrection();
6267}
6268
6269/// ConvertArgumentsForCall - Converts the arguments specified in
6270/// Args/NumArgs to the parameter types of the function FDecl with
6271/// function prototype Proto. Call is the call expression itself, and
6272/// Fn is the function expression. For a C++ member function, this
6273/// routine does not attempt to convert the object argument. Returns
6274/// true if the call is ill-formed.
6275bool
6276Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6277 FunctionDecl *FDecl,
6278 const FunctionProtoType *Proto,
6279 ArrayRef<Expr *> Args,
6280 SourceLocation RParenLoc,
6281 bool IsExecConfig) {
6282 // Bail out early if calling a builtin with custom typechecking.
6283 if (FDecl)
6284 if (unsigned ID = FDecl->getBuiltinID())
6285 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6286 return false;
6287
6288 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6289 // assignment, to the types of the corresponding parameter, ...
6290 unsigned NumParams = Proto->getNumParams();
6291 bool Invalid = false;
6292 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6293 unsigned FnKind = Fn->getType()->isBlockPointerType()
6294 ? 1 /* block */
6295 : (IsExecConfig ? 3 /* kernel function (exec config) */
6296 : 0 /* function */);
6297
6298 // If too few arguments are available (and we don't have default
6299 // arguments for the remaining parameters), don't make the call.
6300 if (Args.size() < NumParams) {
6301 if (Args.size() < MinArgs) {
6302 TypoCorrection TC;
6303 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6304 unsigned diag_id =
6305 MinArgs == NumParams && !Proto->isVariadic()
6306 ? diag::err_typecheck_call_too_few_args_suggest
6307 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6308 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
6309 << static_cast<unsigned>(Args.size())
6310 << TC.getCorrectionRange());
6311 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
6312 Diag(RParenLoc,
6313 MinArgs == NumParams && !Proto->isVariadic()
6314 ? diag::err_typecheck_call_too_few_args_one
6315 : diag::err_typecheck_call_too_few_args_at_least_one)
6316 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
6317 else
6318 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6319 ? diag::err_typecheck_call_too_few_args
6320 : diag::err_typecheck_call_too_few_args_at_least)
6321 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
6322 << Fn->getSourceRange();
6323
6324 // Emit the location of the prototype.
6325 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6326 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6327
6328 return true;
6329 }
6330 // We reserve space for the default arguments when we create
6331 // the call expression, before calling ConvertArgumentsForCall.
6332 assert((Call->getNumArgs() == NumParams) &&(static_cast <bool> ((Call->getNumArgs() == NumParams
) && "We should have reserved space for the default arguments before!"
) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "clang/lib/Sema/SemaExpr.cpp", 6333, __extension__ __PRETTY_FUNCTION__
))
6333 "We should have reserved space for the default arguments before!")(static_cast <bool> ((Call->getNumArgs() == NumParams
) && "We should have reserved space for the default arguments before!"
) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "clang/lib/Sema/SemaExpr.cpp", 6333, __extension__ __PRETTY_FUNCTION__
))
;
6334 }
6335
6336 // If too many are passed and not variadic, error on the extras and drop
6337 // them.
6338 if (Args.size() > NumParams) {
6339 if (!Proto->isVariadic()) {
6340 TypoCorrection TC;
6341 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6342 unsigned diag_id =
6343 MinArgs == NumParams && !Proto->isVariadic()
6344 ? diag::err_typecheck_call_too_many_args_suggest
6345 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6346 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6347 << static_cast<unsigned>(Args.size())
6348 << TC.getCorrectionRange());
6349 } else if (NumParams == 1 && FDecl &&
6350 FDecl->getParamDecl(0)->getDeclName())
6351 Diag(Args[NumParams]->getBeginLoc(),
6352 MinArgs == NumParams
6353 ? diag::err_typecheck_call_too_many_args_one
6354 : diag::err_typecheck_call_too_many_args_at_most_one)
6355 << FnKind << FDecl->getParamDecl(0)
6356 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6357 << SourceRange(Args[NumParams]->getBeginLoc(),
6358 Args.back()->getEndLoc());
6359 else
6360 Diag(Args[NumParams]->getBeginLoc(),
6361 MinArgs == NumParams
6362 ? diag::err_typecheck_call_too_many_args
6363 : diag::err_typecheck_call_too_many_args_at_most)
6364 << FnKind << NumParams << static_cast<unsigned>(Args.size())
6365 << Fn->getSourceRange()
6366 << SourceRange(Args[NumParams]->getBeginLoc(),
6367 Args.back()->getEndLoc());
6368
6369 // Emit the location of the prototype.
6370 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6371 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6372
6373 // This deletes the extra arguments.
6374 Call->shrinkNumArgs(NumParams);
6375 return true;
6376 }
6377 }
6378 SmallVector<Expr *, 8> AllArgs;
6379 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6380
6381 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6382 AllArgs, CallType);
6383 if (Invalid)
6384 return true;
6385 unsigned TotalNumArgs = AllArgs.size();
6386 for (unsigned i = 0; i < TotalNumArgs; ++i)
6387 Call->setArg(i, AllArgs[i]);
6388
6389 Call->computeDependence();
6390 return false;
6391}
6392
6393bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6394 const FunctionProtoType *Proto,
6395 unsigned FirstParam, ArrayRef<Expr *> Args,
6396 SmallVectorImpl<Expr *> &AllArgs,
6397 VariadicCallType CallType, bool AllowExplicit,
6398 bool IsListInitialization) {
6399 unsigned NumParams = Proto->getNumParams();
6400 bool Invalid = false;
6401 size_t ArgIx = 0;
6402 // Continue to check argument types (even if we have too few/many args).
6403 for (unsigned i = FirstParam; i < NumParams; i++) {
6404 QualType ProtoArgType = Proto->getParamType(i);
6405
6406 Expr *Arg;
6407 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6408 if (ArgIx < Args.size()) {
6409 Arg = Args[ArgIx++];
6410
6411 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6412 diag::err_call_incomplete_argument, Arg))
6413 return true;
6414
6415 // Strip the unbridged-cast placeholder expression off, if applicable.
6416 bool CFAudited = false;
6417 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6418 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6419 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6420 Arg = stripARCUnbridgedCast(Arg);
6421 else if (getLangOpts().ObjCAutoRefCount &&
6422 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6423 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6424 CFAudited = true;
6425
6426 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6427 ProtoArgType->isBlockPointerType())
6428 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6429 BE->getBlockDecl()->setDoesNotEscape();
6430
6431 InitializedEntity Entity =
6432 Param ? InitializedEntity::InitializeParameter(Context, Param,
6433 ProtoArgType)
6434 : InitializedEntity::InitializeParameter(
6435 Context, ProtoArgType, Proto->isParamConsumed(i));
6436
6437 // Remember that parameter belongs to a CF audited API.
6438 if (CFAudited)
6439 Entity.setParameterCFAudited();
6440
6441 ExprResult ArgE = PerformCopyInitialization(
6442 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6443 if (ArgE.isInvalid())
6444 return true;
6445
6446 Arg = ArgE.getAs<Expr>();
6447 } else {
6448 assert(Param && "can't use default arguments without a known callee")(static_cast <bool> (Param && "can't use default arguments without a known callee"
) ? void (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\""
, "clang/lib/Sema/SemaExpr.cpp", 6448, __extension__ __PRETTY_FUNCTION__
))
;
6449
6450 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6451 if (ArgExpr.isInvalid())
6452 return true;
6453
6454 Arg = ArgExpr.getAs<Expr>();
6455 }
6456
6457 // Check for array bounds violations for each argument to the call. This
6458 // check only triggers warnings when the argument isn't a more complex Expr
6459 // with its own checking, such as a BinaryOperator.
6460 CheckArrayAccess(Arg);
6461
6462 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6463 CheckStaticArrayArgument(CallLoc, Param, Arg);
6464
6465 AllArgs.push_back(Arg);
6466 }
6467
6468 // If this is a variadic call, handle args passed through "...".
6469 if (CallType != VariadicDoesNotApply) {
6470 // Assume that extern "C" functions with variadic arguments that
6471 // return __unknown_anytype aren't *really* variadic.
6472 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6473 FDecl->isExternC()) {
6474 for (Expr *A : Args.slice(ArgIx)) {
6475 QualType paramType; // ignored
6476 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6477 Invalid |= arg.isInvalid();
6478 AllArgs.push_back(arg.get());
6479 }
6480
6481 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6482 } else {
6483 for (Expr *A : Args.slice(ArgIx)) {
6484 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6485 Invalid |= Arg.isInvalid();
6486 AllArgs.push_back(Arg.get());
6487 }
6488 }
6489
6490 // Check for array bounds violations.
6491 for (Expr *A : Args.slice(ArgIx))
6492 CheckArrayAccess(A);
6493 }
6494 return Invalid;
6495}
6496
6497static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6498 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6499 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6500 TL = DTL.getOriginalLoc();
6501 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6502 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6503 << ATL.getLocalSourceRange();
6504}
6505
6506/// CheckStaticArrayArgument - If the given argument corresponds to a static
6507/// array parameter, check that it is non-null, and that if it is formed by
6508/// array-to-pointer decay, the underlying array is sufficiently large.
6509///
6510/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6511/// array type derivation, then for each call to the function, the value of the
6512/// corresponding actual argument shall provide access to the first element of
6513/// an array with at least as many elements as specified by the size expression.
6514void
6515Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6516 ParmVarDecl *Param,
6517 const Expr *ArgExpr) {
6518 // Static array parameters are not supported in C++.
6519 if (!Param || getLangOpts().CPlusPlus)
6520 return;
6521
6522 QualType OrigTy = Param->getOriginalType();
6523
6524 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6525 if (!AT || AT->getSizeModifier() != ArrayType::Static)
6526 return;
6527
6528 if (ArgExpr->isNullPointerConstant(Context,
6529 Expr::NPC_NeverValueDependent)) {
6530 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6531 DiagnoseCalleeStaticArrayParam(*this, Param);
6532 return;
6533 }
6534
6535 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6536 if (!CAT)
6537 return;
6538
6539 const ConstantArrayType *ArgCAT =
6540 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6541 if (!ArgCAT)
6542 return;
6543
6544 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6545 ArgCAT->getElementType())) {
6546 if (ArgCAT->getSize().ult(CAT->getSize())) {
6547 Diag(CallLoc, diag::warn_static_array_too_small)
6548 << ArgExpr->getSourceRange()
6549 << (unsigned)ArgCAT->getSize().getZExtValue()
6550 << (unsigned)CAT->getSize().getZExtValue() << 0;
6551 DiagnoseCalleeStaticArrayParam(*this, Param);
6552 }
6553 return;
6554 }
6555
6556 std::optional<CharUnits> ArgSize =
6557 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6558 std::optional<CharUnits> ParmSize =
6559 getASTContext().getTypeSizeInCharsIfKnown(CAT);
6560 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6561 Diag(CallLoc, diag::warn_static_array_too_small)
6562 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6563 << (unsigned)ParmSize->getQuantity() << 1;
6564 DiagnoseCalleeStaticArrayParam(*this, Param);
6565 }
6566}
6567
6568/// Given a function expression of unknown-any type, try to rebuild it
6569/// to have a function type.
6570static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6571
6572/// Is the given type a placeholder that we need to lower out
6573/// immediately during argument processing?
6574static bool isPlaceholderToRemoveAsArg(QualType type) {
6575 // Placeholders are never sugared.
6576 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6577 if (!placeholder) return false;
6578
6579 switch (placeholder->getKind()) {
6580 // Ignore all the non-placeholder types.
6581#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6582 case BuiltinType::Id:
6583#include "clang/Basic/OpenCLImageTypes.def"
6584#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6585 case BuiltinType::Id:
6586#include "clang/Basic/OpenCLExtensionTypes.def"
6587 // In practice we'll never use this, since all SVE types are sugared
6588 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6589#define SVE_TYPE(Name, Id, SingletonId) \
6590 case BuiltinType::Id:
6591#include "clang/Basic/AArch64SVEACLETypes.def"
6592#define PPC_VECTOR_TYPE(Name, Id, Size) \
6593 case BuiltinType::Id:
6594#include "clang/Basic/PPCTypes.def"
6595#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6596#include "clang/Basic/RISCVVTypes.def"
6597#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6598#include "clang/Basic/WebAssemblyReferenceTypes.def"
6599#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6600#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6601#include "clang/AST/BuiltinTypes.def"
6602 return false;
6603
6604 // We cannot lower out overload sets; they might validly be resolved
6605 // by the call machinery.
6606 case BuiltinType::Overload:
6607 return false;
6608
6609 // Unbridged casts in ARC can be handled in some call positions and
6610 // should be left in place.
6611 case BuiltinType::ARCUnbridgedCast:
6612 return false;
6613
6614 // Pseudo-objects should be converted as soon as possible.
6615 case BuiltinType::PseudoObject:
6616 return true;
6617
6618 // The debugger mode could theoretically but currently does not try
6619 // to resolve unknown-typed arguments based on known parameter types.
6620 case BuiltinType::UnknownAny:
6621 return true;
6622
6623 // These are always invalid as call arguments and should be reported.
6624 case BuiltinType::BoundMember:
6625 case BuiltinType::BuiltinFn:
6626 case BuiltinType::IncompleteMatrixIdx:
6627 case BuiltinType::OMPArraySection:
6628 case BuiltinType::OMPArrayShaping:
6629 case BuiltinType::OMPIterator:
6630 return true;
6631
6632 }
6633 llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "clang/lib/Sema/SemaExpr.cpp"
, 6633)
;
6634}
6635
6636/// Check an argument list for placeholders that we won't try to
6637/// handle later.
6638static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6639 // Apply this processing to all the arguments at once instead of
6640 // dying at the first failure.
6641 bool hasInvalid = false;
6642 for (size_t i = 0, e = args.size(); i != e; i++) {
6643 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6644 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6645 if (result.isInvalid()) hasInvalid = true;
6646 else args[i] = result.get();
6647 }
6648 }
6649 return hasInvalid;
6650}
6651
6652/// If a builtin function has a pointer argument with no explicit address
6653/// space, then it should be able to accept a pointer to any address
6654/// space as input. In order to do this, we need to replace the
6655/// standard builtin declaration with one that uses the same address space
6656/// as the call.
6657///
6658/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6659/// it does not contain any pointer arguments without
6660/// an address space qualifer. Otherwise the rewritten
6661/// FunctionDecl is returned.
6662/// TODO: Handle pointer return types.
6663static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6664 FunctionDecl *FDecl,
6665 MultiExprArg ArgExprs) {
6666
6667 QualType DeclType = FDecl->getType();
6668 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6669
6670 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6671 ArgExprs.size() < FT->getNumParams())
6672 return nullptr;
6673
6674 bool NeedsNewDecl = false;
6675 unsigned i = 0;
6676 SmallVector<QualType, 8> OverloadParams;
6677
6678 for (QualType ParamType : FT->param_types()) {
6679
6680 // Convert array arguments to pointer to simplify type lookup.
6681 ExprResult ArgRes =
6682 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6683 if (ArgRes.isInvalid())
6684 return nullptr;
6685 Expr *Arg = ArgRes.get();
6686 QualType ArgType = Arg->getType();
6687 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6688 !ArgType->isPointerType() ||
6689 !ArgType->getPointeeType().hasAddressSpace() ||
6690 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6691 OverloadParams.push_back(ParamType);
6692 continue;
6693 }
6694
6695 QualType PointeeType = ParamType->getPointeeType();
6696 if (PointeeType.hasAddressSpace())
6697 continue;
6698
6699 NeedsNewDecl = true;
6700 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6701
6702 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6703 OverloadParams.push_back(Context.getPointerType(PointeeType));
6704 }
6705
6706 if (!NeedsNewDecl)
6707 return nullptr;
6708
6709 FunctionProtoType::ExtProtoInfo EPI;
6710 EPI.Variadic = FT->isVariadic();
6711 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6712 OverloadParams, EPI);
6713 DeclContext *Parent = FDecl->getParent();
6714 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6715 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6716 FDecl->getIdentifier(), OverloadTy,
6717 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6718 false,
6719 /*hasPrototype=*/true);
6720 SmallVector<ParmVarDecl*, 16> Params;
6721 FT = cast<FunctionProtoType>(OverloadTy);
6722 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6723 QualType ParamType = FT->getParamType(i);
6724 ParmVarDecl *Parm =
6725 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6726 SourceLocation(), nullptr, ParamType,
6727 /*TInfo=*/nullptr, SC_None, nullptr);
6728 Parm->setScopeInfo(0, i);
6729 Params.push_back(Parm);
6730 }
6731 OverloadDecl->setParams(Params);
6732 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6733 return OverloadDecl;
6734}
6735
6736static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6737 FunctionDecl *Callee,
6738 MultiExprArg ArgExprs) {
6739 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6740 // similar attributes) really don't like it when functions are called with an
6741 // invalid number of args.
6742 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6743 /*PartialOverloading=*/false) &&
6744 !Callee->isVariadic())
6745 return;
6746 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6747 return;
6748
6749 if (const EnableIfAttr *Attr =
6750 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6751 S.Diag(Fn->getBeginLoc(),
6752 isa<CXXMethodDecl>(Callee)
6753 ? diag::err_ovl_no_viable_member_function_in_call
6754 : diag::err_ovl_no_viable_function_in_call)
6755 << Callee << Callee->getSourceRange();
6756 S.Diag(Callee->getLocation(),
6757 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6758 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6759 return;
6760 }
6761}
6762
6763static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6764 const UnresolvedMemberExpr *const UME, Sema &S) {
6765
6766 const auto GetFunctionLevelDCIfCXXClass =
6767 [](Sema &S) -> const CXXRecordDecl * {
6768 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6769 if (!DC || !DC->getParent())
6770 return nullptr;
6771
6772 // If the call to some member function was made from within a member
6773 // function body 'M' return return 'M's parent.
6774 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6775 return MD->getParent()->getCanonicalDecl();
6776 // else the call was made from within a default member initializer of a
6777 // class, so return the class.
6778 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6779 return RD->getCanonicalDecl();
6780 return nullptr;
6781 };
6782 // If our DeclContext is neither a member function nor a class (in the
6783 // case of a lambda in a default member initializer), we can't have an
6784 // enclosing 'this'.
6785
6786 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6787 if (!CurParentClass)
6788 return false;
6789
6790 // The naming class for implicit member functions call is the class in which
6791 // name lookup starts.
6792 const CXXRecordDecl *const NamingClass =
6793 UME->getNamingClass()->getCanonicalDecl();
6794 assert(NamingClass && "Must have naming class even for implicit access")(static_cast <bool> (NamingClass && "Must have naming class even for implicit access"
) ? void (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\""
, "clang/lib/Sema/SemaExpr.cpp", 6794, __extension__ __PRETTY_FUNCTION__
))
;
6795
6796 // If the unresolved member functions were found in a 'naming class' that is
6797 // related (either the same or derived from) to the class that contains the
6798 // member function that itself contained the implicit member access.
6799
6800 return CurParentClass == NamingClass ||
6801 CurParentClass->isDerivedFrom(NamingClass);
6802}
6803
6804static void
6805tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6806 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6807
6808 if (!UME)
6809 return;
6810
6811 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6812 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6813 // already been captured, or if this is an implicit member function call (if
6814 // it isn't, an attempt to capture 'this' should already have been made).
6815 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6816 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6817 return;
6818
6819 // Check if the naming class in which the unresolved members were found is
6820 // related (same as or is a base of) to the enclosing class.
6821
6822 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6823 return;
6824
6825
6826 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6827 // If the enclosing function is not dependent, then this lambda is
6828 // capture ready, so if we can capture this, do so.
6829 if (!EnclosingFunctionCtx->isDependentContext()) {
6830 // If the current lambda and all enclosing lambdas can capture 'this' -
6831 // then go ahead and capture 'this' (since our unresolved overload set
6832 // contains at least one non-static member function).
6833 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6834 S.CheckCXXThisCapture(CallLoc);
6835 } else if (S.CurContext->isDependentContext()) {
6836 // ... since this is an implicit member reference, that might potentially
6837 // involve a 'this' capture, mark 'this' for potential capture in
6838 // enclosing lambdas.
6839 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6840 CurLSI->addPotentialThisCapture(CallLoc);
6841 }
6842}
6843
6844// Once a call is fully resolved, warn for unqualified calls to specific
6845// C++ standard functions, like move and forward.
6846static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6847 // We are only checking unary move and forward so exit early here.
6848 if (Call->getNumArgs() != 1)
6849 return;
6850
6851 Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6852 if (!E || isa<UnresolvedLookupExpr>(E))
6853 return;
6854 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6855 if (!DRE || !DRE->getLocation().isValid())
6856 return;
6857
6858 if (DRE->getQualifier())
6859 return;
6860
6861 const FunctionDecl *FD = Call->getDirectCallee();
6862 if (!FD)
6863 return;
6864
6865 // Only warn for some functions deemed more frequent or problematic.
6866 unsigned BuiltinID = FD->getBuiltinID();
6867 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6868 return;
6869
6870 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6871 << FD->getQualifiedNameAsString()
6872 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6873}
6874
6875ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6876 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6877 Expr *ExecConfig) {
6878 ExprResult Call =
6879 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6880 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6881 if (Call.isInvalid())
6882 return Call;
6883
6884 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6885 // language modes.
6886 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6887 if (ULE->hasExplicitTemplateArgs() &&
6888 ULE->decls_begin() == ULE->decls_end()) {
6889 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6890 ? diag::warn_cxx17_compat_adl_only_template_id
6891 : diag::ext_adl_only_template_id)
6892 << ULE->getName();
6893 }
6894 }
6895
6896 if (LangOpts.OpenMP)
6897 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6898 ExecConfig);
6899 if (LangOpts.CPlusPlus) {
6900 CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6901 if (CE)
6902 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6903 }
6904 return Call;
6905}
6906
6907/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6908/// This provides the location of the left/right parens and a list of comma
6909/// locations.
6910ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6911 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6912 Expr *ExecConfig, bool IsExecConfig,
6913 bool AllowRecovery) {
6914 // Since this might be a postfix expression, get rid of ParenListExprs.
6915 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6916 if (Result.isInvalid()) return ExprError();
6917 Fn = Result.get();
6918
6919 if (checkArgsForPlaceholders(*this, ArgExprs))
6920 return ExprError();
6921
6922 if (getLangOpts().CPlusPlus) {
6923 // If this is a pseudo-destructor expression, build the call immediately.
6924 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6925 if (!ArgExprs.empty()) {
6926 // Pseudo-destructor calls should not have any arguments.
6927 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6928 << FixItHint::CreateRemoval(
6929 SourceRange(ArgExprs.front()->getBeginLoc(),
6930 ArgExprs.back()->getEndLoc()));
6931 }
6932
6933 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6934 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6935 }
6936 if (Fn->getType() == Context.PseudoObjectTy) {
6937 ExprResult result = CheckPlaceholderExpr(Fn);
6938 if (result.isInvalid()) return ExprError();
6939 Fn = result.get();
6940 }
6941
6942 // Determine whether this is a dependent call inside a C++ template,
6943 // in which case we won't do any semantic analysis now.
6944 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6945 if (ExecConfig) {
6946 return CUDAKernelCallExpr::Create(Context, Fn,
6947 cast<CallExpr>(ExecConfig), ArgExprs,
6948 Context.DependentTy, VK_PRValue,
6949 RParenLoc, CurFPFeatureOverrides());
6950 } else {
6951
6952 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6953 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6954 Fn->getBeginLoc());
6955
6956 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6957 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6958 }
6959 }
6960
6961 // Determine whether this is a call to an object (C++ [over.call.object]).
6962 if (Fn->getType()->isRecordType())
6963 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6964 RParenLoc);
6965
6966 if (Fn->getType() == Context.UnknownAnyTy) {
6967 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6968 if (result.isInvalid()) return ExprError();
6969 Fn = result.get();
6970 }
6971
6972 if (Fn->getType() == Context.BoundMemberTy) {
6973 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6974 RParenLoc, ExecConfig, IsExecConfig,
6975 AllowRecovery);
6976 }
6977 }
6978
6979 // Check for overloaded calls. This can happen even in C due to extensions.
6980 if (Fn->getType() == Context.OverloadTy) {
6981 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6982
6983 // We aren't supposed to apply this logic if there's an '&' involved.
6984 if (!find.HasFormOfMemberPointer) {
6985 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6986 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6987 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6988 OverloadExpr *ovl = find.Expression;
6989 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6990 return BuildOverloadedCallExpr(
6991 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6992 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6993 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6994 RParenLoc, ExecConfig, IsExecConfig,
6995 AllowRecovery);
6996 }
6997 }
6998
6999 // If we're directly calling a function, get the appropriate declaration.
7000 if (Fn->getType() == Context.UnknownAnyTy) {
7001 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7002 if (result.isInvalid()) return ExprError();
7003 Fn = result.get();
7004 }
7005
7006 Expr *NakedFn = Fn->IgnoreParens();
7007
7008 bool CallingNDeclIndirectly = false;
7009 NamedDecl *NDecl = nullptr;
7010 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
7011 if (UnOp->getOpcode() == UO_AddrOf) {
7012 CallingNDeclIndirectly = true;
7013 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7014 }
7015 }
7016
7017 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
7018 NDecl = DRE->getDecl();
7019
7020 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
7021 if (FDecl && FDecl->getBuiltinID()) {
7022 // Rewrite the function decl for this builtin by replacing parameters
7023 // with no explicit address space with the address space of the arguments
7024 // in ArgExprs.
7025 if ((FDecl =
7026 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
7027 NDecl = FDecl;
7028 Fn = DeclRefExpr::Create(
7029 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
7030 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
7031 nullptr, DRE->isNonOdrUse());
7032 }
7033 }
7034 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
7035 NDecl = ME->getMemberDecl();
7036
7037 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
7038 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7039 FD, /*Complain=*/true, Fn->getBeginLoc()))
7040 return ExprError();
7041
7042 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
7043
7044 // If this expression is a call to a builtin function in HIP device
7045 // compilation, allow a pointer-type argument to default address space to be
7046 // passed as a pointer-type parameter to a non-default address space.
7047 // If Arg is declared in the default address space and Param is declared
7048 // in a non-default address space, perform an implicit address space cast to
7049 // the parameter type.
7050 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
7051 FD->getBuiltinID()) {
7052 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
7053 ParmVarDecl *Param = FD->getParamDecl(Idx);
7054 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7055 !ArgExprs[Idx]->getType()->isPointerType())
7056 continue;
7057
7058 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7059 auto ArgTy = ArgExprs[Idx]->getType();
7060 auto ArgPtTy = ArgTy->getPointeeType();
7061 auto ArgAS = ArgPtTy.getAddressSpace();
7062
7063 // Add address space cast if target address spaces are different
7064 bool NeedImplicitASC =
7065 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7066 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7067 // or from specific AS which has target AS matching that of Param.
7068 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
7069 if (!NeedImplicitASC)
7070 continue;
7071
7072 // First, ensure that the Arg is an RValue.
7073 if (ArgExprs[Idx]->isGLValue()) {
7074 ArgExprs[Idx] = ImplicitCastExpr::Create(
7075 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
7076 nullptr, VK_PRValue, FPOptionsOverride());
7077 }
7078
7079 // Construct a new arg type with address space of Param
7080 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7081 ArgPtQuals.setAddressSpace(ParamAS);
7082 auto NewArgPtTy =
7083 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7084 auto NewArgTy =
7085 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
7086 ArgTy.getQualifiers());
7087
7088 // Finally perform an implicit address space cast
7089 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7090 CK_AddressSpaceConversion)
7091 .get();
7092 }
7093 }
7094 }
7095
7096 if (Context.isDependenceAllowed() &&
7097 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7098 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 7098, __extension__ __PRETTY_FUNCTION__))
;
7099 assert((Fn->containsErrors() ||(static_cast <bool> ((Fn->containsErrors() || llvm::
any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors
(); })) && "should only occur in error-recovery path."
) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 7102, __extension__ __PRETTY_FUNCTION__
))
7100 llvm::any_of(ArgExprs,(static_cast <bool> ((Fn->containsErrors() || llvm::
any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors
(); })) && "should only occur in error-recovery path."
) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 7102, __extension__ __PRETTY_FUNCTION__
))
7101 [](clang::Expr *E) { return E->containsErrors(); })) &&(static_cast <bool> ((Fn->containsErrors() || llvm::
any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors
(); })) && "should only occur in error-recovery path."
) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 7102, __extension__ __PRETTY_FUNCTION__
))
7102 "should only occur in error-recovery path.")(static_cast <bool> ((Fn->containsErrors() || llvm::
any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors
(); })) && "should only occur in error-recovery path."
) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 7102, __extension__ __PRETTY_FUNCTION__
))
;
7103 QualType ReturnType =
7104 llvm::isa_and_nonnull<FunctionDecl>(NDecl)
7105 ? cast<FunctionDecl>(NDecl)->getCallResultType()
7106 : Context.DependentTy;
7107 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
7108 Expr::getValueKindForType(ReturnType), RParenLoc,
7109 CurFPFeatureOverrides());
7110 }
7111 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7112 ExecConfig, IsExecConfig);
7113}
7114
7115/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7116// with the specified CallArgs
7117Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7118 MultiExprArg CallArgs) {
7119 StringRef Name = Context.BuiltinInfo.getName(Id);
7120 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7121 Sema::LookupOrdinaryName);
7122 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7123
7124 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7125 assert(BuiltInDecl && "failed to find builtin declaration")(static_cast <bool> (BuiltInDecl && "failed to find builtin declaration"
) ? void (0) : __assert_fail ("BuiltInDecl && \"failed to find builtin declaration\""
, "clang/lib/Sema/SemaExpr.cpp", 7125, __extension__ __PRETTY_FUNCTION__
))
;
7126
7127 ExprResult DeclRef =
7128 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7129 assert(DeclRef.isUsable() && "Builtin reference cannot fail")(static_cast <bool> (DeclRef.isUsable() && "Builtin reference cannot fail"
) ? void (0) : __assert_fail ("DeclRef.isUsable() && \"Builtin reference cannot fail\""
, "clang/lib/Sema/SemaExpr.cpp", 7129, __extension__ __PRETTY_FUNCTION__
))
;
7130
7131 ExprResult Call =
7132 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7133
7134 assert(!Call.isInvalid() && "Call to builtin cannot fail!")(static_cast <bool> (!Call.isInvalid() && "Call to builtin cannot fail!"
) ? void (0) : __assert_fail ("!Call.isInvalid() && \"Call to builtin cannot fail!\""
, "clang/lib/Sema/SemaExpr.cpp", 7134, __extension__ __PRETTY_FUNCTION__
))
;
7135 return Call.get();
7136}
7137
7138/// Parse a __builtin_astype expression.
7139///
7140/// __builtin_astype( value, dst type )
7141///
7142ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7143 SourceLocation BuiltinLoc,
7144 SourceLocation RParenLoc) {
7145 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7146 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7147}
7148
7149/// Create a new AsTypeExpr node (bitcast) from the arguments.
7150ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7151 SourceLocation BuiltinLoc,
7152 SourceLocation RParenLoc) {
7153 ExprValueKind VK = VK_PRValue;
7154 ExprObjectKind OK = OK_Ordinary;
7155 QualType SrcTy = E->getType();
7156 if (!SrcTy->isDependentType() &&
7157 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7158 return ExprError(
7159 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7160 << DestTy << SrcTy << E->getSourceRange());
7161 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7162}
7163
7164/// ActOnConvertVectorExpr - create a new convert-vector expression from the
7165/// provided arguments.
7166///
7167/// __builtin_convertvector( value, dst type )
7168///
7169ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7170 SourceLocation BuiltinLoc,
7171 SourceLocation RParenLoc) {
7172 TypeSourceInfo *TInfo;
7173 GetTypeFromParser(ParsedDestTy, &TInfo);
7174 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7175}
7176
7177/// BuildResolvedCallExpr - Build a call to a resolved expression,
7178/// i.e. an expression not of \p OverloadTy. The expression should
7179/// unary-convert to an expression of function-pointer or
7180/// block-pointer type.
7181///
7182/// \param NDecl the declaration being called, if available
7183ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7184 SourceLocation LParenLoc,
7185 ArrayRef<Expr *> Args,
7186 SourceLocation RParenLoc, Expr *Config,
7187 bool IsExecConfig, ADLCallKind UsesADL) {
7188 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7189 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7190
7191 // Functions with 'interrupt' attribute cannot be called directly.
7192 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
7193 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7194 return ExprError();
7195 }
7196
7197 // Interrupt handlers don't save off the VFP regs automatically on ARM,
7198 // so there's some risk when calling out to non-interrupt handler functions
7199 // that the callee might not preserve them. This is easy to diagnose here,
7200 // but can be very challenging to debug.
7201 // Likewise, X86 interrupt handlers may only call routines with attribute
7202 // no_caller_saved_registers since there is no efficient way to
7203 // save and restore the non-GPR state.
7204 if (auto *Caller = getCurFunctionDecl()) {
7205 if (Caller->hasAttr<ARMInterruptAttr>()) {
7206 bool VFP = Context.getTargetInfo().hasFeature("vfp");
7207 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
7208 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
7209 if (FDecl)
7210 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7211 }
7212 }
7213 if (Caller->hasAttr<AnyX86InterruptAttr>() &&
7214 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
7215 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
7216 if (FDecl)
7217 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7218 }
7219 }
7220
7221 // Promote the function operand.
7222 // We special-case function promotion here because we only allow promoting
7223 // builtin functions to function pointers in the callee of a call.
7224 ExprResult Result;
7225 QualType ResultTy;
7226 if (BuiltinID &&
7227 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7228 // Extract the return type from the (builtin) function pointer type.
7229 // FIXME Several builtins still have setType in
7230 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7231 // Builtins.def to ensure they are correct before removing setType calls.
7232 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7233 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7234 ResultTy = FDecl->getCallResultType();
7235 } else {
7236 Result = CallExprUnaryConversions(Fn);
7237 ResultTy = Context.BoolTy;
7238 }
7239 if (Result.isInvalid())
7240 return ExprError();
7241 Fn = Result.get();
7242
7243 // Check for a valid function type, but only if it is not a builtin which
7244 // requires custom type checking. These will be handled by
7245 // CheckBuiltinFunctionCall below just after creation of the call expression.
7246 const FunctionType *FuncT = nullptr;
7247 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7248 retry:
7249 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7250 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7251 // have type pointer to function".
7252 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7253 if (!FuncT)
7254 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7255 << Fn->getType() << Fn->getSourceRange());
7256 } else if (const BlockPointerType *BPT =
7257 Fn->getType()->getAs<BlockPointerType>()) {
7258 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7259 } else {
7260 // Handle calls to expressions of unknown-any type.
7261 if (Fn->getType() == Context.UnknownAnyTy) {
7262 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7263 if (rewrite.isInvalid())
7264 return ExprError();
7265 Fn = rewrite.get();
7266 goto retry;
7267 }
7268
7269 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7270 << Fn->getType() << Fn->getSourceRange());
7271 }
7272 }
7273
7274 // Get the number of parameters in the function prototype, if any.
7275 // We will allocate space for max(Args.size(), NumParams) arguments
7276 // in the call expression.
7277 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7278 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7279
7280 CallExpr *TheCall;
7281 if (Config) {
7282 assert(UsesADL == ADLCallKind::NotADL &&(static_cast <bool> (UsesADL == ADLCallKind::NotADL &&
"CUDAKernelCallExpr should not use ADL") ? void (0) : __assert_fail
("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\""
, "clang/lib/Sema/SemaExpr.cpp", 7283, __extension__ __PRETTY_FUNCTION__
))
7283 "CUDAKernelCallExpr should not use ADL")(static_cast <bool> (UsesADL == ADLCallKind::NotADL &&
"CUDAKernelCallExpr should not use ADL") ? void (0) : __assert_fail
("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\""
, "clang/lib/Sema/SemaExpr.cpp", 7283, __extension__ __PRETTY_FUNCTION__
))
;
7284 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7285 Args, ResultTy, VK_PRValue, RParenLoc,
7286 CurFPFeatureOverrides(), NumParams);
7287 } else {
7288 TheCall =
7289 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7290 CurFPFeatureOverrides(), NumParams, UsesADL);
7291 }
7292
7293 if (!Context.isDependenceAllowed()) {
7294 // Forget about the nulled arguments since typo correction
7295 // do not handle them well.
7296 TheCall->shrinkNumArgs(Args.size());
7297 // C cannot always handle TypoExpr nodes in builtin calls and direct
7298 // function calls as their argument checking don't necessarily handle
7299 // dependent types properly, so make sure any TypoExprs have been
7300 // dealt with.
7301 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7302 if (!Result.isUsable()) return ExprError();
7303 CallExpr *TheOldCall = TheCall;
7304 TheCall = dyn_cast<CallExpr>(Result.get());
7305 bool CorrectedTypos = TheCall != TheOldCall;
7306 if (!TheCall) return Result;
7307 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7308
7309 // A new call expression node was created if some typos were corrected.
7310 // However it may not have been constructed with enough storage. In this
7311 // case, rebuild the node with enough storage. The waste of space is
7312 // immaterial since this only happens when some typos were corrected.
7313 if (CorrectedTypos && Args.size() < NumParams) {
7314 if (Config)
7315 TheCall = CUDAKernelCallExpr::Create(
7316 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7317 RParenLoc, CurFPFeatureOverrides(), NumParams);
7318 else
7319 TheCall =
7320 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7321 CurFPFeatureOverrides(), NumParams, UsesADL);
7322 }
7323 // We can now handle the nulled arguments for the default arguments.
7324 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7325 }
7326
7327 // Bail out early if calling a builtin with custom type checking.
7328 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7329 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7330
7331 if (getLangOpts().CUDA) {
7332 if (Config) {
7333 // CUDA: Kernel calls must be to global functions
7334 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7335 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7336 << FDecl << Fn->getSourceRange());
7337
7338 // CUDA: Kernel function must have 'void' return type
7339 if (!FuncT->getReturnType()->isVoidType() &&
7340 !FuncT->getReturnType()->getAs<AutoType>() &&
7341 !FuncT->getReturnType()->isInstantiationDependentType())
7342 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7343 << Fn->getType() << Fn->getSourceRange());
7344 } else {
7345 // CUDA: Calls to global functions must be configured
7346 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7347 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7348 << FDecl << Fn->getSourceRange());
7349 }
7350 }
7351
7352 // Check for a valid return type
7353 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7354 FDecl))
7355 return ExprError();
7356
7357 // We know the result type of the call, set it.
7358 TheCall->setType(FuncT->getCallResultType(Context));
7359 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7360
7361 if (Proto) {
7362 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7363 IsExecConfig))
7364 return ExprError();
7365 } else {
7366 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")(static_cast <bool> (isa<FunctionNoProtoType>(FuncT
) && "Unknown FunctionType!") ? void (0) : __assert_fail
("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\""
, "clang/lib/Sema/SemaExpr.cpp", 7366, __extension__ __PRETTY_FUNCTION__
))
;
7367
7368 if (FDecl) {
7369 // Check if we have too few/too many template arguments, based
7370 // on our knowledge of the function definition.
7371 const FunctionDecl *Def = nullptr;
7372 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7373 Proto = Def->getType()->getAs<FunctionProtoType>();
7374 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7375 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7376 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7377 }
7378
7379 // If the function we're calling isn't a function prototype, but we have
7380 // a function prototype from a prior declaratiom, use that prototype.
7381 if (!FDecl->hasPrototype())
7382 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7383 }
7384
7385 // If we still haven't found a prototype to use but there are arguments to
7386 // the call, diagnose this as calling a function without a prototype.
7387 // However, if we found a function declaration, check to see if
7388 // -Wdeprecated-non-prototype was disabled where the function was declared.
7389 // If so, we will silence the diagnostic here on the assumption that this
7390 // interface is intentional and the user knows what they're doing. We will
7391 // also silence the diagnostic if there is a function declaration but it
7392 // was implicitly defined (the user already gets diagnostics about the
7393 // creation of the implicit function declaration, so the additional warning
7394 // is not helpful).
7395 if (!Proto && !Args.empty() &&
7396 (!FDecl || (!FDecl->isImplicit() &&
7397 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7398 FDecl->getLocation()))))
7399 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7400 << (FDecl != nullptr) << FDecl;
7401
7402 // Promote the arguments (C99 6.5.2.2p6).
7403 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7404 Expr *Arg = Args[i];
7405
7406 if (Proto && i < Proto->getNumParams()) {
7407 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7408 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7409 ExprResult ArgE =
7410 PerformCopyInitialization(Entity, SourceLocation(), Arg);
7411 if (ArgE.isInvalid())
7412 return true;
7413
7414 Arg = ArgE.getAs<Expr>();
7415
7416 } else {
7417 ExprResult ArgE = DefaultArgumentPromotion(Arg);
7418
7419 if (ArgE.isInvalid())
7420 return true;
7421
7422 Arg = ArgE.getAs<Expr>();
7423 }
7424
7425 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7426 diag::err_call_incomplete_argument, Arg))
7427 return ExprError();
7428
7429 TheCall->setArg(i, Arg);
7430 }
7431 TheCall->computeDependence();
7432 }
7433
7434 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7435 if (!Method->isStatic())
7436 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7437 << Fn->getSourceRange());
7438
7439 // Check for sentinels
7440 if (NDecl)
7441 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7442
7443 // Warn for unions passing across security boundary (CMSE).
7444 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7445 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7446 if (const auto *RT =
7447 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7448 if (RT->getDecl()->isOrContainsUnion())
7449 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7450 << 0 << i;
7451 }
7452 }
7453 }
7454
7455 // Do special checking on direct calls to functions.
7456 if (FDecl) {
7457 if (CheckFunctionCall(FDecl, TheCall, Proto))
7458 return ExprError();
7459
7460 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7461
7462 if (BuiltinID)
7463 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7464 } else if (NDecl) {
7465 if (CheckPointerCall(NDecl, TheCall, Proto))
7466 return ExprError();
7467 } else {
7468 if (CheckOtherCall(TheCall, Proto))
7469 return ExprError();
7470 }
7471
7472 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7473}
7474
7475ExprResult
7476Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7477 SourceLocation RParenLoc, Expr *InitExpr) {
7478 assert(Ty && "ActOnCompoundLiteral(): missing type")(static_cast <bool> (Ty && "ActOnCompoundLiteral(): missing type"
) ? void (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\""
, "clang/lib/Sema/SemaExpr.cpp", 7478, __extension__ __PRETTY_FUNCTION__
))
;
7479 assert(InitExpr && "ActOnCompoundLiteral(): missing expression")(static_cast <bool> (InitExpr && "ActOnCompoundLiteral(): missing expression"
) ? void (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\""
, "clang/lib/Sema/SemaExpr.cpp", 7479, __extension__ __PRETTY_FUNCTION__
))
;
7480
7481 TypeSourceInfo *TInfo;
7482 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7483 if (!TInfo)
7484 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7485
7486 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7487}
7488
7489ExprResult
7490Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7491 SourceLocation RParenLoc, Expr *LiteralExpr) {
7492 QualType literalType = TInfo->getType();
7493
7494 if (literalType->isArrayType()) {
7495 if (RequireCompleteSizedType(
7496 LParenLoc, Context.getBaseElementType(literalType),
7497 diag::err_array_incomplete_or_sizeless_type,
7498 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7499 return ExprError();
7500 if (literalType->isVariableArrayType()) {
7501 // C2x 6.7.9p4: An entity of variable length array type shall not be
7502 // initialized except by an empty initializer.
7503 //
7504 // The C extension warnings are issued from ParseBraceInitializer() and
7505 // do not need to be issued here. However, we continue to issue an error
7506 // in the case there are initializers or we are compiling C++. We allow
7507 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7508 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7509 // FIXME: should we allow this construct in C++ when it makes sense to do
7510 // so?
7511 std::optional<unsigned> NumInits;
7512 if (const auto *ILE = dyn_cast<InitListExpr>(LiteralExpr))
7513 NumInits = ILE->getNumInits();
7514 if ((LangOpts.CPlusPlus || NumInits.value_or(0)) &&
7515 !tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7516 diag::err_variable_object_no_init))
7517 return ExprError();
7518 }
7519 } else if (!literalType->isDependentType() &&
7520 RequireCompleteType(LParenLoc, literalType,
7521 diag::err_typecheck_decl_incomplete_type,
7522 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7523 return ExprError();
7524
7525 InitializedEntity Entity
7526 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7527 InitializationKind Kind
7528 = InitializationKind::CreateCStyleCast(LParenLoc,
7529 SourceRange(LParenLoc, RParenLoc),
7530 /*InitList=*/true);
7531 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7532 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7533 &literalType);
7534 if (Result.isInvalid())
7535 return ExprError();
7536 LiteralExpr = Result.get();
7537
7538 bool isFileScope = !CurContext->isFunctionOrMethod();
7539
7540 // In C, compound literals are l-values for some reason.
7541 // For GCC compatibility, in C++, file-scope array compound literals with
7542 // constant initializers are also l-values, and compound literals are
7543 // otherwise prvalues.
7544 //
7545 // (GCC also treats C++ list-initialized file-scope array prvalues with
7546 // constant initializers as l-values, but that's non-conforming, so we don't
7547 // follow it there.)
7548 //
7549 // FIXME: It would be better to handle the lvalue cases as materializing and
7550 // lifetime-extending a temporary object, but our materialized temporaries
7551 // representation only supports lifetime extension from a variable, not "out
7552 // of thin air".
7553 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7554 // is bound to the result of applying array-to-pointer decay to the compound
7555 // literal.
7556 // FIXME: GCC supports compound literals of reference type, which should
7557 // obviously have a value kind derived from the kind of reference involved.
7558 ExprValueKind VK =
7559 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7560 ? VK_PRValue
7561 : VK_LValue;
7562
7563 if (isFileScope)
7564 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7565 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7566 Expr *Init = ILE->getInit(i);
7567 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7568 }
7569
7570 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7571 VK, LiteralExpr, isFileScope);
7572 if (isFileScope) {
7573 if (!LiteralExpr->isTypeDependent() &&
7574 !LiteralExpr->isValueDependent() &&
7575 !literalType->isDependentType()) // C99 6.5.2.5p3
7576 if (CheckForConstantInitializer(LiteralExpr, literalType))
7577 return ExprError();
7578 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7579 literalType.getAddressSpace() != LangAS::Default) {
7580 // Embedded-C extensions to C99 6.5.2.5:
7581 // "If the compound literal occurs inside the body of a function, the
7582 // type name shall not be qualified by an address-space qualifier."
7583 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7584 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7585 return ExprError();
7586 }
7587
7588 if (!isFileScope && !getLangOpts().CPlusPlus) {
7589 // Compound literals that have automatic storage duration are destroyed at
7590 // the end of the scope in C; in C++, they're just temporaries.
7591
7592 // Emit diagnostics if it is or contains a C union type that is non-trivial
7593 // to destruct.
7594 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7595 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7596 NTCUC_CompoundLiteral, NTCUK_Destruct);
7597
7598 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7599 if (literalType.isDestructedType()) {
7600 Cleanup.setExprNeedsCleanups(true);
7601 ExprCleanupObjects.push_back(E);
7602 getCurFunction()->setHasBranchProtectedScope();
7603 }
7604 }
7605
7606 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7607 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7608 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7609 E->getInitializer()->getExprLoc());
7610
7611 return MaybeBindToTemporary(E);
7612}
7613
7614ExprResult
7615Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7616 SourceLocation RBraceLoc) {
7617 // Only produce each kind of designated initialization diagnostic once.
7618 SourceLocation FirstDesignator;
7619 bool DiagnosedArrayDesignator = false;
7620 bool DiagnosedNestedDesignator = false;
7621 bool DiagnosedMixedDesignator = false;
7622
7623 // Check that any designated initializers are syntactically valid in the
7624 // current language mode.
7625 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7626 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7627 if (FirstDesignator.isInvalid())
7628 FirstDesignator = DIE->getBeginLoc();
7629
7630 if (!getLangOpts().CPlusPlus)
7631 break;
7632
7633 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7634 DiagnosedNestedDesignator = true;
7635 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7636 << DIE->getDesignatorsSourceRange();
7637 }
7638
7639 for (auto &Desig : DIE->designators()) {
7640 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7641 DiagnosedArrayDesignator = true;
7642 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7643 << Desig.getSourceRange();
7644 }
7645 }
7646
7647 if (!DiagnosedMixedDesignator &&
7648 !isa<DesignatedInitExpr>(InitArgList[0])) {
7649 DiagnosedMixedDesignator = true;
7650 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7651 << DIE->getSourceRange();
7652 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7653 << InitArgList[0]->getSourceRange();
7654 }
7655 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7656 isa<DesignatedInitExpr>(InitArgList[0])) {
7657 DiagnosedMixedDesignator = true;
7658 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7659 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7660 << DIE->getSourceRange();
7661 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7662 << InitArgList[I]->getSourceRange();
7663 }
7664 }
7665
7666 if (FirstDesignator.isValid()) {
7667 // Only diagnose designated initiaization as a C++20 extension if we didn't
7668 // already diagnose use of (non-C++20) C99 designator syntax.
7669 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7670 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7671 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7672 ? diag::warn_cxx17_compat_designated_init
7673 : diag::ext_cxx_designated_init);
7674 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7675 Diag(FirstDesignator, diag::ext_designated_init);
7676 }
7677 }
7678
7679 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7680}
7681
7682ExprResult
7683Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7684 SourceLocation RBraceLoc) {
7685 // Semantic analysis for initializers is done by ActOnDeclarator() and
7686 // CheckInitializer() - it requires knowledge of the object being initialized.
7687
7688 // Immediately handle non-overload placeholders. Overloads can be
7689 // resolved contextually, but everything else here can't.
7690 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7691 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7692 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7693
7694 // Ignore failures; dropping the entire initializer list because
7695 // of one failure would be terrible for indexing/etc.
7696 if (result.isInvalid()) continue;
7697
7698 InitArgList[I] = result.get();
7699 }
7700 }
7701
7702 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7703 RBraceLoc);
7704 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7705 return E;
7706}
7707
7708/// Do an explicit extend of the given block pointer if we're in ARC.
7709void Sema::maybeExtendBlockObject(ExprResult &E) {
7710 assert(E.get()->getType()->isBlockPointerType())(static_cast <bool> (E.get()->getType()->isBlockPointerType
()) ? void (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 7710, __extension__ __PRETTY_FUNCTION__
))
;
7711 assert(E.get()->isPRValue())(static_cast <bool> (E.get()->isPRValue()) ? void (0
) : __assert_fail ("E.get()->isPRValue()", "clang/lib/Sema/SemaExpr.cpp"
, 7711, __extension__ __PRETTY_FUNCTION__))
;
7712
7713 // Only do this in an r-value context.
7714 if (!getLangOpts().ObjCAutoRefCount) return;
7715
7716 E = ImplicitCastExpr::Create(
7717 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7718 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7719 Cleanup.setExprNeedsCleanups(true);
7720}
7721
7722/// Prepare a conversion of the given expression to an ObjC object
7723/// pointer type.
7724CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7725 QualType type = E.get()->getType();
7726 if (type->isObjCObjectPointerType()) {
7727 return CK_BitCast;
7728 } else if (type->isBlockPointerType()) {
7729 maybeExtendBlockObject(E);
7730 return CK_BlockPointerToObjCPointerCast;
7731 } else {
7732 assert(type->isPointerType())(static_cast <bool> (type->isPointerType()) ? void (
0) : __assert_fail ("type->isPointerType()", "clang/lib/Sema/SemaExpr.cpp"
, 7732, __extension__ __PRETTY_FUNCTION__))
;
7733 return CK_CPointerToObjCPointerCast;
7734 }
7735}
7736
7737/// Prepares for a scalar cast, performing all the necessary stages
7738/// except the final cast and returning the kind required.
7739CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7740 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7741 // Also, callers should have filtered out the invalid cases with
7742 // pointers. Everything else should be possible.
7743
7744 QualType SrcTy = Src.get()->getType();
7745 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7746 return CK_NoOp;
7747
7748 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7749 case Type::STK_MemberPointer:
7750 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7750)
;
7751
7752 case Type::STK_CPointer:
7753 case Type::STK_BlockPointer:
7754 case Type::STK_ObjCObjectPointer:
7755 switch (DestTy->getScalarTypeKind()) {
7756 case Type::STK_CPointer: {
7757 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7758 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7759 if (SrcAS != DestAS)
7760 return CK_AddressSpaceConversion;
7761 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7762 return CK_NoOp;
7763 return CK_BitCast;
7764 }
7765 case Type::STK_BlockPointer:
7766 return (SrcKind == Type::STK_BlockPointer
7767 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7768 case Type::STK_ObjCObjectPointer:
7769 if (SrcKind == Type::STK_ObjCObjectPointer)
7770 return CK_BitCast;
7771 if (SrcKind == Type::STK_CPointer)
7772 return CK_CPointerToObjCPointerCast;
7773 maybeExtendBlockObject(Src);
7774 return CK_BlockPointerToObjCPointerCast;
7775 case Type::STK_Bool:
7776 return CK_PointerToBoolean;
7777 case Type::STK_Integral:
7778 return CK_PointerToIntegral;
7779 case Type::STK_Floating:
7780 case Type::STK_FloatingComplex:
7781 case Type::STK_IntegralComplex:
7782 case Type::STK_MemberPointer:
7783 case Type::STK_FixedPoint:
7784 llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer"
, "clang/lib/Sema/SemaExpr.cpp", 7784)
;
7785 }
7786 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7786)
;
7787
7788 case Type::STK_FixedPoint:
7789 switch (DestTy->getScalarTypeKind()) {
7790 case Type::STK_FixedPoint:
7791 return CK_FixedPointCast;
7792 case Type::STK_Bool:
7793 return CK_FixedPointToBoolean;
7794 case Type::STK_Integral:
7795 return CK_FixedPointToIntegral;
7796 case Type::STK_Floating:
7797 return CK_FixedPointToFloating;
7798 case Type::STK_IntegralComplex:
7799 case Type::STK_FloatingComplex:
7800 Diag(Src.get()->getExprLoc(),
7801 diag::err_unimplemented_conversion_with_fixed_point_type)
7802 << DestTy;
7803 return CK_IntegralCast;
7804 case Type::STK_CPointer:
7805 case Type::STK_ObjCObjectPointer:
7806 case Type::STK_BlockPointer:
7807 case Type::STK_MemberPointer:
7808 llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type"
, "clang/lib/Sema/SemaExpr.cpp", 7808)
;
7809 }
7810 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7810)
;
7811
7812 case Type::STK_Bool: // casting from bool is like casting from an integer
7813 case Type::STK_Integral:
7814 switch (DestTy->getScalarTypeKind()) {
7815 case Type::STK_CPointer:
7816 case Type::STK_ObjCObjectPointer:
7817 case Type::STK_BlockPointer:
7818 if (Src.get()->isNullPointerConstant(Context,
7819 Expr::NPC_ValueDependentIsNull))
7820 return CK_NullToPointer;
7821 return CK_IntegralToPointer;
7822 case Type::STK_Bool:
7823 return CK_IntegralToBoolean;
7824 case Type::STK_Integral:
7825 return CK_IntegralCast;
7826 case Type::STK_Floating:
7827 return CK_IntegralToFloating;
7828 case Type::STK_IntegralComplex:
7829 Src = ImpCastExprToType(Src.get(),
7830 DestTy->castAs<ComplexType>()->getElementType(),
7831 CK_IntegralCast);
7832 return CK_IntegralRealToComplex;
7833 case Type::STK_FloatingComplex:
7834 Src = ImpCastExprToType(Src.get(),
7835 DestTy->castAs<ComplexType>()->getElementType(),
7836 CK_IntegralToFloating);
7837 return CK_FloatingRealToComplex;
7838 case Type::STK_MemberPointer:
7839 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7839)
;
7840 case Type::STK_FixedPoint:
7841 return CK_IntegralToFixedPoint;
7842 }
7843 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7843)
;
7844
7845 case Type::STK_Floating:
7846 switch (DestTy->getScalarTypeKind()) {
7847 case Type::STK_Floating:
7848 return CK_FloatingCast;
7849 case Type::STK_Bool:
7850 return CK_FloatingToBoolean;
7851 case Type::STK_Integral:
7852 return CK_FloatingToIntegral;
7853 case Type::STK_FloatingComplex:
7854 Src = ImpCastExprToType(Src.get(),
7855 DestTy->castAs<ComplexType>()->getElementType(),
7856 CK_FloatingCast);
7857 return CK_FloatingRealToComplex;
7858 case Type::STK_IntegralComplex:
7859 Src = ImpCastExprToType(Src.get(),
7860 DestTy->castAs<ComplexType>()->getElementType(),
7861 CK_FloatingToIntegral);
7862 return CK_IntegralRealToComplex;
7863 case Type::STK_CPointer:
7864 case Type::STK_ObjCObjectPointer:
7865 case Type::STK_BlockPointer:
7866 llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7866)
;
7867 case Type::STK_MemberPointer:
7868 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7868)
;
7869 case Type::STK_FixedPoint:
7870 return CK_FloatingToFixedPoint;
7871 }
7872 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7872)
;
7873
7874 case Type::STK_FloatingComplex:
7875 switch (DestTy->getScalarTypeKind()) {
7876 case Type::STK_FloatingComplex:
7877 return CK_FloatingComplexCast;
7878 case Type::STK_IntegralComplex:
7879 return CK_FloatingComplexToIntegralComplex;
7880 case Type::STK_Floating: {
7881 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7882 if (Context.hasSameType(ET, DestTy))
7883 return CK_FloatingComplexToReal;
7884 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7885 return CK_FloatingCast;
7886 }
7887 case Type::STK_Bool:
7888 return CK_FloatingComplexToBoolean;
7889 case Type::STK_Integral:
7890 Src = ImpCastExprToType(Src.get(),
7891 SrcTy->castAs<ComplexType>()->getElementType(),
7892 CK_FloatingComplexToReal);
7893 return CK_FloatingToIntegral;
7894 case Type::STK_CPointer:
7895 case Type::STK_ObjCObjectPointer:
7896 case Type::STK_BlockPointer:
7897 llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7897)
;
7898 case Type::STK_MemberPointer:
7899 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7899)
;
7900 case Type::STK_FixedPoint:
7901 Diag(Src.get()->getExprLoc(),
7902 diag::err_unimplemented_conversion_with_fixed_point_type)
7903 << SrcTy;
7904 return CK_IntegralCast;
7905 }
7906 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7906)
;
7907
7908 case Type::STK_IntegralComplex:
7909 switch (DestTy->getScalarTypeKind()) {
7910 case Type::STK_FloatingComplex:
7911 return CK_IntegralComplexToFloatingComplex;
7912 case Type::STK_IntegralComplex:
7913 return CK_IntegralComplexCast;
7914 case Type::STK_Integral: {
7915 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7916 if (Context.hasSameType(ET, DestTy))
7917 return CK_IntegralComplexToReal;
7918 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7919 return CK_IntegralCast;
7920 }
7921 case Type::STK_Bool:
7922 return CK_IntegralComplexToBoolean;
7923 case Type::STK_Floating:
7924 Src = ImpCastExprToType(Src.get(),
7925 SrcTy->castAs<ComplexType>()->getElementType(),
7926 CK_IntegralComplexToReal);
7927 return CK_IntegralToFloating;
7928 case Type::STK_CPointer:
7929 case Type::STK_ObjCObjectPointer:
7930 case Type::STK_BlockPointer:
7931 llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7931)
;
7932 case Type::STK_MemberPointer:
7933 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7933)
;
7934 case Type::STK_FixedPoint:
7935 Diag(Src.get()->getExprLoc(),
7936 diag::err_unimplemented_conversion_with_fixed_point_type)
7937 << SrcTy;
7938 return CK_IntegralCast;
7939 }
7940 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7940)
;
7941 }
7942
7943 llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "clang/lib/Sema/SemaExpr.cpp"
, 7943)
;
7944}
7945
7946static bool breakDownVectorType(QualType type, uint64_t &len,
7947 QualType &eltType) {
7948 // Vectors are simple.
7949 if (const VectorType *vecType = type->getAs<VectorType>()) {
7950 len = vecType->getNumElements();
7951 eltType = vecType->getElementType();
7952 assert(eltType->isScalarType())(static_cast <bool> (eltType->isScalarType()) ? void
(0) : __assert_fail ("eltType->isScalarType()", "clang/lib/Sema/SemaExpr.cpp"
, 7952, __extension__ __PRETTY_FUNCTION__))
;
7953 return true;
7954 }
7955
7956 // We allow lax conversion to and from non-vector types, but only if
7957 // they're real types (i.e. non-complex, non-pointer scalar types).
7958 if (!type->isRealType()) return false;
7959
7960 len = 1;
7961 eltType = type;
7962 return true;
7963}
7964
7965/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7966/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7967/// allowed?
7968///
7969/// This will also return false if the two given types do not make sense from
7970/// the perspective of SVE bitcasts.
7971bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7972 assert(srcTy->isVectorType() || destTy->isVectorType())(static_cast <bool> (srcTy->isVectorType() || destTy
->isVectorType()) ? void (0) : __assert_fail ("srcTy->isVectorType() || destTy->isVectorType()"
, "clang/lib/Sema/SemaExpr.cpp", 7972, __extension__ __PRETTY_FUNCTION__
))
;
7973
7974 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7975 if (!FirstType->isSVESizelessBuiltinType())
7976 return false;
7977
7978 const auto *VecTy = SecondType->getAs<VectorType>();
7979 return VecTy &&
7980 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7981 };
7982
7983 return ValidScalableConversion(srcTy, destTy) ||
7984 ValidScalableConversion(destTy, srcTy);
7985}
7986
7987/// Are the two types RVV-bitcast-compatible types? I.e. is bitcasting from the
7988/// first RVV type (e.g. an RVV scalable type) to the second type (e.g. an RVV
7989/// VLS type) allowed?
7990///
7991/// This will also return false if the two given types do not make sense from
7992/// the perspective of RVV bitcasts.
7993bool Sema::isValidRVVBitcast(QualType srcTy, QualType destTy) {
7994 assert(srcTy->isVectorType() || destTy->isVectorType())(static_cast <bool> (srcTy->isVectorType() || destTy
->isVectorType()) ? void (0) : __assert_fail ("srcTy->isVectorType() || destTy->isVectorType()"
, "clang/lib/Sema/SemaExpr.cpp", 7994, __extension__ __PRETTY_FUNCTION__
))
;
7995
7996 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7997 if (!FirstType->isRVVSizelessBuiltinType())
7998 return false;
7999
8000 const auto *VecTy = SecondType->getAs<VectorType>();
8001 return VecTy &&
8002 VecTy->getVectorKind() == VectorType::RVVFixedLengthDataVector;
8003 };
8004
8005 return ValidScalableConversion(srcTy, destTy) ||
8006 ValidScalableConversion(destTy, srcTy);
8007}
8008
8009/// Are the two types matrix types and do they have the same dimensions i.e.
8010/// do they have the same number of rows and the same number of columns?
8011bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
8012 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8013 return false;
8014
8015 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8016 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8017
8018 return matSrcType->getNumRows() == matDestType->getNumRows() &&
8019 matSrcType->getNumColumns() == matDestType->getNumColumns();
8020}
8021
8022bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
8023 assert(DestTy->isVectorType() || SrcTy->isVectorType())(static_cast <bool> (DestTy->isVectorType() || SrcTy
->isVectorType()) ? void (0) : __assert_fail ("DestTy->isVectorType() || SrcTy->isVectorType()"
, "clang/lib/Sema/SemaExpr.cpp", 8023, __extension__ __PRETTY_FUNCTION__
))
;
8024
8025 uint64_t SrcLen, DestLen;
8026 QualType SrcEltTy, DestEltTy;
8027 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
8028 return false;
8029 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
8030 return false;
8031
8032 // ASTContext::getTypeSize will return the size rounded up to a
8033 // power of 2, so instead of using that, we need to use the raw
8034 // element size multiplied by the element count.
8035 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
8036 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
8037
8038 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8039}
8040
8041// This returns true if at least one of the types is an altivec vector.
8042bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
8043 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&(static_cast <bool> ((DestTy->isVectorType() || SrcTy
->isVectorType()) && "expected at least one type to be a vector here"
) ? void (0) : __assert_fail ("(DestTy->isVectorType() || SrcTy->isVectorType()) && \"expected at least one type to be a vector here\""
, "clang/lib/Sema/SemaExpr.cpp", 8044, __extension__ __PRETTY_FUNCTION__
))
8044 "expected at least one type to be a vector here")(static_cast <bool> ((DestTy->isVectorType() || SrcTy
->isVectorType()) && "expected at least one type to be a vector here"
) ? void (0) : __assert_fail ("(DestTy->isVectorType() || SrcTy->isVectorType()) && \"expected at least one type to be a vector here\""
, "clang/lib/Sema/SemaExpr.cpp", 8044, __extension__ __PRETTY_FUNCTION__
))
;
8045
8046 bool IsSrcTyAltivec =
8047 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8048 VectorType::AltiVecVector) ||
8049 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8050 VectorType::AltiVecBool) ||
8051 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8052 VectorType::AltiVecPixel));
8053
8054 bool IsDestTyAltivec = DestTy->isVectorType() &&
8055 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8056 VectorType::AltiVecVector) ||
8057 (DestTy->castAs<VectorType>()->getVectorKind() ==
8058 VectorType::AltiVecBool) ||
8059 (DestTy->castAs<VectorType>()->getVectorKind() ==
8060 VectorType::AltiVecPixel));
8061
8062 return (IsSrcTyAltivec || IsDestTyAltivec);
8063}
8064
8065/// Are the two types lax-compatible vector types? That is, given
8066/// that one of them is a vector, do they have equal storage sizes,
8067/// where the storage size is the number of elements times the element
8068/// size?
8069///
8070/// This will also return false if either of the types is neither a
8071/// vector nor a real type.
8072bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8073 assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy
->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()"
, "clang/lib/Sema/SemaExpr.cpp", 8073, __extension__ __PRETTY_FUNCTION__
))
;
8074
8075 // Disallow lax conversions between scalars and ExtVectors (these
8076 // conversions are allowed for other vector types because common headers
8077 // depend on them). Most scalar OP ExtVector cases are handled by the
8078 // splat path anyway, which does what we want (convert, not bitcast).
8079 // What this rules out for ExtVectors is crazy things like char4*float.
8080 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8081 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8082
8083 return areVectorTypesSameSize(srcTy, destTy);
8084}
8085
8086/// Is this a legal conversion between two types, one of which is
8087/// known to be a vector type?
8088bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8089 assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy
->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()"
, "clang/lib/Sema/SemaExpr.cpp", 8089, __extension__ __PRETTY_FUNCTION__
))
;
8090
8091 switch (Context.getLangOpts().getLaxVectorConversions()) {
8092 case LangOptions::LaxVectorConversionKind::None:
8093 return false;
8094
8095 case LangOptions::LaxVectorConversionKind::Integer:
8096 if (!srcTy->isIntegralOrEnumerationType()) {
8097 auto *Vec = srcTy->getAs<VectorType>();
8098 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8099 return false;
8100 }
8101 if (!destTy->isIntegralOrEnumerationType()) {
8102 auto *Vec = destTy->getAs<VectorType>();
8103 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8104 return false;
8105 }
8106 // OK, integer (vector) -> integer (vector) bitcast.
8107 break;
8108
8109 case LangOptions::LaxVectorConversionKind::All:
8110 break;
8111 }
8112
8113 return areLaxCompatibleVectorTypes(srcTy, destTy);
8114}
8115
8116bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8117 CastKind &Kind) {
8118 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8119 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8120 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8121 << DestTy << SrcTy << R;
8122 }
8123 } else if (SrcTy->isMatrixType()) {
8124 return Diag(R.getBegin(),
8125 diag::err_invalid_conversion_between_matrix_and_type)
8126 << SrcTy << DestTy << R;
8127 } else if (DestTy->isMatrixType()) {
8128 return Diag(R.getBegin(),
8129 diag::err_invalid_conversion_between_matrix_and_type)
8130 << DestTy << SrcTy << R;
8131 }
8132
8133 Kind = CK_MatrixCast;
8134 return false;
8135}
8136
8137bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8138 CastKind &Kind) {
8139 assert(VectorTy->isVectorType() && "Not a vector type!")(static_cast <bool> (VectorTy->isVectorType() &&
"Not a vector type!") ? void (0) : __assert_fail ("VectorTy->isVectorType() && \"Not a vector type!\""
, "clang/lib/Sema/SemaExpr.cpp", 8139, __extension__ __PRETTY_FUNCTION__
))
;
8140
8141 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8142 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8143 return Diag(R.getBegin(),
8144 Ty->isVectorType() ?
8145 diag::err_invalid_conversion_between_vectors :
8146 diag::err_invalid_conversion_between_vector_and_integer)
8147 << VectorTy << Ty << R;
8148 } else
8149 return Diag(R.getBegin(),
8150 diag::err_invalid_conversion_between_vector_and_scalar)
8151 << VectorTy << Ty << R;
8152
8153 Kind = CK_BitCast;
8154 return false;
8155}
8156
8157ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8158 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8159
8160 if (DestElemTy == SplattedExpr->getType())
8161 return SplattedExpr;
8162
8163 assert(DestElemTy->isFloatingType() ||(static_cast <bool> (DestElemTy->isFloatingType() ||
DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "clang/lib/Sema/SemaExpr.cpp", 8164, __extension__ __PRETTY_FUNCTION__
))
8164 DestElemTy->isIntegralOrEnumerationType())(static_cast <bool> (DestElemTy->isFloatingType() ||
DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "clang/lib/Sema/SemaExpr.cpp", 8164, __extension__ __PRETTY_FUNCTION__
))
;
8165
8166 CastKind CK;
8167 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8168 // OpenCL requires that we convert `true` boolean expressions to -1, but
8169 // only when splatting vectors.
8170 if (DestElemTy->isFloatingType()) {
8171 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8172 // in two steps: boolean to signed integral, then to floating.
8173 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8174 CK_BooleanToSignedIntegral);
8175 SplattedExpr = CastExprRes.get();
8176 CK = CK_IntegralToFloating;
8177 } else {
8178 CK = CK_BooleanToSignedIntegral;
8179 }
8180 } else {
8181 ExprResult CastExprRes = SplattedExpr;
8182 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8183 if (CastExprRes.isInvalid())
8184 return ExprError();
8185 SplattedExpr = CastExprRes.get();
8186 }
8187 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8188}
8189
8190ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8191 Expr *CastExpr, CastKind &Kind) {
8192 assert(DestTy->isExtVectorType() && "Not an extended vector type!")(static_cast <bool> (DestTy->isExtVectorType() &&
"Not an extended vector type!") ? void (0) : __assert_fail (
"DestTy->isExtVectorType() && \"Not an extended vector type!\""
, "clang/lib/Sema/SemaExpr.cpp", 8192, __extension__ __PRETTY_FUNCTION__
))
;
8193
8194 QualType SrcTy = CastExpr->getType();
8195
8196 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8197 // an ExtVectorType.
8198 // In OpenCL, casts between vectors of different types are not allowed.
8199 // (See OpenCL 6.2).
8200 if (SrcTy->isVectorType()) {
8201 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8202 (getLangOpts().OpenCL &&
8203 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
8204 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8205 << DestTy << SrcTy << R;
8206 return ExprError();
8207 }
8208 Kind = CK_BitCast;
8209 return CastExpr;
8210 }
8211
8212 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8213 // conversion will take place first from scalar to elt type, and then
8214 // splat from elt type to vector.
8215 if (SrcTy->isPointerType())
8216 return Diag(R.getBegin(),
8217 diag::err_invalid_conversion_between_vector_and_scalar)
8218 << DestTy << SrcTy << R;
8219
8220 Kind = CK_VectorSplat;
8221 return prepareVectorSplat(DestTy, CastExpr);
8222}
8223
8224ExprResult
8225Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8226 Declarator &D, ParsedType &Ty,
8227 SourceLocation RParenLoc, Expr *CastExpr) {
8228 assert(!D.isInvalidType() && (CastExpr != nullptr) &&(static_cast <bool> (!D.isInvalidType() && (CastExpr
!= nullptr) && "ActOnCastExpr(): missing type or expr"
) ? void (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\""
, "clang/lib/Sema/SemaExpr.cpp", 8229, __extension__ __PRETTY_FUNCTION__
))
8229 "ActOnCastExpr(): missing type or expr")(static_cast <bool> (!D.isInvalidType() && (CastExpr
!= nullptr) && "ActOnCastExpr(): missing type or expr"
) ? void (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\""
, "clang/lib/Sema/SemaExpr.cpp", 8229, __extension__ __PRETTY_FUNCTION__
))
;
8230
8231 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
8232 if (D.isInvalidType())
8233 return ExprError();
8234
8235 if (getLangOpts().CPlusPlus) {
8236 // Check that there are no default arguments (C++ only).
8237 CheckExtraCXXDefaultArguments(D);
8238 } else {
8239 // Make sure any TypoExprs have been dealt with.
8240 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
8241 if (!Res.isUsable())
8242 return ExprError();
8243 CastExpr = Res.get();
8244 }
8245
8246 checkUnusedDeclAttributes(D);
8247
8248 QualType castType = castTInfo->getType();
8249 Ty = CreateParsedType(castType, castTInfo);
8250
8251 bool isVectorLiteral = false;
8252
8253 // Check for an altivec or OpenCL literal,
8254 // i.e. all the elements are integer constants.
8255 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8256 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8257 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8258 && castType->isVectorType() && (PE || PLE)) {
8259 if (PLE && PLE->getNumExprs() == 0) {
8260 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8261 return ExprError();
8262 }
8263 if (PE || PLE->getNumExprs() == 1) {
8264 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8265 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8266 isVectorLiteral = true;
8267 }
8268 else
8269 isVectorLiteral = true;
8270 }
8271
8272 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8273 // then handle it as such.
8274 if (isVectorLiteral)
8275 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8276
8277 // If the Expr being casted is a ParenListExpr, handle it specially.
8278 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8279 // sequence of BinOp comma operators.
8280 if (isa<ParenListExpr>(CastExpr)) {
8281 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
8282 if (Result.isInvalid()) return ExprError();
8283 CastExpr = Result.get();
8284 }
8285
8286 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8287 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8288
8289 CheckTollFreeBridgeCast(castType, CastExpr);
8290
8291 CheckObjCBridgeRelatedCast(castType, CastExpr);
8292
8293 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
8294
8295 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8296}
8297
8298ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8299 SourceLocation RParenLoc, Expr *E,
8300 TypeSourceInfo *TInfo) {
8301 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(static_cast <bool> ((isa<ParenListExpr>(E) || isa
<ParenExpr>(E)) && "Expected paren or paren list expression"
) ? void (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\""
, "clang/lib/Sema/SemaExpr.cpp", 8302, __extension__ __PRETTY_FUNCTION__
))
8302 "Expected paren or paren list expression")(static_cast <bool> ((isa<ParenListExpr>(E) || isa
<ParenExpr>(E)) && "Expected paren or paren list expression"
) ? void (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\""
, "clang/lib/Sema/SemaExpr.cpp", 8302, __extension__ __PRETTY_FUNCTION__
))
;
8303
8304 Expr **exprs;
8305 unsigned numExprs;
8306 Expr *subExpr;
8307 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8308 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8309 LiteralLParenLoc = PE->getLParenLoc();
8310 LiteralRParenLoc = PE->getRParenLoc();
8311 exprs = PE->getExprs();
8312 numExprs = PE->getNumExprs();
8313 } else { // isa<ParenExpr> by assertion at function entrance
8314 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8315 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8316 subExpr = cast<ParenExpr>(E)->getSubExpr();
8317 exprs = &subExpr;
8318 numExprs = 1;
8319 }
8320
8321 QualType Ty = TInfo->getType();
8322 assert(Ty->isVectorType() && "Expected vector type")(static_cast <bool> (Ty->isVectorType() && "Expected vector type"
) ? void (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\""
, "clang/lib/Sema/SemaExpr.cpp", 8322, __extension__ __PRETTY_FUNCTION__
))
;
8323
8324 SmallVector<Expr *, 8> initExprs;
8325 const VectorType *VTy = Ty->castAs<VectorType>();
8326 unsigned numElems = VTy->getNumElements();
8327
8328 // '(...)' form of vector initialization in AltiVec: the number of
8329 // initializers must be one or must match the size of the vector.
8330 // If a single value is specified in the initializer then it will be
8331 // replicated to all the components of the vector
8332 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
8333 VTy->getElementType()))
8334 return ExprError();
8335 if (ShouldSplatAltivecScalarInCast(VTy)) {
8336 // The number of initializers must be one or must match the size of the
8337 // vector. If a single value is specified in the initializer then it will
8338 // be replicated to all the components of the vector
8339 if (numExprs == 1) {
8340 QualType ElemTy = VTy->getElementType();
8341 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8342 if (Literal.isInvalid())
8343 return ExprError();
8344 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8345 PrepareScalarCast(Literal, ElemTy));
8346 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8347 }
8348 else if (numExprs < numElems) {
8349 Diag(E->getExprLoc(),
8350 diag::err_incorrect_number_of_vector_initializers);
8351 return ExprError();
8352 }
8353 else
8354 initExprs.append(exprs, exprs + numExprs);
8355 }
8356 else {
8357 // For OpenCL, when the number of initializers is a single value,
8358 // it will be replicated to all components of the vector.
8359 if (getLangOpts().OpenCL &&
8360 VTy->getVectorKind() == VectorType::GenericVector &&
8361 numExprs == 1) {
8362 QualType ElemTy = VTy->getElementType();
8363 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8364 if (Literal.isInvalid())
8365 return ExprError();
8366 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8367 PrepareScalarCast(Literal, ElemTy));
8368 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8369 }
8370
8371 initExprs.append(exprs, exprs + numExprs);
8372 }
8373 // FIXME: This means that pretty-printing the final AST will produce curly
8374 // braces instead of the original commas.
8375 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8376 initExprs, LiteralRParenLoc);
8377 initE->setType(Ty);
8378 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8379}
8380
8381/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8382/// the ParenListExpr into a sequence of comma binary operators.
8383ExprResult
8384Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8385 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8386 if (!E)
8387 return OrigExpr;
8388
8389 ExprResult Result(E->getExpr(0));
8390
8391 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8392 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8393 E->getExpr(i));
8394
8395 if (Result.isInvalid()) return ExprError();
8396
8397 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8398}
8399
8400ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8401 SourceLocation R,
8402 MultiExprArg Val) {
8403 return ParenListExpr::Create(Context, L, Val, R);
8404}
8405
8406/// Emit a specialized diagnostic when one expression is a null pointer
8407/// constant and the other is not a pointer. Returns true if a diagnostic is
8408/// emitted.
8409bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8410 SourceLocation QuestionLoc) {
8411 Expr *NullExpr = LHSExpr;
8412 Expr *NonPointerExpr = RHSExpr;
8413 Expr::NullPointerConstantKind NullKind =
8414 NullExpr->isNullPointerConstant(Context,
8415 Expr::NPC_ValueDependentIsNotNull);
8416
8417 if (NullKind == Expr::NPCK_NotNull) {
8418 NullExpr = RHSExpr;
8419 NonPointerExpr = LHSExpr;
8420 NullKind =
8421 NullExpr->isNullPointerConstant(Context,
8422 Expr::NPC_ValueDependentIsNotNull);
8423 }
8424
8425 if (NullKind == Expr::NPCK_NotNull)
8426 return false;
8427
8428 if (NullKind == Expr::NPCK_ZeroExpression)
8429 return false;
8430
8431 if (NullKind == Expr::NPCK_ZeroLiteral) {
8432 // In this case, check to make sure that we got here from a "NULL"
8433 // string in the source code.
8434 NullExpr = NullExpr->IgnoreParenImpCasts();
8435 SourceLocation loc = NullExpr->getExprLoc();
8436 if (!findMacroSpelling(loc, "NULL"))
8437 return false;
8438 }
8439
8440 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8441 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8442 << NonPointerExpr->getType() << DiagType
8443 << NonPointerExpr->getSourceRange();
8444 return true;
8445}
8446
8447/// Return false if the condition expression is valid, true otherwise.
8448static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8449 QualType CondTy = Cond->getType();
8450
8451 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8452 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8453 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8454 << CondTy << Cond->getSourceRange();
8455 return true;
8456 }
8457
8458 // C99 6.5.15p2
8459 if (CondTy->isScalarType()) return false;
8460
8461 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8462 << CondTy << Cond->getSourceRange();
8463 return true;
8464}
8465
8466/// Return false if the NullExpr can be promoted to PointerTy,
8467/// true otherwise.
8468static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8469 QualType PointerTy) {
8470 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8471 !NullExpr.get()->isNullPointerConstant(S.Context,
8472 Expr::NPC_ValueDependentIsNull))
8473 return true;
8474
8475 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8476 return false;
8477}
8478
8479/// Checks compatibility between two pointers and return the resulting
8480/// type.
8481static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8482 ExprResult &RHS,
8483 SourceLocation Loc) {
8484 QualType LHSTy = LHS.get()->getType();
8485 QualType RHSTy = RHS.get()->getType();
8486
8487 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8488 // Two identical pointers types are always compatible.
8489 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8490 }
8491
8492 QualType lhptee, rhptee;
8493
8494 // Get the pointee types.
8495 bool IsBlockPointer = false;
8496 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8497 lhptee = LHSBTy->getPointeeType();
8498 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8499 IsBlockPointer = true;
8500 } else {
8501 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8502 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8503 }
8504
8505 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8506 // differently qualified versions of compatible types, the result type is
8507 // a pointer to an appropriately qualified version of the composite
8508 // type.
8509
8510 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8511 // clause doesn't make sense for our extensions. E.g. address space 2 should
8512 // be incompatible with address space 3: they may live on different devices or
8513 // anything.
8514 Qualifiers lhQual = lhptee.getQualifiers();
8515 Qualifiers rhQual = rhptee.getQualifiers();
8516
8517 LangAS ResultAddrSpace = LangAS::Default;
8518 LangAS LAddrSpace = lhQual.getAddressSpace();
8519 LangAS RAddrSpace = rhQual.getAddressSpace();
8520
8521 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8522 // spaces is disallowed.
8523 if (lhQual.isAddressSpaceSupersetOf(rhQual))
8524 ResultAddrSpace = LAddrSpace;
8525 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8526 ResultAddrSpace = RAddrSpace;
8527 else {
8528 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8529 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8530 << RHS.get()->getSourceRange();
8531 return QualType();
8532 }
8533
8534 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8535 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8536 lhQual.removeCVRQualifiers();
8537 rhQual.removeCVRQualifiers();
8538
8539 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8540 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8541 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8542 // qual types are compatible iff
8543 // * corresponded types are compatible
8544 // * CVR qualifiers are equal
8545 // * address spaces are equal
8546 // Thus for conditional operator we merge CVR and address space unqualified
8547 // pointees and if there is a composite type we return a pointer to it with
8548 // merged qualifiers.
8549 LHSCastKind =
8550 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8551 RHSCastKind =
8552 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8553 lhQual.removeAddressSpace();
8554 rhQual.removeAddressSpace();
8555
8556 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8557 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8558
8559 QualType CompositeTy = S.Context.mergeTypes(
8560 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8561 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8562
8563 if (CompositeTy.isNull()) {
8564 // In this situation, we assume void* type. No especially good
8565 // reason, but this is what gcc does, and we do have to pick
8566 // to get a consistent AST.
8567 QualType incompatTy;
8568 incompatTy = S.Context.getPointerType(
8569 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8570 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8571 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8572
8573 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8574 // for casts between types with incompatible address space qualifiers.
8575 // For the following code the compiler produces casts between global and
8576 // local address spaces of the corresponded innermost pointees:
8577 // local int *global *a;
8578 // global int *global *b;
8579 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8580 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8581 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8582 << RHS.get()->getSourceRange();
8583
8584 return incompatTy;
8585 }
8586
8587 // The pointer types are compatible.
8588 // In case of OpenCL ResultTy should have the address space qualifier
8589 // which is a superset of address spaces of both the 2nd and the 3rd
8590 // operands of the conditional operator.
8591 QualType ResultTy = [&, ResultAddrSpace]() {
8592 if (S.getLangOpts().OpenCL) {
8593 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8594 CompositeQuals.setAddressSpace(ResultAddrSpace);
8595 return S.Context
8596 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8597 .withCVRQualifiers(MergedCVRQual);
8598 }
8599 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8600 }();
8601 if (IsBlockPointer)
8602 ResultTy = S.Context.getBlockPointerType(ResultTy);
8603 else
8604 ResultTy = S.Context.getPointerType(ResultTy);
8605
8606 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8607 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8608 return ResultTy;
8609}
8610
8611/// Return the resulting type when the operands are both block pointers.
8612static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8613 ExprResult &LHS,
8614 ExprResult &RHS,
8615 SourceLocation Loc) {
8616 QualType LHSTy = LHS.get()->getType();
8617 QualType RHSTy = RHS.get()->getType();
8618
8619 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8620 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8621 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8622 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8623 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8624 return destType;
8625 }
8626 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8627 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8628 << RHS.get()->getSourceRange();
8629 return QualType();
8630 }
8631
8632 // We have 2 block pointer types.
8633 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8634}
8635
8636/// Return the resulting type when the operands are both pointers.
8637static QualType
8638checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8639 ExprResult &RHS,
8640 SourceLocation Loc) {
8641 // get the pointer types
8642 QualType LHSTy = LHS.get()->getType();
8643 QualType RHSTy = RHS.get()->getType();
8644
8645 // get the "pointed to" types
8646 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8647 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8648
8649 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8650 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8651 // Figure out necessary qualifiers (C99 6.5.15p6)
8652 QualType destPointee
8653 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8654 QualType destType = S.Context.getPointerType(destPointee);
8655 // Add qualifiers if necessary.
8656 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8657 // Promote to void*.
8658 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8659 return destType;
8660 }
8661 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8662 QualType destPointee
8663 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8664 QualType destType = S.Context.getPointerType(destPointee);
8665 // Add qualifiers if necessary.
8666 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8667 // Promote to void*.
8668 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8669 return destType;
8670 }
8671
8672 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8673}
8674
8675/// Return false if the first expression is not an integer and the second
8676/// expression is not a pointer, true otherwise.
8677static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8678 Expr* PointerExpr, SourceLocation Loc,
8679 bool IsIntFirstExpr) {
8680 if (!PointerExpr->getType()->isPointerType() ||
8681 !Int.get()->getType()->isIntegerType())
8682 return false;
8683
8684 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8685 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8686
8687 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8688 << Expr1->getType() << Expr2->getType()
8689 << Expr1->getSourceRange() << Expr2->getSourceRange();
8690 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8691 CK_IntegralToPointer);
8692 return true;
8693}
8694
8695/// Simple conversion between integer and floating point types.
8696///
8697/// Used when handling the OpenCL conditional operator where the
8698/// condition is a vector while the other operands are scalar.
8699///
8700/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8701/// types are either integer or floating type. Between the two
8702/// operands, the type with the higher rank is defined as the "result
8703/// type". The other operand needs to be promoted to the same type. No
8704/// other type promotion is allowed. We cannot use
8705/// UsualArithmeticConversions() for this purpose, since it always
8706/// promotes promotable types.
8707static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8708 ExprResult &RHS,
8709 SourceLocation QuestionLoc) {
8710 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8711 if (LHS.isInvalid())
8712 return QualType();
8713 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8714 if (RHS.isInvalid())
8715 return QualType();
8716
8717 // For conversion purposes, we ignore any qualifiers.
8718 // For example, "const float" and "float" are equivalent.
8719 QualType LHSType =
8720 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8721 QualType RHSType =
8722 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8723
8724 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8725 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8726 << LHSType << LHS.get()->getSourceRange();
8727 return QualType();
8728 }
8729
8730 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8731 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8732 << RHSType << RHS.get()->getSourceRange();
8733 return QualType();
8734 }
8735
8736 // If both types are identical, no conversion is needed.
8737 if (LHSType == RHSType)
8738 return LHSType;
8739
8740 // Now handle "real" floating types (i.e. float, double, long double).
8741 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8742 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8743 /*IsCompAssign = */ false);
8744
8745 // Finally, we have two differing integer types.
8746 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8747 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8748}
8749
8750/// Convert scalar operands to a vector that matches the
8751/// condition in length.
8752///
8753/// Used when handling the OpenCL conditional operator where the
8754/// condition is a vector while the other operands are scalar.
8755///
8756/// We first compute the "result type" for the scalar operands
8757/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8758/// into a vector of that type where the length matches the condition
8759/// vector type. s6.11.6 requires that the element types of the result
8760/// and the condition must have the same number of bits.
8761static QualType
8762OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8763 QualType CondTy, SourceLocation QuestionLoc) {
8764 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8765 if (ResTy.isNull()) return QualType();
8766
8767 const VectorType *CV = CondTy->getAs<VectorType>();
8768 assert(CV)(static_cast <bool> (CV) ? void (0) : __assert_fail ("CV"
, "clang/lib/Sema/SemaExpr.cpp", 8768, __extension__ __PRETTY_FUNCTION__
))
;
8769
8770 // Determine the vector result type
8771 unsigned NumElements = CV->getNumElements();
8772 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8773
8774 // Ensure that all types have the same number of bits
8775 if (S.Context.getTypeSize(CV->getElementType())
8776 != S.Context.getTypeSize(ResTy)) {
8777 // Since VectorTy is created internally, it does not pretty print
8778 // with an OpenCL name. Instead, we just print a description.
8779 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8780 SmallString<64> Str;
8781 llvm::raw_svector_ostream OS(Str);
8782 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8783 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8784 << CondTy << OS.str();
8785 return QualType();
8786 }
8787
8788 // Convert operands to the vector result type
8789 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8790 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8791
8792 return VectorTy;
8793}
8794
8795/// Return false if this is a valid OpenCL condition vector
8796static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8797 SourceLocation QuestionLoc) {
8798 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8799 // integral type.
8800 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8801 assert(CondTy)(static_cast <bool> (CondTy) ? void (0) : __assert_fail
("CondTy", "clang/lib/Sema/SemaExpr.cpp", 8801, __extension__
__PRETTY_FUNCTION__))
;
8802 QualType EleTy = CondTy->getElementType();
8803 if (EleTy->isIntegerType()) return false;
8804
8805 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8806 << Cond->getType() << Cond->getSourceRange();
8807 return true;
8808}
8809
8810/// Return false if the vector condition type and the vector
8811/// result type are compatible.
8812///
8813/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8814/// number of elements, and their element types have the same number
8815/// of bits.
8816static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8817 SourceLocation QuestionLoc) {
8818 const VectorType *CV = CondTy->getAs<VectorType>();
8819 const VectorType *RV = VecResTy->getAs<VectorType>();
8820 assert(CV && RV)(static_cast <bool> (CV && RV) ? void (0) : __assert_fail
("CV && RV", "clang/lib/Sema/SemaExpr.cpp", 8820, __extension__
__PRETTY_FUNCTION__))
;
8821
8822 if (CV->getNumElements() != RV->getNumElements()) {
8823 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8824 << CondTy << VecResTy;
8825 return true;
8826 }
8827
8828 QualType CVE = CV->getElementType();
8829 QualType RVE = RV->getElementType();
8830
8831 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8832 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8833 << CondTy << VecResTy;
8834 return true;
8835 }
8836
8837 return false;
8838}
8839
8840/// Return the resulting type for the conditional operator in
8841/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8842/// s6.3.i) when the condition is a vector type.
8843static QualType
8844OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8845 ExprResult &LHS, ExprResult &RHS,
8846 SourceLocation QuestionLoc) {
8847 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8848 if (Cond.isInvalid())
8849 return QualType();
8850 QualType CondTy = Cond.get()->getType();
8851
8852 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8853 return QualType();
8854
8855 // If either operand is a vector then find the vector type of the
8856 // result as specified in OpenCL v1.1 s6.3.i.
8857 if (LHS.get()->getType()->isVectorType() ||
8858 RHS.get()->getType()->isVectorType()) {
8859 bool IsBoolVecLang =
8860 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8861 QualType VecResTy =
8862 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8863 /*isCompAssign*/ false,
8864 /*AllowBothBool*/ true,
8865 /*AllowBoolConversions*/ false,
8866 /*AllowBooleanOperation*/ IsBoolVecLang,
8867 /*ReportInvalid*/ true);
8868 if (VecResTy.isNull())
8869 return QualType();
8870 // The result type must match the condition type as specified in
8871 // OpenCL v1.1 s6.11.6.
8872 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8873 return QualType();
8874 return VecResTy;
8875 }
8876
8877 // Both operands are scalar.
8878 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8879}
8880
8881/// Return true if the Expr is block type
8882static bool checkBlockType(Sema &S, const Expr *E) {
8883 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8884 QualType Ty = CE->getCallee()->getType();
8885 if (Ty->isBlockPointerType()) {
8886 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8887 return true;
8888 }
8889 }
8890 return false;
8891}
8892
8893/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8894/// In that case, LHS = cond.
8895/// C99 6.5.15
8896QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8897 ExprResult &RHS, ExprValueKind &VK,
8898 ExprObjectKind &OK,
8899 SourceLocation QuestionLoc) {
8900
8901 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8902 if (!LHSResult.isUsable()) return QualType();
8903 LHS = LHSResult;
8904
8905 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8906 if (!RHSResult.isUsable()) return QualType();
8907 RHS = RHSResult;
8908
8909 // C++ is sufficiently different to merit its own checker.
8910 if (getLangOpts().CPlusPlus)
8911 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8912
8913 VK = VK_PRValue;
8914 OK = OK_Ordinary;
8915
8916 if (Context.isDependenceAllowed() &&
8917 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8918 RHS.get()->isTypeDependent())) {
8919 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 8919, __extension__ __PRETTY_FUNCTION__))
;
8920 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||(static_cast <bool> ((Cond.get()->containsErrors() ||
LHS.get()->containsErrors() || RHS.get()->containsErrors
()) && "should only occur in error-recovery path.") ?
void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 8922, __extension__ __PRETTY_FUNCTION__
))
8921 RHS.get()->containsErrors()) &&(static_cast <bool> ((Cond.get()->containsErrors() ||
LHS.get()->containsErrors() || RHS.get()->containsErrors
()) && "should only occur in error-recovery path.") ?
void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 8922, __extension__ __PRETTY_FUNCTION__
))
8922 "should only occur in error-recovery path.")(static_cast <bool> ((Cond.get()->containsErrors() ||
LHS.get()->containsErrors() || RHS.get()->containsErrors
()) && "should only occur in error-recovery path.") ?
void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 8922, __extension__ __PRETTY_FUNCTION__
))
;
8923 return Context.DependentTy;
8924 }
8925
8926 // The OpenCL operator with a vector condition is sufficiently
8927 // different to merit its own checker.
8928 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8929 Cond.get()->getType()->isExtVectorType())
8930 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8931
8932 // First, check the condition.
8933 Cond = UsualUnaryConversions(Cond.get());
8934 if (Cond.isInvalid())
8935 return QualType();
8936 if (checkCondition(*this, Cond.get(), QuestionLoc))
8937 return QualType();
8938
8939 // Now check the two expressions.
8940 if (LHS.get()->getType()->isVectorType() ||
8941 RHS.get()->getType()->isVectorType())
8942 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8943 /*AllowBothBool*/ true,
8944 /*AllowBoolConversions*/ false,
8945 /*AllowBooleanOperation*/ false,
8946 /*ReportInvalid*/ true);
8947
8948 QualType ResTy =
8949 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8950 if (LHS.isInvalid() || RHS.isInvalid())
8951 return QualType();
8952
8953 QualType LHSTy = LHS.get()->getType();
8954 QualType RHSTy = RHS.get()->getType();
8955
8956 // Diagnose attempts to convert between __ibm128, __float128 and long double
8957 // where such conversions currently can't be handled.
8958 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8959 Diag(QuestionLoc,
8960 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8961 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8962 return QualType();
8963 }
8964
8965 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8966 // selection operator (?:).
8967 if (getLangOpts().OpenCL &&
8968 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8969 return QualType();
8970 }
8971
8972 // If both operands have arithmetic type, do the usual arithmetic conversions
8973 // to find a common type: C99 6.5.15p3,5.
8974 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8975 // Disallow invalid arithmetic conversions, such as those between bit-
8976 // precise integers types of different sizes, or between a bit-precise
8977 // integer and another type.
8978 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8979 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8980 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8981 << RHS.get()->getSourceRange();
8982 return QualType();
8983 }
8984
8985 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8986 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8987
8988 return ResTy;
8989 }
8990
8991 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8992 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8993 return Context.getCommonSugaredType(LHSTy, RHSTy);
8994 }
8995
8996 // If both operands are the same structure or union type, the result is that
8997 // type.
8998 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8999 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
9000 if (LHSRT->getDecl() == RHSRT->getDecl())
9001 // "If both the operands have structure or union type, the result has
9002 // that type." This implies that CV qualifiers are dropped.
9003 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
9004 RHSTy.getUnqualifiedType());
9005 // FIXME: Type of conditional expression must be complete in C mode.
9006 }
9007
9008 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9009 // The following || allows only one side to be void (a GCC-ism).
9010 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9011 QualType ResTy;
9012 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9013 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
9014 } else if (RHSTy->isVoidType()) {
9015 ResTy = RHSTy;
9016 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9017 << RHS.get()->getSourceRange();
9018 } else {
9019 ResTy = LHSTy;
9020 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9021 << LHS.get()->getSourceRange();
9022 }
9023 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
9024 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
9025 return ResTy;
9026 }
9027
9028 // C2x 6.5.15p7:
9029 // ... if both the second and third operands have nullptr_t type, the
9030 // result also has that type.
9031 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
9032 return ResTy;
9033
9034 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9035 // the type of the other operand."
9036 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
9037 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
9038
9039 // All objective-c pointer type analysis is done here.
9040 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
9041 QuestionLoc);
9042 if (LHS.isInvalid() || RHS.isInvalid())
9043 return QualType();
9044 if (!compositeType.isNull())
9045 return compositeType;
9046
9047
9048 // Handle block pointer types.
9049 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9050 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9051 QuestionLoc);
9052
9053 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9054 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9055 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9056 QuestionLoc);
9057
9058 // GCC compatibility: soften pointer/integer mismatch. Note that
9059 // null pointers have been filtered out by this point.
9060 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9061 /*IsIntFirstExpr=*/true))
9062 return RHSTy;
9063 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9064 /*IsIntFirstExpr=*/false))
9065 return LHSTy;
9066
9067 // Allow ?: operations in which both operands have the same
9068 // built-in sizeless type.
9069 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
9070 return Context.getCommonSugaredType(LHSTy, RHSTy);
9071
9072 // Emit a better diagnostic if one of the expressions is a null pointer
9073 // constant and the other is not a pointer type. In this case, the user most
9074 // likely forgot to take the address of the other expression.
9075 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9076 return QualType();
9077
9078 // Otherwise, the operands are not compatible.
9079 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9080 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9081 << RHS.get()->getSourceRange();
9082 return QualType();
9083}
9084
9085/// FindCompositeObjCPointerType - Helper method to find composite type of
9086/// two objective-c pointer types of the two input expressions.
9087QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9088 SourceLocation QuestionLoc) {
9089 QualType LHSTy = LHS.get()->getType();
9090 QualType RHSTy = RHS.get()->getType();
9091
9092 // Handle things like Class and struct objc_class*. Here we case the result
9093 // to the pseudo-builtin, because that will be implicitly cast back to the
9094 // redefinition type if an attempt is made to access its fields.
9095 if (LHSTy->isObjCClassType() &&
9096 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
9097 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9098 return LHSTy;
9099 }
9100 if (RHSTy->isObjCClassType() &&
9101 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
9102 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9103 return RHSTy;
9104 }
9105 // And the same for struct objc_object* / id
9106 if (LHSTy->isObjCIdType() &&
9107 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
9108 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9109 return LHSTy;
9110 }
9111 if (RHSTy->isObjCIdType() &&
9112 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
9113 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9114 return RHSTy;
9115 }
9116 // And the same for struct objc_selector* / SEL
9117 if (Context.isObjCSelType(LHSTy) &&
9118 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
9119 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
9120 return LHSTy;
9121 }
9122 if (Context.isObjCSelType(RHSTy) &&
9123 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
9124 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
9125 return RHSTy;
9126 }
9127 // Check constraints for Objective-C object pointers types.
9128 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
9129
9130 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
9131 // Two identical object pointer types are always compatible.
9132 return LHSTy;
9133 }
9134 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
9135 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
9136 QualType compositeType = LHSTy;
9137
9138 // If both operands are interfaces and either operand can be
9139 // assigned to the other, use that type as the composite
9140 // type. This allows
9141 // xxx ? (A*) a : (B*) b
9142 // where B is a subclass of A.
9143 //
9144 // Additionally, as for assignment, if either type is 'id'
9145 // allow silent coercion. Finally, if the types are
9146 // incompatible then make sure to use 'id' as the composite
9147 // type so the result is acceptable for sending messages to.
9148
9149 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
9150 // It could return the composite type.
9151 if (!(compositeType =
9152 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
9153 // Nothing more to do.
9154 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
9155 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
9156 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
9157 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
9158 } else if ((LHSOPT->isObjCQualifiedIdType() ||
9159 RHSOPT->isObjCQualifiedIdType()) &&
9160 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
9161 true)) {
9162 // Need to handle "id<xx>" explicitly.
9163 // GCC allows qualified id and any Objective-C type to devolve to
9164 // id. Currently localizing to here until clear this should be
9165 // part of ObjCQualifiedIdTypesAreCompatible.
9166 compositeType = Context.getObjCIdType();
9167 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
9168 compositeType = Context.getObjCIdType();
9169 } else {
9170 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
9171 << LHSTy << RHSTy
9172 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9173 QualType incompatTy = Context.getObjCIdType();
9174 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
9175 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
9176 return incompatTy;
9177 }
9178 // The object pointer types are compatible.
9179 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
9180 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
9181 return compositeType;
9182 }
9183 // Check Objective-C object pointer types and 'void *'
9184 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
9185 if (getLangOpts().ObjCAutoRefCount) {
9186 // ARC forbids the implicit conversion of object pointers to 'void *',
9187 // so these types are not compatible.
9188 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9189 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9190 LHS = RHS = true;
9191 return QualType();
9192 }
9193 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
9194 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9195 QualType destPointee
9196 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
9197 QualType destType = Context.getPointerType(destPointee);
9198 // Add qualifiers if necessary.
9199 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
9200 // Promote to void*.
9201 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
9202 return destType;
9203 }
9204 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
9205 if (getLangOpts().ObjCAutoRefCount) {
9206 // ARC forbids the implicit conversion of object pointers to 'void *',
9207 // so these types are not compatible.
9208 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9209 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9210 LHS = RHS = true;
9211 return QualType();
9212 }
9213 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9214 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
9215 QualType destPointee
9216 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
9217 QualType destType = Context.getPointerType(destPointee);
9218 // Add qualifiers if necessary.
9219 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
9220 // Promote to void*.
9221 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
9222 return destType;
9223 }
9224 return QualType();
9225}
9226
9227/// SuggestParentheses - Emit a note with a fixit hint that wraps
9228/// ParenRange in parentheses.
9229static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9230 const PartialDiagnostic &Note,
9231 SourceRange ParenRange) {
9232 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9233 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9234 EndLoc.isValid()) {
9235 Self.Diag(Loc, Note)
9236 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9237 << FixItHint::CreateInsertion(EndLoc, ")");
9238 } else {
9239 // We can't display the parentheses, so just show the bare note.
9240 Self.Diag(Loc, Note) << ParenRange;
9241 }
9242}
9243
9244static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9245 return BinaryOperator::isAdditiveOp(Opc) ||
9246 BinaryOperator::isMultiplicativeOp(Opc) ||
9247 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9248 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9249 // not any of the logical operators. Bitwise-xor is commonly used as a
9250 // logical-xor because there is no logical-xor operator. The logical
9251 // operators, including uses of xor, have a high false positive rate for
9252 // precedence warnings.
9253}
9254
9255/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9256/// expression, either using a built-in or overloaded operator,
9257/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9258/// expression.
9259static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
9260 Expr **RHSExprs) {
9261 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9262 E = E->IgnoreImpCasts();
9263 E = E->IgnoreConversionOperatorSingleStep();
9264 E = E->IgnoreImpCasts();
9265 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9266 E = MTE->getSubExpr();
9267 E = E->IgnoreImpCasts();
9268 }
9269
9270 // Built-in binary operator.
9271 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
9272 if (IsArithmeticOp(OP->getOpcode())) {
9273 *Opcode = OP->getOpcode();
9274 *RHSExprs = OP->getRHS();
9275 return true;
9276 }
9277 }
9278
9279 // Overloaded operator.
9280 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9281 if (Call->getNumArgs() != 2)
9282 return false;
9283
9284 // Make sure this is really a binary operator that is safe to pass into
9285 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9286 OverloadedOperatorKind OO = Call->getOperator();
9287 if (OO < OO_Plus || OO > OO_Arrow ||
9288 OO == OO_PlusPlus || OO == OO_MinusMinus)
9289 return false;
9290
9291 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9292 if (IsArithmeticOp(OpKind)) {
9293 *Opcode = OpKind;
9294 *RHSExprs = Call->getArg(1);
9295 return true;
9296 }
9297 }
9298
9299 return false;
9300}
9301
9302/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9303/// or is a logical expression such as (x==y) which has int type, but is
9304/// commonly interpreted as boolean.
9305static bool ExprLooksBoolean(Expr *E) {
9306 E = E->IgnoreParenImpCasts();
9307
9308 if (E->getType()->isBooleanType())
9309 return true;
9310 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
9311 return OP->isComparisonOp() || OP->isLogicalOp();
9312 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
9313 return OP->getOpcode() == UO_LNot;
9314 if (E->getType()->isPointerType())
9315 return true;
9316 // FIXME: What about overloaded operator calls returning "unspecified boolean
9317 // type"s (commonly pointer-to-members)?
9318
9319 return false;
9320}
9321
9322/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9323/// and binary operator are mixed in a way that suggests the programmer assumed
9324/// the conditional operator has higher precedence, for example:
9325/// "int x = a + someBinaryCondition ? 1 : 2".
9326static void DiagnoseConditionalPrecedence(Sema &Self,
9327 SourceLocation OpLoc,
9328 Expr *Condition,
9329 Expr *LHSExpr,
9330 Expr *RHSExpr) {
9331 BinaryOperatorKind CondOpcode;
9332 Expr *CondRHS;
9333
9334 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9335 return;
9336 if (!ExprLooksBoolean(CondRHS))
9337 return;
9338
9339 // The condition is an arithmetic binary expression, with a right-
9340 // hand side that looks boolean, so warn.
9341
9342 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9343 ? diag::warn_precedence_bitwise_conditional
9344 : diag::warn_precedence_conditional;
9345
9346 Self.Diag(OpLoc, DiagID)
9347 << Condition->getSourceRange()
9348 << BinaryOperator::getOpcodeStr(CondOpcode);
9349
9350 SuggestParentheses(
9351 Self, OpLoc,
9352 Self.PDiag(diag::note_precedence_silence)
9353 << BinaryOperator::getOpcodeStr(CondOpcode),
9354 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9355
9356 SuggestParentheses(Self, OpLoc,
9357 Self.PDiag(diag::note_precedence_conditional_first),
9358 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9359}
9360
9361/// Compute the nullability of a conditional expression.
9362static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9363 QualType LHSTy, QualType RHSTy,
9364 ASTContext &Ctx) {
9365 if (!ResTy->isAnyPointerType())
9366 return ResTy;
9367
9368 auto GetNullability = [](QualType Ty) {
9369 std::optional<NullabilityKind> Kind = Ty->getNullability();
9370 if (Kind) {
9371 // For our purposes, treat _Nullable_result as _Nullable.
9372 if (*Kind == NullabilityKind::NullableResult)
9373 return NullabilityKind::Nullable;
9374 return *Kind;
9375 }
9376 return NullabilityKind::Unspecified;
9377 };
9378
9379 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9380 NullabilityKind MergedKind;
9381
9382 // Compute nullability of a binary conditional expression.
9383 if (IsBin) {
9384 if (LHSKind == NullabilityKind::NonNull)
9385 MergedKind = NullabilityKind::NonNull;
9386 else
9387 MergedKind = RHSKind;
9388 // Compute nullability of a normal conditional expression.
9389 } else {
9390 if (LHSKind == NullabilityKind::Nullable ||
9391 RHSKind == NullabilityKind::Nullable)
9392 MergedKind = NullabilityKind::Nullable;
9393 else if (LHSKind == NullabilityKind::NonNull)
9394 MergedKind = RHSKind;
9395 else if (RHSKind == NullabilityKind::NonNull)
9396 MergedKind = LHSKind;
9397 else
9398 MergedKind = NullabilityKind::Unspecified;
9399 }
9400
9401 // Return if ResTy already has the correct nullability.
9402 if (GetNullability(ResTy) == MergedKind)
9403 return ResTy;
9404
9405 // Strip all nullability from ResTy.
9406 while (ResTy->getNullability())
9407 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9408
9409 // Create a new AttributedType with the new nullability kind.
9410 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9411 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9412}
9413
9414/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9415/// in the case of a the GNU conditional expr extension.
9416ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9417 SourceLocation ColonLoc,
9418 Expr *CondExpr, Expr *LHSExpr,
9419 Expr *RHSExpr) {
9420 if (!Context.isDependenceAllowed()) {
9421 // C cannot handle TypoExpr nodes in the condition because it
9422 // doesn't handle dependent types properly, so make sure any TypoExprs have
9423 // been dealt with before checking the operands.
9424 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9425 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9426 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9427
9428 if (!CondResult.isUsable())
9429 return ExprError();
9430
9431 if (LHSExpr) {
9432 if (!LHSResult.isUsable())
9433 return ExprError();
9434 }
9435
9436 if (!RHSResult.isUsable())
9437 return ExprError();
9438
9439 CondExpr = CondResult.get();
9440 LHSExpr = LHSResult.get();
9441 RHSExpr = RHSResult.get();
9442 }
9443
9444 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9445 // was the condition.
9446 OpaqueValueExpr *opaqueValue = nullptr;
9447 Expr *commonExpr = nullptr;
9448 if (!LHSExpr) {
9449 commonExpr = CondExpr;
9450 // Lower out placeholder types first. This is important so that we don't
9451 // try to capture a placeholder. This happens in few cases in C++; such
9452 // as Objective-C++'s dictionary subscripting syntax.
9453 if (commonExpr->hasPlaceholderType()) {
9454 ExprResult result = CheckPlaceholderExpr(commonExpr);
9455 if (!result.isUsable()) return ExprError();
9456 commonExpr = result.get();
9457 }
9458 // We usually want to apply unary conversions *before* saving, except
9459 // in the special case of a C++ l-value conditional.
9460 if (!(getLangOpts().CPlusPlus
9461 && !commonExpr->isTypeDependent()
9462 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9463 && commonExpr->isGLValue()
9464 && commonExpr->isOrdinaryOrBitFieldObject()
9465 && RHSExpr->isOrdinaryOrBitFieldObject()
9466 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9467 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9468 if (commonRes.isInvalid())
9469 return ExprError();
9470 commonExpr = commonRes.get();
9471 }
9472
9473 // If the common expression is a class or array prvalue, materialize it
9474 // so that we can safely refer to it multiple times.
9475 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9476 commonExpr->getType()->isArrayType())) {
9477 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9478 if (MatExpr.isInvalid())
9479 return ExprError();
9480 commonExpr = MatExpr.get();
9481 }
9482
9483 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9484 commonExpr->getType(),
9485 commonExpr->getValueKind(),
9486 commonExpr->getObjectKind(),
9487 commonExpr);
9488 LHSExpr = CondExpr = opaqueValue;
9489 }
9490
9491 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9492 ExprValueKind VK = VK_PRValue;
9493 ExprObjectKind OK = OK_Ordinary;
9494 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9495 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9496 VK, OK, QuestionLoc);
9497 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9498 RHS.isInvalid())
9499 return ExprError();
9500
9501 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9502 RHS.get());
9503
9504 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9505
9506 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9507 Context);
9508
9509 if (!commonExpr)
9510 return new (Context)
9511 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9512 RHS.get(), result, VK, OK);
9513
9514 return new (Context) BinaryConditionalOperator(
9515 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9516 ColonLoc, result, VK, OK);
9517}
9518
9519// Check if we have a conversion between incompatible cmse function pointer
9520// types, that is, a conversion between a function pointer with the
9521// cmse_nonsecure_call attribute and one without.
9522static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9523 QualType ToType) {
9524 if (const auto *ToFn =
9525 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9526 if (const auto *FromFn =
9527 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9528 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9529 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9530
9531 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9532 }
9533 }
9534 return false;
9535}
9536
9537// checkPointerTypesForAssignment - This is a very tricky routine (despite
9538// being closely modeled after the C99 spec:-). The odd characteristic of this
9539// routine is it effectively iqnores the qualifiers on the top level pointee.
9540// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9541// FIXME: add a couple examples in this comment.
9542static Sema::AssignConvertType
9543checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType,
9544 SourceLocation Loc) {
9545 assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!"
) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\""
, "clang/lib/Sema/SemaExpr.cpp", 9545, __extension__ __PRETTY_FUNCTION__
))
;
9546 assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!"
) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\""
, "clang/lib/Sema/SemaExpr.cpp", 9546, __extension__ __PRETTY_FUNCTION__
))
;
9547
9548 // get the "pointed to" type (ignoring qualifiers at the top level)
9549 const Type *lhptee, *rhptee;
9550 Qualifiers lhq, rhq;
9551 std::tie(lhptee, lhq) =
9552 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9553 std::tie(rhptee, rhq) =
9554 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9555
9556 Sema::AssignConvertType ConvTy = Sema::Compatible;
9557
9558 // C99 6.5.16.1p1: This following citation is common to constraints
9559 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9560 // qualifiers of the type *pointed to* by the right;
9561
9562 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9563 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9564 lhq.compatiblyIncludesObjCLifetime(rhq)) {
9565 // Ignore lifetime for further calculation.
9566 lhq.removeObjCLifetime();
9567 rhq.removeObjCLifetime();
9568 }
9569
9570 if (!lhq.compatiblyIncludes(rhq)) {
9571 // Treat address-space mismatches as fatal.
9572 if (!lhq.isAddressSpaceSupersetOf(rhq))
9573 return Sema::IncompatiblePointerDiscardsQualifiers;
9574
9575 // It's okay to add or remove GC or lifetime qualifiers when converting to
9576 // and from void*.
9577 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9578 .compatiblyIncludes(
9579 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9580 && (lhptee->isVoidType() || rhptee->isVoidType()))
9581 ; // keep old
9582
9583 // Treat lifetime mismatches as fatal.
9584 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9585 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9586
9587 // For GCC/MS compatibility, other qualifier mismatches are treated
9588 // as still compatible in C.
9589 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9590 }
9591
9592 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9593 // incomplete type and the other is a pointer to a qualified or unqualified
9594 // version of void...
9595 if (lhptee->isVoidType()) {
9596 if (rhptee->isIncompleteOrObjectType())
9597 return ConvTy;
9598
9599 // As an extension, we allow cast to/from void* to function pointer.
9600 assert(rhptee->isFunctionType())(static_cast <bool> (rhptee->isFunctionType()) ? void
(0) : __assert_fail ("rhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp"
, 9600, __extension__ __PRETTY_FUNCTION__))
;
9601 return Sema::FunctionVoidPointer;
9602 }
9603
9604 if (rhptee->isVoidType()) {
9605 if (lhptee->isIncompleteOrObjectType())
9606 return ConvTy;
9607
9608 // As an extension, we allow cast to/from void* to function pointer.
9609 assert(lhptee->isFunctionType())(static_cast <bool> (lhptee->isFunctionType()) ? void
(0) : __assert_fail ("lhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp"
, 9609, __extension__ __PRETTY_FUNCTION__))
;
9610 return Sema::FunctionVoidPointer;
9611 }
9612
9613 if (!S.Diags.isIgnored(
9614 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9615 Loc) &&
9616 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9617 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9618 return Sema::IncompatibleFunctionPointerStrict;
9619
9620 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9621 // unqualified versions of compatible types, ...
9622 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9623 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9624 // Check if the pointee types are compatible ignoring the sign.
9625 // We explicitly check for char so that we catch "char" vs
9626 // "unsigned char" on systems where "char" is unsigned.
9627 if (lhptee->isCharType())
9628 ltrans = S.Context.UnsignedCharTy;
9629 else if (lhptee->hasSignedIntegerRepresentation())
9630 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9631
9632 if (rhptee->isCharType())
9633 rtrans = S.Context.UnsignedCharTy;
9634 else if (rhptee->hasSignedIntegerRepresentation())
9635 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9636
9637 if (ltrans == rtrans) {
9638 // Types are compatible ignoring the sign. Qualifier incompatibility
9639 // takes priority over sign incompatibility because the sign
9640 // warning can be disabled.
9641 if (ConvTy != Sema::Compatible)
9642 return ConvTy;
9643
9644 return Sema::IncompatiblePointerSign;
9645 }
9646
9647 // If we are a multi-level pointer, it's possible that our issue is simply
9648 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9649 // the eventual target type is the same and the pointers have the same
9650 // level of indirection, this must be the issue.
9651 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9652 do {
9653 std::tie(lhptee, lhq) =
9654 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9655 std::tie(rhptee, rhq) =
9656 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9657
9658 // Inconsistent address spaces at this point is invalid, even if the
9659 // address spaces would be compatible.
9660 // FIXME: This doesn't catch address space mismatches for pointers of
9661 // different nesting levels, like:
9662 // __local int *** a;
9663 // int ** b = a;
9664 // It's not clear how to actually determine when such pointers are
9665 // invalidly incompatible.
9666 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9667 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9668
9669 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9670
9671 if (lhptee == rhptee)
9672 return Sema::IncompatibleNestedPointerQualifiers;
9673 }
9674
9675 // General pointer incompatibility takes priority over qualifiers.
9676 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9677 return Sema::IncompatibleFunctionPointer;
9678 return Sema::IncompatiblePointer;
9679 }
9680 if (!S.getLangOpts().CPlusPlus &&
9681 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9682 return Sema::IncompatibleFunctionPointer;
9683 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9684 return Sema::IncompatibleFunctionPointer;
9685 return ConvTy;
9686}
9687
9688/// checkBlockPointerTypesForAssignment - This routine determines whether two
9689/// block pointer types are compatible or whether a block and normal pointer
9690/// are compatible. It is more restrict than comparing two function pointer
9691// types.
9692static Sema::AssignConvertType
9693checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9694 QualType RHSType) {
9695 assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!"
) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\""
, "clang/lib/Sema/SemaExpr.cpp", 9695, __extension__ __PRETTY_FUNCTION__
))
;
9696 assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!"
) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\""
, "clang/lib/Sema/SemaExpr.cpp", 9696, __extension__ __PRETTY_FUNCTION__
))
;
9697
9698 QualType lhptee, rhptee;
9699
9700 // get the "pointed to" type (ignoring qualifiers at the top level)
9701 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9702 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9703
9704 // In C++, the types have to match exactly.
9705 if (S.getLangOpts().CPlusPlus)
9706 return Sema::IncompatibleBlockPointer;
9707
9708 Sema::AssignConvertType ConvTy = Sema::Compatible;
9709
9710 // For blocks we enforce that qualifiers are identical.
9711 Qualifiers LQuals = lhptee.getLocalQualifiers();
9712 Qualifiers RQuals = rhptee.getLocalQualifiers();
9713 if (S.getLangOpts().OpenCL) {
9714 LQuals.removeAddressSpace();
9715 RQuals.removeAddressSpace();
9716 }
9717 if (LQuals != RQuals)
9718 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9719
9720 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9721 // assignment.
9722 // The current behavior is similar to C++ lambdas. A block might be
9723 // assigned to a variable iff its return type and parameters are compatible
9724 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9725 // an assignment. Presumably it should behave in way that a function pointer
9726 // assignment does in C, so for each parameter and return type:
9727 // * CVR and address space of LHS should be a superset of CVR and address
9728 // space of RHS.
9729 // * unqualified types should be compatible.
9730 if (S.getLangOpts().OpenCL) {
9731 if (!S.Context.typesAreBlockPointerCompatible(
9732 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9733 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9734 return Sema::IncompatibleBlockPointer;
9735 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9736 return Sema::IncompatibleBlockPointer;
9737
9738 return ConvTy;
9739}
9740
9741/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9742/// for assignment compatibility.
9743static Sema::AssignConvertType
9744checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9745 QualType RHSType) {
9746 assert(LHSType.isCanonical() && "LHS was not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS was not canonicalized!"
) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS was not canonicalized!\""
, "clang/lib/Sema/SemaExpr.cpp", 9746, __extension__ __PRETTY_FUNCTION__
))
;
9747 assert(RHSType.isCanonical() && "RHS was not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS was not canonicalized!"
) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS was not canonicalized!\""
, "clang/lib/Sema/SemaExpr.cpp", 9747, __extension__ __PRETTY_FUNCTION__
))
;
9748
9749 if (LHSType->isObjCBuiltinType()) {
9750 // Class is not compatible with ObjC object pointers.
9751 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9752 !RHSType->isObjCQualifiedClassType())
9753 return Sema::IncompatiblePointer;
9754 return Sema::Compatible;
9755 }
9756 if (RHSType->isObjCBuiltinType()) {
9757 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9758 !LHSType->isObjCQualifiedClassType())
9759 return Sema::IncompatiblePointer;
9760 return Sema::Compatible;
9761 }
9762 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9763 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9764
9765 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9766 // make an exception for id<P>
9767 !LHSType->isObjCQualifiedIdType())
9768 return Sema::CompatiblePointerDiscardsQualifiers;
9769
9770 if (S.Context.typesAreCompatible(LHSType, RHSType))
9771 return Sema::Compatible;
9772 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9773 return Sema::IncompatibleObjCQualifiedId;
9774 return Sema::IncompatiblePointer;
9775}
9776
9777Sema::AssignConvertType
9778Sema::CheckAssignmentConstraints(SourceLocation Loc,
9779 QualType LHSType, QualType RHSType) {
9780 // Fake up an opaque expression. We don't actually care about what
9781 // cast operations are required, so if CheckAssignmentConstraints
9782 // adds casts to this they'll be wasted, but fortunately that doesn't
9783 // usually happen on valid code.
9784 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9785 ExprResult RHSPtr = &RHSExpr;
9786 CastKind K;
9787
9788 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9789}
9790
9791/// This helper function returns true if QT is a vector type that has element
9792/// type ElementType.
9793static bool isVector(QualType QT, QualType ElementType) {
9794 if (const VectorType *VT = QT->getAs<VectorType>())
9795 return VT->getElementType().getCanonicalType() == ElementType;
9796 return false;
9797}
9798
9799/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9800/// has code to accommodate several GCC extensions when type checking
9801/// pointers. Here are some objectionable examples that GCC considers warnings:
9802///
9803/// int a, *pint;
9804/// short *pshort;
9805/// struct foo *pfoo;
9806///
9807/// pint = pshort; // warning: assignment from incompatible pointer type
9808/// a = pint; // warning: assignment makes integer from pointer without a cast
9809/// pint = a; // warning: assignment makes pointer from integer without a cast
9810/// pint = pfoo; // warning: assignment from incompatible pointer type
9811///
9812/// As a result, the code for dealing with pointers is more complex than the
9813/// C99 spec dictates.
9814///
9815/// Sets 'Kind' for any result kind except Incompatible.
9816Sema::AssignConvertType
9817Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9818 CastKind &Kind, bool ConvertRHS) {
9819 QualType RHSType = RHS.get()->getType();
9820 QualType OrigLHSType = LHSType;
9821
9822 // Get canonical types. We're not formatting these types, just comparing
9823 // them.
9824 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9825 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9826
9827 // Common case: no conversion required.
9828 if (LHSType == RHSType) {
9829 Kind = CK_NoOp;
9830 return Compatible;
9831 }
9832
9833 // If the LHS has an __auto_type, there are no additional type constraints
9834 // to be worried about.
9835 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9836 if (AT->isGNUAutoType()) {
9837 Kind = CK_NoOp;
9838 return Compatible;
9839 }
9840 }
9841
9842 // If we have an atomic type, try a non-atomic assignment, then just add an
9843 // atomic qualification step.
9844 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9845 Sema::AssignConvertType result =
9846 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9847 if (result != Compatible)
9848 return result;
9849 if (Kind != CK_NoOp && ConvertRHS)
9850 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9851 Kind = CK_NonAtomicToAtomic;
9852 return Compatible;
9853 }
9854
9855 // If the left-hand side is a reference type, then we are in a
9856 // (rare!) case where we've allowed the use of references in C,
9857 // e.g., as a parameter type in a built-in function. In this case,
9858 // just make sure that the type referenced is compatible with the
9859 // right-hand side type. The caller is responsible for adjusting
9860 // LHSType so that the resulting expression does not have reference
9861 // type.
9862 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9863 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9864 Kind = CK_LValueBitCast;
9865 return Compatible;
9866 }
9867 return Incompatible;
9868 }
9869
9870 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9871 // to the same ExtVector type.
9872 if (LHSType->isExtVectorType()) {
9873 if (RHSType->isExtVectorType())
9874 return Incompatible;
9875 if (RHSType->isArithmeticType()) {
9876 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9877 if (ConvertRHS)
9878 RHS = prepareVectorSplat(LHSType, RHS.get());
9879 Kind = CK_VectorSplat;
9880 return Compatible;
9881 }
9882 }
9883
9884 // Conversions to or from vector type.
9885 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9886 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9887 // Allow assignments of an AltiVec vector type to an equivalent GCC
9888 // vector type and vice versa
9889 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9890 Kind = CK_BitCast;
9891 return Compatible;
9892 }
9893
9894 // If we are allowing lax vector conversions, and LHS and RHS are both
9895 // vectors, the total size only needs to be the same. This is a bitcast;
9896 // no bits are changed but the result type is different.
9897 if (isLaxVectorConversion(RHSType, LHSType)) {
9898 // The default for lax vector conversions with Altivec vectors will
9899 // change, so if we are converting between vector types where
9900 // at least one is an Altivec vector, emit a warning.
9901 if (Context.getTargetInfo().getTriple().isPPC() &&
9902 anyAltivecTypes(RHSType, LHSType) &&
9903 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9904 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9905 << RHSType << LHSType;
9906 Kind = CK_BitCast;
9907 return IncompatibleVectors;
9908 }
9909 }
9910
9911 // When the RHS comes from another lax conversion (e.g. binops between
9912 // scalars and vectors) the result is canonicalized as a vector. When the
9913 // LHS is also a vector, the lax is allowed by the condition above. Handle
9914 // the case where LHS is a scalar.
9915 if (LHSType->isScalarType()) {
9916 const VectorType *VecType = RHSType->getAs<VectorType>();
9917 if (VecType && VecType->getNumElements() == 1 &&
9918 isLaxVectorConversion(RHSType, LHSType)) {
9919 if (Context.getTargetInfo().getTriple().isPPC() &&
9920 (VecType->getVectorKind() == VectorType::AltiVecVector ||
9921 VecType->getVectorKind() == VectorType::AltiVecBool ||
9922 VecType->getVectorKind() == VectorType::AltiVecPixel))
9923 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9924 << RHSType << LHSType;
9925 ExprResult *VecExpr = &RHS;
9926 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9927 Kind = CK_BitCast;
9928 return Compatible;
9929 }
9930 }
9931
9932 // Allow assignments between fixed-length and sizeless SVE vectors.
9933 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9934 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9935 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9936 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9937 Kind = CK_BitCast;
9938 return Compatible;
9939 }
9940
9941 // Allow assignments between fixed-length and sizeless RVV vectors.
9942 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9943 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9944 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9945 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9946 Kind = CK_BitCast;
9947 return Compatible;
9948 }
9949 }
9950
9951 return Incompatible;
9952 }
9953
9954 // Diagnose attempts to convert between __ibm128, __float128 and long double
9955 // where such conversions currently can't be handled.
9956 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9957 return Incompatible;
9958
9959 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9960 // discards the imaginary part.
9961 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9962 !LHSType->getAs<ComplexType>())
9963 return Incompatible;
9964
9965 // Arithmetic conversions.
9966 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9967 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9968 if (ConvertRHS)
9969 Kind = PrepareScalarCast(RHS, LHSType);
9970 return Compatible;
9971 }
9972
9973 // Conversions to normal pointers.
9974 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9975 // U* -> T*
9976 if (isa<PointerType>(RHSType)) {
9977 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9978 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9979 if (AddrSpaceL != AddrSpaceR)
9980 Kind = CK_AddressSpaceConversion;
9981 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9982 Kind = CK_NoOp;
9983 else
9984 Kind = CK_BitCast;
9985 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9986 RHS.get()->getBeginLoc());
9987 }
9988
9989 // int -> T*
9990 if (RHSType->isIntegerType()) {
9991 Kind = CK_IntegralToPointer; // FIXME: null?
9992 return IntToPointer;
9993 }
9994
9995 // C pointers are not compatible with ObjC object pointers,
9996 // with two exceptions:
9997 if (isa<ObjCObjectPointerType>(RHSType)) {
9998 // - conversions to void*
9999 if (LHSPointer->getPointeeType()->isVoidType()) {
10000 Kind = CK_BitCast;
10001 return Compatible;
10002 }
10003
10004 // - conversions from 'Class' to the redefinition type
10005 if (RHSType->isObjCClassType() &&
10006 Context.hasSameType(LHSType,
10007 Context.getObjCClassRedefinitionType())) {
10008 Kind = CK_BitCast;
10009 return Compatible;
10010 }
10011
10012 Kind = CK_BitCast;
10013 return IncompatiblePointer;
10014 }
10015
10016 // U^ -> void*
10017 if (RHSType->getAs<BlockPointerType>()) {
10018 if (LHSPointer->getPointeeType()->isVoidType()) {
10019 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10020 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10021 ->getPointeeType()
10022 .getAddressSpace();
10023 Kind =
10024 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10025 return Compatible;
10026 }
10027 }
10028
10029 return Incompatible;
10030 }
10031
10032 // Conversions to block pointers.
10033 if (isa<BlockPointerType>(LHSType)) {
10034 // U^ -> T^
10035 if (RHSType->isBlockPointerType()) {
10036 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10037 ->getPointeeType()
10038 .getAddressSpace();
10039 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10040 ->getPointeeType()
10041 .getAddressSpace();
10042 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10043 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
10044 }
10045
10046 // int or null -> T^
10047 if (RHSType->isIntegerType()) {
10048 Kind = CK_IntegralToPointer; // FIXME: null
10049 return IntToBlockPointer;
10050 }
10051
10052 // id -> T^
10053 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10054 Kind = CK_AnyPointerToBlockPointerCast;
10055 return Compatible;
10056 }
10057
10058 // void* -> T^
10059 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10060 if (RHSPT->getPointeeType()->isVoidType()) {
10061 Kind = CK_AnyPointerToBlockPointerCast;
10062 return Compatible;
10063 }
10064
10065 return Incompatible;
10066 }
10067
10068 // Conversions to Objective-C pointers.
10069 if (isa<ObjCObjectPointerType>(LHSType)) {
10070 // A* -> B*
10071 if (RHSType->isObjCObjectPointerType()) {
10072 Kind = CK_BitCast;
10073 Sema::AssignConvertType result =
10074 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
10075 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10076 result == Compatible &&
10077 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
10078 result = IncompatibleObjCWeakRef;
10079 return result;
10080 }
10081
10082 // int or null -> A*
10083 if (RHSType->isIntegerType()) {
10084 Kind = CK_IntegralToPointer; // FIXME: null
10085 return IntToPointer;
10086 }
10087
10088 // In general, C pointers are not compatible with ObjC object pointers,
10089 // with two exceptions:
10090 if (isa<PointerType>(RHSType)) {
10091 Kind = CK_CPointerToObjCPointerCast;
10092
10093 // - conversions from 'void*'
10094 if (RHSType->isVoidPointerType()) {
10095 return Compatible;
10096 }
10097
10098 // - conversions to 'Class' from its redefinition type
10099 if (LHSType->isObjCClassType() &&
10100 Context.hasSameType(RHSType,
10101 Context.getObjCClassRedefinitionType())) {
10102 return Compatible;
10103 }
10104
10105 return IncompatiblePointer;
10106 }
10107
10108 // Only under strict condition T^ is compatible with an Objective-C pointer.
10109 if (RHSType->isBlockPointerType() &&
10110 LHSType->isBlockCompatibleObjCPointerType(Context)) {
10111 if (ConvertRHS)
10112 maybeExtendBlockObject(RHS);
10113 Kind = CK_BlockPointerToObjCPointerCast;
10114 return Compatible;
10115 }
10116
10117 return Incompatible;
10118 }
10119
10120 // Conversion to nullptr_t (C2x only)
10121 if (getLangOpts().C2x && LHSType->isNullPtrType() &&
10122 RHS.get()->isNullPointerConstant(Context,
10123 Expr::NPC_ValueDependentIsNull)) {
10124 // null -> nullptr_t
10125 Kind = CK_NullToPointer;
10126 return Compatible;
10127 }
10128
10129 // Conversions from pointers that are not covered by the above.
10130 if (isa<PointerType>(RHSType)) {
10131 // T* -> _Bool
10132 if (LHSType == Context.BoolTy) {
10133 Kind = CK_PointerToBoolean;
10134 return Compatible;
10135 }
10136
10137 // T* -> int
10138 if (LHSType->isIntegerType()) {
10139 Kind = CK_PointerToIntegral;
10140 return PointerToInt;
10141 }
10142
10143 return Incompatible;
10144 }
10145
10146 // Conversions from Objective-C pointers that are not covered by the above.
10147 if (isa<ObjCObjectPointerType>(RHSType)) {
10148 // T* -> _Bool
10149 if (LHSType == Context.BoolTy) {
10150 Kind = CK_PointerToBoolean;
10151 return Compatible;
10152 }
10153
10154 // T* -> int
10155 if (LHSType->isIntegerType()) {
10156 Kind = CK_PointerToIntegral;
10157 return PointerToInt;
10158 }
10159
10160 return Incompatible;
10161 }
10162
10163 // struct A -> struct B
10164 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10165 if (Context.typesAreCompatible(LHSType, RHSType)) {
10166 Kind = CK_NoOp;
10167 return Compatible;
10168 }
10169 }
10170
10171 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10172 Kind = CK_IntToOCLSampler;
10173 return Compatible;
10174 }
10175
10176 return Incompatible;
10177}
10178
10179/// Constructs a transparent union from an expression that is
10180/// used to initialize the transparent union.
10181static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10182 ExprResult &EResult, QualType UnionType,
10183 FieldDecl *Field) {
10184 // Build an initializer list that designates the appropriate member
10185 // of the transparent union.
10186 Expr *E = EResult.get();
10187 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
10188 E, SourceLocation());
10189 Initializer->setType(UnionType);
10190 Initializer->setInitializedFieldInUnion(Field);
10191
10192 // Build a compound literal constructing a value of the transparent
10193 // union type from this initializer list.
10194 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10195 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10196 VK_PRValue, Initializer, false);
10197}
10198
10199Sema::AssignConvertType
10200Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10201 ExprResult &RHS) {
10202 QualType RHSType = RHS.get()->getType();
10203
10204 // If the ArgType is a Union type, we want to handle a potential
10205 // transparent_union GCC extension.
10206 const RecordType *UT = ArgType->getAsUnionType();
10207 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
10208 return Incompatible;
10209
10210 // The field to initialize within the transparent union.
10211 RecordDecl *UD = UT->getDecl();
10212 FieldDecl *InitField = nullptr;
10213 // It's compatible if the expression matches any of the fields.
10214 for (auto *it : UD->fields()) {
10215 if (it->getType()->isPointerType()) {
10216 // If the transparent union contains a pointer type, we allow:
10217 // 1) void pointer
10218 // 2) null pointer constant
10219 if (RHSType->isPointerType())
10220 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10221 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10222 InitField = it;
10223 break;
10224 }
10225
10226 if (RHS.get()->isNullPointerConstant(Context,
10227 Expr::NPC_ValueDependentIsNull)) {
10228 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10229 CK_NullToPointer);
10230 InitField = it;
10231 break;
10232 }
10233 }
10234
10235 CastKind Kind;
10236 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
10237 == Compatible) {
10238 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10239 InitField = it;
10240 break;
10241 }
10242 }
10243
10244 if (!InitField)
10245 return Incompatible;
10246
10247 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10248 return Compatible;
10249}
10250
10251Sema::AssignConvertType
10252Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
10253 bool Diagnose,
10254 bool DiagnoseCFAudited,
10255 bool ConvertRHS) {
10256 // We need to be able to tell the caller whether we diagnosed a problem, if
10257 // they ask us to issue diagnostics.
10258 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(static_cast <bool> ((ConvertRHS || !Diagnose) &&
"can't indicate whether we diagnosed") ? void (0) : __assert_fail
("(ConvertRHS || !Diagnose) && \"can't indicate whether we diagnosed\""
, "clang/lib/Sema/SemaExpr.cpp", 10258, __extension__ __PRETTY_FUNCTION__
))
;
10259
10260 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10261 // we can't avoid *all* modifications at the moment, so we need some somewhere
10262 // to put the updated value.
10263 ExprResult LocalRHS = CallerRHS;
10264 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10265
10266 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10267 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10268 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10269 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10270 Diag(RHS.get()->getExprLoc(),
10271 diag::warn_noderef_to_dereferenceable_pointer)
10272 << RHS.get()->getSourceRange();
10273 }
10274 }
10275 }
10276
10277 if (getLangOpts().CPlusPlus) {
10278 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10279 // C++ 5.17p3: If the left operand is not of class type, the
10280 // expression is implicitly converted (C++ 4) to the
10281 // cv-unqualified type of the left operand.
10282 QualType RHSType = RHS.get()->getType();
10283 if (Diagnose) {
10284 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10285 AA_Assigning);
10286 } else {
10287 ImplicitConversionSequence ICS =
10288 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10289 /*SuppressUserConversions=*/false,
10290 AllowedExplicit::None,
10291 /*InOverloadResolution=*/false,
10292 /*CStyle=*/false,
10293 /*AllowObjCWritebackConversion=*/false);
10294 if (ICS.isFailure())
10295 return Incompatible;
10296 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10297 ICS, AA_Assigning);
10298 }
10299 if (RHS.isInvalid())
10300 return Incompatible;
10301 Sema::AssignConvertType result = Compatible;
10302 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10303 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10304 result = IncompatibleObjCWeakRef;
10305 return result;
10306 }
10307
10308 // FIXME: Currently, we fall through and treat C++ classes like C
10309 // structures.
10310 // FIXME: We also fall through for atomics; not sure what should
10311 // happen there, though.
10312 } else if (RHS.get()->getType() == Context.OverloadTy) {
10313 // As a set of extensions to C, we support overloading on functions. These
10314 // functions need to be resolved here.
10315 DeclAccessPair DAP;
10316 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10317 RHS.get(), LHSType, /*Complain=*/false, DAP))
10318 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10319 else
10320 return Incompatible;
10321 }
10322
10323 // This check seems unnatural, however it is necessary to ensure the proper
10324 // conversion of functions/arrays. If the conversion were done for all
10325 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10326 // expressions that suppress this implicit conversion (&, sizeof). This needs
10327 // to happen before we check for null pointer conversions because C does not
10328 // undergo the same implicit conversions as C++ does above (by the calls to
10329 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10330 // lvalue to rvalue cast before checking for null pointer constraints. This
10331 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10332 //
10333 // Suppress this for references: C++ 8.5.3p5.
10334 if (!LHSType->isReferenceType()) {
10335 // FIXME: We potentially allocate here even if ConvertRHS is false.
10336 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
10337 if (RHS.isInvalid())
10338 return Incompatible;
10339 }
10340
10341 // The constraints are expressed in terms of the atomic, qualified, or
10342 // unqualified type of the LHS.
10343 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10344
10345 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10346 // a null pointer constant <C2x>or its type is nullptr_t;</C2x>.
10347 if ((LHSTypeAfterConversion->isPointerType() ||
10348 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10349 LHSTypeAfterConversion->isBlockPointerType()) &&
10350 ((getLangOpts().C2x && RHS.get()->getType()->isNullPtrType()) ||
10351 RHS.get()->isNullPointerConstant(Context,
10352 Expr::NPC_ValueDependentIsNull))) {
10353 if (Diagnose || ConvertRHS) {
10354 CastKind Kind;
10355 CXXCastPath Path;
10356 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10357 /*IgnoreBaseAccess=*/false, Diagnose);
10358 if (ConvertRHS)
10359 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10360 }
10361 return Compatible;
10362 }
10363 // C2x 6.5.16.1p1: the left operand has type atomic, qualified, or
10364 // unqualified bool, and the right operand is a pointer or its type is
10365 // nullptr_t.
10366 if (getLangOpts().C2x && LHSType->isBooleanType() &&
10367 RHS.get()->getType()->isNullPtrType()) {
10368 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10369 // only handles nullptr -> _Bool due to needing an extra conversion
10370 // step.
10371 // We model this by converting from nullptr -> void * and then let the
10372 // conversion from void * -> _Bool happen naturally.
10373 if (Diagnose || ConvertRHS) {
10374 CastKind Kind;
10375 CXXCastPath Path;
10376 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10377 /*IgnoreBaseAccess=*/false, Diagnose);
10378 if (ConvertRHS)
10379 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10380 &Path);
10381 }
10382 }
10383
10384 // OpenCL queue_t type assignment.
10385 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10386 Context, Expr::NPC_ValueDependentIsNull)) {
10387 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10388 return Compatible;
10389 }
10390
10391 CastKind Kind;
10392 Sema::AssignConvertType result =
10393 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10394
10395 // C99 6.5.16.1p2: The value of the right operand is converted to the
10396 // type of the assignment expression.
10397 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10398 // so that we can use references in built-in functions even in C.
10399 // The getNonReferenceType() call makes sure that the resulting expression
10400 // does not have reference type.
10401 if (result != Incompatible && RHS.get()->getType() != LHSType) {
10402 QualType Ty = LHSType.getNonLValueExprType(Context);
10403 Expr *E = RHS.get();
10404
10405 // Check for various Objective-C errors. If we are not reporting
10406 // diagnostics and just checking for errors, e.g., during overload
10407 // resolution, return Incompatible to indicate the failure.
10408 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10409 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
10410 Diagnose, DiagnoseCFAudited) != ACR_okay) {
10411 if (!Diagnose)
10412 return Incompatible;
10413 }
10414 if (getLangOpts().ObjC &&
10415 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10416 E->getType(), E, Diagnose) ||
10417 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10418 if (!Diagnose)
10419 return Incompatible;
10420 // Replace the expression with a corrected version and continue so we
10421 // can find further errors.
10422 RHS = E;
10423 return Compatible;
10424 }
10425
10426 if (ConvertRHS)
10427 RHS = ImpCastExprToType(E, Ty, Kind);
10428 }
10429
10430 return result;
10431}
10432
10433namespace {
10434/// The original operand to an operator, prior to the application of the usual
10435/// arithmetic conversions and converting the arguments of a builtin operator
10436/// candidate.
10437struct OriginalOperand {
10438 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10439 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10440 Op = MTE->getSubExpr();
10441 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10442 Op = BTE->getSubExpr();
10443 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10444 Orig = ICE->getSubExprAsWritten();
10445 Conversion = ICE->getConversionFunction();
10446 }
10447 }
10448
10449 QualType getType() const { return Orig->getType(); }
10450
10451 Expr *Orig;
10452 NamedDecl *Conversion;
10453};
10454}
10455
10456QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10457 ExprResult &RHS) {
10458 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10459
10460 Diag(Loc, diag::err_typecheck_invalid_operands)
10461 << OrigLHS.getType() << OrigRHS.getType()
10462 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10463
10464 // If a user-defined conversion was applied to either of the operands prior
10465 // to applying the built-in operator rules, tell the user about it.
10466 if (OrigLHS.Conversion) {
10467 Diag(OrigLHS.Conversion->getLocation(),
10468 diag::note_typecheck_invalid_operands_converted)
10469 << 0 << LHS.get()->getType();
10470 }
10471 if (OrigRHS.Conversion) {
10472 Diag(OrigRHS.Conversion->getLocation(),
10473 diag::note_typecheck_invalid_operands_converted)
10474 << 1 << RHS.get()->getType();
10475 }
10476
10477 return QualType();
10478}
10479
10480// Diagnose cases where a scalar was implicitly converted to a vector and
10481// diagnose the underlying types. Otherwise, diagnose the error
10482// as invalid vector logical operands for non-C++ cases.
10483QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10484 ExprResult &RHS) {
10485 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10486 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10487
10488 bool LHSNatVec = LHSType->isVectorType();
10489 bool RHSNatVec = RHSType->isVectorType();
10490
10491 if (!(LHSNatVec && RHSNatVec)) {
10492 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10493 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10494 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10495 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10496 << Vector->getSourceRange();
10497 return QualType();
10498 }
10499
10500 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10501 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10502 << RHS.get()->getSourceRange();
10503
10504 return QualType();
10505}
10506
10507/// Try to convert a value of non-vector type to a vector type by converting
10508/// the type to the element type of the vector and then performing a splat.
10509/// If the language is OpenCL, we only use conversions that promote scalar
10510/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10511/// for float->int.
10512///
10513/// OpenCL V2.0 6.2.6.p2:
10514/// An error shall occur if any scalar operand type has greater rank
10515/// than the type of the vector element.
10516///
10517/// \param scalar - if non-null, actually perform the conversions
10518/// \return true if the operation fails (but without diagnosing the failure)
10519static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10520 QualType scalarTy,
10521 QualType vectorEltTy,
10522 QualType vectorTy,
10523 unsigned &DiagID) {
10524 // The conversion to apply to the scalar before splatting it,
10525 // if necessary.
10526 CastKind scalarCast = CK_NoOp;
10527
10528 if (vectorEltTy->isIntegralType(S.Context)) {
10529 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10530 (scalarTy->isIntegerType() &&
10531 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10532 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10533 return true;
10534 }
10535 if (!scalarTy->isIntegralType(S.Context))
10536 return true;
10537 scalarCast = CK_IntegralCast;
10538 } else if (vectorEltTy->isRealFloatingType()) {
10539 if (scalarTy->isRealFloatingType()) {
10540 if (S.getLangOpts().OpenCL &&
10541 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10542 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10543 return true;
10544 }
10545 scalarCast = CK_FloatingCast;
10546 }
10547 else if (scalarTy->isIntegralType(S.Context))
10548 scalarCast = CK_IntegralToFloating;
10549 else
10550 return true;
10551 } else {
10552 return true;
10553 }
10554
10555 // Adjust scalar if desired.
10556 if (scalar) {
10557 if (scalarCast != CK_NoOp)
10558 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10559 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10560 }
10561 return false;
10562}
10563
10564/// Convert vector E to a vector with the same number of elements but different
10565/// element type.
10566static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10567 const auto *VecTy = E->getType()->getAs<VectorType>();
10568 assert(VecTy && "Expression E must be a vector")(static_cast <bool> (VecTy && "Expression E must be a vector"
) ? void (0) : __assert_fail ("VecTy && \"Expression E must be a vector\""
, "clang/lib/Sema/SemaExpr.cpp", 10568, __extension__ __PRETTY_FUNCTION__
))
;
10569 QualType NewVecTy =
10570 VecTy->isExtVectorType()
10571 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10572 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10573 VecTy->getVectorKind());
10574
10575 // Look through the implicit cast. Return the subexpression if its type is
10576 // NewVecTy.
10577 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10578 if (ICE->getSubExpr()->getType() == NewVecTy)
10579 return ICE->getSubExpr();
10580
10581 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10582 return S.ImpCastExprToType(E, NewVecTy, Cast);
10583}
10584
10585/// Test if a (constant) integer Int can be casted to another integer type
10586/// IntTy without losing precision.
10587static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10588 QualType OtherIntTy) {
10589 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10590
10591 // Reject cases where the value of the Int is unknown as that would
10592 // possibly cause truncation, but accept cases where the scalar can be
10593 // demoted without loss of precision.
10594 Expr::EvalResult EVResult;
10595 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10596 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10597 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10598 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10599
10600 if (CstInt) {
10601 // If the scalar is constant and is of a higher order and has more active
10602 // bits that the vector element type, reject it.
10603 llvm::APSInt Result = EVResult.Val.getInt();
10604 unsigned NumBits = IntSigned
10605 ? (Result.isNegative() ? Result.getSignificantBits()
10606 : Result.getActiveBits())
10607 : Result.getActiveBits();
10608 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10609 return true;
10610
10611 // If the signedness of the scalar type and the vector element type
10612 // differs and the number of bits is greater than that of the vector
10613 // element reject it.
10614 return (IntSigned != OtherIntSigned &&
10615 NumBits > S.Context.getIntWidth(OtherIntTy));
10616 }
10617
10618 // Reject cases where the value of the scalar is not constant and it's
10619 // order is greater than that of the vector element type.
10620 return (Order < 0);
10621}
10622
10623/// Test if a (constant) integer Int can be casted to floating point type
10624/// FloatTy without losing precision.
10625static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10626 QualType FloatTy) {
10627 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10628
10629 // Determine if the integer constant can be expressed as a floating point
10630 // number of the appropriate type.
10631 Expr::EvalResult EVResult;
10632 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10633
10634 uint64_t Bits = 0;
10635 if (CstInt) {
10636 // Reject constants that would be truncated if they were converted to
10637 // the floating point type. Test by simple to/from conversion.
10638 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10639 // could be avoided if there was a convertFromAPInt method
10640 // which could signal back if implicit truncation occurred.
10641 llvm::APSInt Result = EVResult.Val.getInt();
10642 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10643 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10644 llvm::APFloat::rmTowardZero);
10645 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10646 !IntTy->hasSignedIntegerRepresentation());
10647 bool Ignored = false;
10648 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10649 &Ignored);
10650 if (Result != ConvertBack)
10651 return true;
10652 } else {
10653 // Reject types that cannot be fully encoded into the mantissa of
10654 // the float.
10655 Bits = S.Context.getTypeSize(IntTy);
10656 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10657 S.Context.getFloatTypeSemantics(FloatTy));
10658 if (Bits > FloatPrec)
10659 return true;
10660 }
10661
10662 return false;
10663}
10664
10665/// Attempt to convert and splat Scalar into a vector whose types matches
10666/// Vector following GCC conversion rules. The rule is that implicit
10667/// conversion can occur when Scalar can be casted to match Vector's element
10668/// type without causing truncation of Scalar.
10669static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10670 ExprResult *Vector) {
10671 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10672 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10673 QualType VectorEltTy;
10674
10675 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10676 assert(!isa<ExtVectorType>(VT) &&(static_cast <bool> (!isa<ExtVectorType>(VT) &&
"ExtVectorTypes should not be handled here!") ? void (0) : __assert_fail
("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\""
, "clang/lib/Sema/SemaExpr.cpp", 10677, __extension__ __PRETTY_FUNCTION__
))
10677 "ExtVectorTypes should not be handled here!")(static_cast <bool> (!isa<ExtVectorType>(VT) &&
"ExtVectorTypes should not be handled here!") ? void (0) : __assert_fail
("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\""
, "clang/lib/Sema/SemaExpr.cpp", 10677, __extension__ __PRETTY_FUNCTION__
))
;
10678 VectorEltTy = VT->getElementType();
10679 } else if (VectorTy->isVLSTBuiltinType()) {
10680 VectorEltTy =
10681 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10682 } else {
10683 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here")::llvm::llvm_unreachable_internal("Only Fixed-Length and SVE Vector types are handled here"
, "clang/lib/Sema/SemaExpr.cpp", 10683)
;
10684 }
10685
10686 // Reject cases where the vector element type or the scalar element type are
10687 // not integral or floating point types.
10688 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10689 return true;
10690
10691 // The conversion to apply to the scalar before splatting it,
10692 // if necessary.
10693 CastKind ScalarCast = CK_NoOp;
10694
10695 // Accept cases where the vector elements are integers and the scalar is
10696 // an integer.
10697 // FIXME: Notionally if the scalar was a floating point value with a precise
10698 // integral representation, we could cast it to an appropriate integer
10699 // type and then perform the rest of the checks here. GCC will perform
10700 // this conversion in some cases as determined by the input language.
10701 // We should accept it on a language independent basis.
10702 if (VectorEltTy->isIntegralType(S.Context) &&
10703 ScalarTy->isIntegralType(S.Context) &&
10704 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10705
10706 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10707 return true;
10708
10709 ScalarCast = CK_IntegralCast;
10710 } else if (VectorEltTy->isIntegralType(S.Context) &&
10711 ScalarTy->isRealFloatingType()) {
10712 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10713 ScalarCast = CK_FloatingToIntegral;
10714 else
10715 return true;
10716 } else if (VectorEltTy->isRealFloatingType()) {
10717 if (ScalarTy->isRealFloatingType()) {
10718
10719 // Reject cases where the scalar type is not a constant and has a higher
10720 // Order than the vector element type.
10721 llvm::APFloat Result(0.0);
10722
10723 // Determine whether this is a constant scalar. In the event that the
10724 // value is dependent (and thus cannot be evaluated by the constant
10725 // evaluator), skip the evaluation. This will then diagnose once the
10726 // expression is instantiated.
10727 bool CstScalar = Scalar->get()->isValueDependent() ||
10728 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10729 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10730 if (!CstScalar && Order < 0)
10731 return true;
10732
10733 // If the scalar cannot be safely casted to the vector element type,
10734 // reject it.
10735 if (CstScalar) {
10736 bool Truncated = false;
10737 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10738 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10739 if (Truncated)
10740 return true;
10741 }
10742
10743 ScalarCast = CK_FloatingCast;
10744 } else if (ScalarTy->isIntegralType(S.Context)) {
10745 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10746 return true;
10747
10748 ScalarCast = CK_IntegralToFloating;
10749 } else
10750 return true;
10751 } else if (ScalarTy->isEnumeralType())
10752 return true;
10753
10754 // Adjust scalar if desired.
10755 if (Scalar) {
10756 if (ScalarCast != CK_NoOp)
10757 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10758 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10759 }
10760 return false;
10761}
10762
10763QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10764 SourceLocation Loc, bool IsCompAssign,
10765 bool AllowBothBool,
10766 bool AllowBoolConversions,
10767 bool AllowBoolOperation,
10768 bool ReportInvalid) {
10769 if (!IsCompAssign) {
10770 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10771 if (LHS.isInvalid())
10772 return QualType();
10773 }
10774 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10775 if (RHS.isInvalid())
10776 return QualType();
10777
10778 // For conversion purposes, we ignore any qualifiers.
10779 // For example, "const float" and "float" are equivalent.
10780 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10781 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10782
10783 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10784 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10785 assert(LHSVecType || RHSVecType)(static_cast <bool> (LHSVecType || RHSVecType) ? void (
0) : __assert_fail ("LHSVecType || RHSVecType", "clang/lib/Sema/SemaExpr.cpp"
, 10785, __extension__ __PRETTY_FUNCTION__))
;
10786
10787 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10788 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10789 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10790
10791 // AltiVec-style "vector bool op vector bool" combinations are allowed
10792 // for some operators but not others.
10793 if (!AllowBothBool &&
10794 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10795 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10796 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10797
10798 // This operation may not be performed on boolean vectors.
10799 if (!AllowBoolOperation &&
10800 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10801 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10802
10803 // If the vector types are identical, return.
10804 if (Context.hasSameType(LHSType, RHSType))
10805 return Context.getCommonSugaredType(LHSType, RHSType);
10806
10807 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10808 if (LHSVecType && RHSVecType &&
10809 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10810 if (isa<ExtVectorType>(LHSVecType)) {
10811 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10812 return LHSType;
10813 }
10814
10815 if (!IsCompAssign)
10816 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10817 return RHSType;
10818 }
10819
10820 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10821 // can be mixed, with the result being the non-bool type. The non-bool
10822 // operand must have integer element type.
10823 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10824 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10825 (Context.getTypeSize(LHSVecType->getElementType()) ==
10826 Context.getTypeSize(RHSVecType->getElementType()))) {
10827 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10828 LHSVecType->getElementType()->isIntegerType() &&
10829 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10830 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10831 return LHSType;
10832 }
10833 if (!IsCompAssign &&
10834 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10835 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10836 RHSVecType->getElementType()->isIntegerType()) {
10837 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10838 return RHSType;
10839 }
10840 }
10841
10842 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10843 // invalid since the ambiguity can affect the ABI.
10844 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10845 unsigned &SVEorRVV) {
10846 const VectorType *VecType = SecondType->getAs<VectorType>();
10847 SVEorRVV = 0;
10848 if (FirstType->isSizelessBuiltinType() && VecType) {
10849 if (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10850 VecType->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
10851 return true;
10852 if (VecType->getVectorKind() == VectorType::RVVFixedLengthDataVector) {
10853 SVEorRVV = 1;
10854 return true;
10855 }
10856 }
10857
10858 return false;
10859 };
10860
10861 unsigned SVEorRVV;
10862 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10863 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10864 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10865 << SVEorRVV << LHSType << RHSType;
10866 return QualType();
10867 }
10868
10869 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10870 // invalid since the ambiguity can affect the ABI.
10871 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10872 unsigned &SVEorRVV) {
10873 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10874 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10875
10876 SVEorRVV = 0;
10877 if (FirstVecType && SecondVecType) {
10878 if (FirstVecType->getVectorKind() == VectorType::GenericVector) {
10879 if (SecondVecType->getVectorKind() ==
10880 VectorType::SveFixedLengthDataVector ||
10881 SecondVecType->getVectorKind() ==
10882 VectorType::SveFixedLengthPredicateVector)
10883 return true;
10884 if (SecondVecType->getVectorKind() ==
10885 VectorType::RVVFixedLengthDataVector) {
10886 SVEorRVV = 1;
10887 return true;
10888 }
10889 }
10890 return false;
10891 }
10892
10893 if (SecondVecType &&
10894 SecondVecType->getVectorKind() == VectorType::GenericVector) {
10895 if (FirstType->isSVESizelessBuiltinType())
10896 return true;
10897 if (FirstType->isRVVSizelessBuiltinType()) {
10898 SVEorRVV = 1;
10899 return true;
10900 }
10901 }
10902
10903 return false;
10904 };
10905
10906 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10907 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10908 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10909 << SVEorRVV << LHSType << RHSType;
10910 return QualType();
10911 }
10912
10913 // If there's a vector type and a scalar, try to convert the scalar to
10914 // the vector element type and splat.
10915 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10916 if (!RHSVecType) {
10917 if (isa<ExtVectorType>(LHSVecType)) {
10918 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10919 LHSVecType->getElementType(), LHSType,
10920 DiagID))
10921 return LHSType;
10922 } else {
10923 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10924 return LHSType;
10925 }
10926 }
10927 if (!LHSVecType) {
10928 if (isa<ExtVectorType>(RHSVecType)) {
10929 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10930 LHSType, RHSVecType->getElementType(),
10931 RHSType, DiagID))
10932 return RHSType;
10933 } else {
10934 if (LHS.get()->isLValue() ||
10935 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10936 return RHSType;
10937 }
10938 }
10939
10940 // FIXME: The code below also handles conversion between vectors and
10941 // non-scalars, we should break this down into fine grained specific checks
10942 // and emit proper diagnostics.
10943 QualType VecType = LHSVecType ? LHSType : RHSType;
10944 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10945 QualType OtherType = LHSVecType ? RHSType : LHSType;
10946 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10947 if (isLaxVectorConversion(OtherType, VecType)) {
10948 if (Context.getTargetInfo().getTriple().isPPC() &&
10949 anyAltivecTypes(RHSType, LHSType) &&
10950 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10951 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10952 // If we're allowing lax vector conversions, only the total (data) size
10953 // needs to be the same. For non compound assignment, if one of the types is
10954 // scalar, the result is always the vector type.
10955 if (!IsCompAssign) {
10956 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10957 return VecType;
10958 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10959 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10960 // type. Note that this is already done by non-compound assignments in
10961 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10962 // <1 x T> -> T. The result is also a vector type.
10963 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10964 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10965 ExprResult *RHSExpr = &RHS;
10966 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10967 return VecType;
10968 }
10969 }
10970
10971 // Okay, the expression is invalid.
10972
10973 // If there's a non-vector, non-real operand, diagnose that.
10974 if ((!RHSVecType && !RHSType->isRealType()) ||
10975 (!LHSVecType && !LHSType->isRealType())) {
10976 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10977 << LHSType << RHSType
10978 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10979 return QualType();
10980 }
10981
10982 // OpenCL V1.1 6.2.6.p1:
10983 // If the operands are of more than one vector type, then an error shall
10984 // occur. Implicit conversions between vector types are not permitted, per
10985 // section 6.2.1.
10986 if (getLangOpts().OpenCL &&
10987 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10988 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10989 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10990 << RHSType;
10991 return QualType();
10992 }
10993
10994
10995 // If there is a vector type that is not a ExtVector and a scalar, we reach
10996 // this point if scalar could not be converted to the vector's element type
10997 // without truncation.
10998 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10999 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
11000 QualType Scalar = LHSVecType ? RHSType : LHSType;
11001 QualType Vector = LHSVecType ? LHSType : RHSType;
11002 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11003 Diag(Loc,
11004 diag::err_typecheck_vector_not_convertable_implict_truncation)
11005 << ScalarOrVector << Scalar << Vector;
11006
11007 return QualType();
11008 }
11009
11010 // Otherwise, use the generic diagnostic.
11011 Diag(Loc, DiagID)
11012 << LHSType << RHSType
11013 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11014 return QualType();
11015}
11016
11017QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
11018 SourceLocation Loc,
11019 bool IsCompAssign,
11020 ArithConvKind OperationKind) {
11021 if (!IsCompAssign) {
11022 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11023 if (LHS.isInvalid())
11024 return QualType();
11025 }
11026 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11027 if (RHS.isInvalid())
11028 return QualType();
11029
11030 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11031 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11032
11033 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11034 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11035
11036 unsigned DiagID = diag::err_typecheck_invalid_operands;
11037 if ((OperationKind == ACK_Arithmetic) &&
11038 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11039 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11040 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11041 << RHS.get()->getSourceRange();
11042 return QualType();
11043 }
11044
11045 if (Context.hasSameType(LHSType, RHSType))
11046 return LHSType;
11047
11048 if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
11049 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11050 return LHSType;
11051 }
11052 if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
11053 if (LHS.get()->isLValue() ||
11054 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11055 return RHSType;
11056 }
11057
11058 if ((!LHSType->isVLSTBuiltinType() && !LHSType->isRealType()) ||
11059 (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) {
11060 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11061 << LHSType << RHSType << LHS.get()->getSourceRange()
11062 << RHS.get()->getSourceRange();
11063 return QualType();
11064 }
11065
11066 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
11067 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11068 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
11069 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11070 << LHSType << RHSType << LHS.get()->getSourceRange()
11071 << RHS.get()->getSourceRange();
11072 return QualType();
11073 }
11074
11075 if (LHSType->isVLSTBuiltinType() || RHSType->isVLSTBuiltinType()) {
11076 QualType Scalar = LHSType->isVLSTBuiltinType() ? RHSType : LHSType;
11077 QualType Vector = LHSType->isVLSTBuiltinType() ? LHSType : RHSType;
11078 bool ScalarOrVector =
11079 LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType();
11080
11081 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11082 << ScalarOrVector << Scalar << Vector;
11083
11084 return QualType();
11085 }
11086
11087 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11088 << RHS.get()->getSourceRange();
11089 return QualType();
11090}
11091
11092// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11093// expression. These are mainly cases where the null pointer is used as an
11094// integer instead of a pointer.
11095static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11096 SourceLocation Loc, bool IsCompare) {
11097 // The canonical way to check for a GNU null is with isNullPointerConstant,
11098 // but we use a bit of a hack here for speed; this is a relatively
11099 // hot path, and isNullPointerConstant is slow.
11100 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11101 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11102
11103 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11104
11105 // Avoid analyzing cases where the result will either be invalid (and
11106 // diagnosed as such) or entirely valid and not something to warn about.
11107 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11108 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11109 return;
11110
11111 // Comparison operations would not make sense with a null pointer no matter
11112 // what the other expression is.
11113 if (!IsCompare) {
11114 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11115 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11116 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11117 return;
11118 }
11119
11120 // The rest of the operations only make sense with a null pointer
11121 // if the other expression is a pointer.
11122 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11123 NonNullType->canDecayToPointerType())
11124 return;
11125
11126 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11127 << LHSNull /* LHS is NULL */ << NonNullType
11128 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11129}
11130
11131static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11132 SourceLocation Loc) {
11133 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11134 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11135 if (!LUE || !RUE)
11136 return;
11137 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11138 RUE->getKind() != UETT_SizeOf)
11139 return;
11140
11141 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11142 QualType LHSTy = LHSArg->getType();
11143 QualType RHSTy;
11144
11145 if (RUE->isArgumentType())
11146 RHSTy = RUE->getArgumentType().getNonReferenceType();
11147 else
11148 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11149
11150 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11151 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11152 return;
11153
11154 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11155 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11156 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11157 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11158 << LHSArgDecl;
11159 }
11160 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11161 QualType ArrayElemTy = ArrayTy->getElementType();
11162 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11163 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11164 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11165 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11166 return;
11167 S.Diag(Loc, diag::warn_division_sizeof_array)
11168 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11169 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11170 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11171 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11172 << LHSArgDecl;
11173 }
11174
11175 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11176 }
11177}
11178
11179static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11180 ExprResult &RHS,
11181 SourceLocation Loc, bool IsDiv) {
11182 // Check for division/remainder by zero.
11183 Expr::EvalResult RHSValue;
11184 if (!RHS.get()->isValueDependent() &&
11185 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11186 RHSValue.Val.getInt() == 0)
11187 S.DiagRuntimeBehavior(Loc, RHS.get(),
11188 S.PDiag(diag::warn_remainder_division_by_zero)
11189 << IsDiv << RHS.get()->getSourceRange());
11190}
11191
11192QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11193 SourceLocation Loc,
11194 bool IsCompAssign, bool IsDiv) {
11195 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11196
11197 QualType LHSTy = LHS.get()->getType();
11198 QualType RHSTy = RHS.get()->getType();
11199 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11200 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11201 /*AllowBothBool*/ getLangOpts().AltiVec,
11202 /*AllowBoolConversions*/ false,
11203 /*AllowBooleanOperation*/ false,
11204 /*ReportInvalid*/ true);
11205 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
11206 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11207 ACK_Arithmetic);
11208 if (!IsDiv &&
11209 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11210 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11211 // For division, only matrix-by-scalar is supported. Other combinations with
11212 // matrix types are invalid.
11213 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11214 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11215
11216 QualType compType = UsualArithmeticConversions(
11217 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11218 if (LHS.isInvalid() || RHS.isInvalid())
11219 return QualType();
11220
11221
11222 if (compType.isNull() || !compType->isArithmeticType())
11223 return InvalidOperands(Loc, LHS, RHS);
11224 if (IsDiv) {
11225 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11226 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11227 }
11228 return compType;
11229}
11230
11231QualType Sema::CheckRemainderOperands(
11232 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11233 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11234
11235 if (LHS.get()->getType()->isVectorType() ||
11236 RHS.get()->getType()->isVectorType()) {
11237 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11238 RHS.get()->getType()->hasIntegerRepresentation())
11239 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11240 /*AllowBothBool*/ getLangOpts().AltiVec,
11241 /*AllowBoolConversions*/ false,
11242 /*AllowBooleanOperation*/ false,
11243 /*ReportInvalid*/ true);
11244 return InvalidOperands(Loc, LHS, RHS);
11245 }
11246
11247 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11248 RHS.get()->getType()->isVLSTBuiltinType()) {
11249 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11250 RHS.get()->getType()->hasIntegerRepresentation())
11251 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11252 ACK_Arithmetic);
11253
11254 return InvalidOperands(Loc, LHS, RHS);
11255 }
11256
11257 QualType compType = UsualArithmeticConversions(
11258 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11259 if (LHS.isInvalid() || RHS.isInvalid())
11260 return QualType();
11261
11262 if (compType.isNull() || !compType->isIntegerType())
11263 return InvalidOperands(Loc, LHS, RHS);
11264 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11265 return compType;
11266}
11267
11268/// Diagnose invalid arithmetic on two void pointers.
11269static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11270 Expr *LHSExpr, Expr *RHSExpr) {
11271 S.Diag(Loc, S.getLangOpts().CPlusPlus
11272 ? diag::err_typecheck_pointer_arith_void_type
11273 : diag::ext_gnu_void_ptr)
11274 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11275 << RHSExpr->getSourceRange();
11276}
11277
11278/// Diagnose invalid arithmetic on a void pointer.
11279static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11280 Expr *Pointer) {
11281 S.Diag(Loc, S.getLangOpts().CPlusPlus
11282 ? diag::err_typecheck_pointer_arith_void_type
11283 : diag::ext_gnu_void_ptr)
11284 << 0 /* one pointer */ << Pointer->getSourceRange();
11285}
11286
11287/// Diagnose invalid arithmetic on a null pointer.
11288///
11289/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11290/// idiom, which we recognize as a GNU extension.
11291///
11292static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11293 Expr *Pointer, bool IsGNUIdiom) {
11294 if (IsGNUIdiom)
11295 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11296 << Pointer->getSourceRange();
11297 else
11298 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11299 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11300}
11301
11302/// Diagnose invalid subraction on a null pointer.
11303///
11304static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11305 Expr *Pointer, bool BothNull) {
11306 // Null - null is valid in C++ [expr.add]p7
11307 if (BothNull && S.getLangOpts().CPlusPlus)
11308 return;
11309
11310 // Is this s a macro from a system header?
11311 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
11312 return;
11313
11314 S.DiagRuntimeBehavior(Loc, Pointer,
11315 S.PDiag(diag::warn_pointer_sub_null_ptr)
11316 << S.getLangOpts().CPlusPlus
11317 << Pointer->getSourceRange());
11318}
11319
11320/// Diagnose invalid arithmetic on two function pointers.
11321static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11322 Expr *LHS, Expr *RHS) {
11323 assert(LHS->getType()->isAnyPointerType())(static_cast <bool> (LHS->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("LHS->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11323, __extension__ __PRETTY_FUNCTION__
))
;
11324 assert(RHS->getType()->isAnyPointerType())(static_cast <bool> (RHS->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("RHS->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11324, __extension__ __PRETTY_FUNCTION__
))
;
11325 S.Diag(Loc, S.getLangOpts().CPlusPlus
11326 ? diag::err_typecheck_pointer_arith_function_type
11327 : diag::ext_gnu_ptr_func_arith)
11328 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11329 // We only show the second type if it differs from the first.
11330 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
11331 RHS->getType())
11332 << RHS->getType()->getPointeeType()
11333 << LHS->getSourceRange() << RHS->getSourceRange();
11334}
11335
11336/// Diagnose invalid arithmetic on a function pointer.
11337static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11338 Expr *Pointer) {
11339 assert(Pointer->getType()->isAnyPointerType())(static_cast <bool> (Pointer->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11339, __extension__ __PRETTY_FUNCTION__
))
;
11340 S.Diag(Loc, S.getLangOpts().CPlusPlus
11341 ? diag::err_typecheck_pointer_arith_function_type
11342 : diag::ext_gnu_ptr_func_arith)
11343 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11344 << 0 /* one pointer, so only one type */
11345 << Pointer->getSourceRange();
11346}
11347
11348/// Emit error if Operand is incomplete pointer type
11349///
11350/// \returns True if pointer has incomplete type
11351static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11352 Expr *Operand) {
11353 QualType ResType = Operand->getType();
11354 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11355 ResType = ResAtomicType->getValueType();
11356
11357 assert(ResType->isAnyPointerType() && !ResType->isDependentType())(static_cast <bool> (ResType->isAnyPointerType() &&
!ResType->isDependentType()) ? void (0) : __assert_fail (
"ResType->isAnyPointerType() && !ResType->isDependentType()"
, "clang/lib/Sema/SemaExpr.cpp", 11357, __extension__ __PRETTY_FUNCTION__
))
;
11358 QualType PointeeTy = ResType->getPointeeType();
11359 return S.RequireCompleteSizedType(
11360 Loc, PointeeTy,
11361 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11362 Operand->getSourceRange());
11363}
11364
11365/// Check the validity of an arithmetic pointer operand.
11366///
11367/// If the operand has pointer type, this code will check for pointer types
11368/// which are invalid in arithmetic operations. These will be diagnosed
11369/// appropriately, including whether or not the use is supported as an
11370/// extension.
11371///
11372/// \returns True when the operand is valid to use (even if as an extension).
11373static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11374 Expr *Operand) {
11375 QualType ResType = Operand->getType();
11376 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11377 ResType = ResAtomicType->getValueType();
11378
11379 if (!ResType->isAnyPointerType()) return true;
11380
11381 QualType PointeeTy = ResType->getPointeeType();
11382 if (PointeeTy->isVoidType()) {
11383 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11384 return !S.getLangOpts().CPlusPlus;
11385 }
11386 if (PointeeTy->isFunctionType()) {
11387 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11388 return !S.getLangOpts().CPlusPlus;
11389 }
11390
11391 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11392
11393 return true;
11394}
11395
11396/// Check the validity of a binary arithmetic operation w.r.t. pointer
11397/// operands.
11398///
11399/// This routine will diagnose any invalid arithmetic on pointer operands much
11400/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11401/// for emitting a single diagnostic even for operations where both LHS and RHS
11402/// are (potentially problematic) pointers.
11403///
11404/// \returns True when the operand is valid to use (even if as an extension).
11405static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11406 Expr *LHSExpr, Expr *RHSExpr) {
11407 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11408 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11409 if (!isLHSPointer && !isRHSPointer) return true;
11410
11411 QualType LHSPointeeTy, RHSPointeeTy;
11412 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11413 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11414
11415 // if both are pointers check if operation is valid wrt address spaces
11416 if (isLHSPointer && isRHSPointer) {
11417 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
11418 S.Diag(Loc,
11419 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11420 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11421 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11422 return false;
11423 }
11424 }
11425
11426 // Check for arithmetic on pointers to incomplete types.
11427 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11428 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11429 if (isLHSVoidPtr || isRHSVoidPtr) {
11430 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11431 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11432 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11433
11434 return !S.getLangOpts().CPlusPlus;
11435 }
11436
11437 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11438 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11439 if (isLHSFuncPtr || isRHSFuncPtr) {
11440 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11441 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11442 RHSExpr);
11443 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11444
11445 return !S.getLangOpts().CPlusPlus;
11446 }
11447
11448 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11449 return false;
11450 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11451 return false;
11452
11453 return true;
11454}
11455
11456/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11457/// literal.
11458static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11459 Expr *LHSExpr, Expr *RHSExpr) {
11460 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11461 Expr* IndexExpr = RHSExpr;
11462 if (!StrExpr) {
11463 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11464 IndexExpr = LHSExpr;
11465 }
11466
11467 bool IsStringPlusInt = StrExpr &&
11468 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11469 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11470 return;
11471
11472 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11473 Self.Diag(OpLoc, diag::warn_string_plus_int)
11474 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11475
11476 // Only print a fixit for "str" + int, not for int + "str".
11477 if (IndexExpr == RHSExpr) {
11478 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11479 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11480 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11481 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11482 << FixItHint::CreateInsertion(EndLoc, "]");
11483 } else
11484 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11485}
11486
11487/// Emit a warning when adding a char literal to a string.
11488static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11489 Expr *LHSExpr, Expr *RHSExpr) {
11490 const Expr *StringRefExpr = LHSExpr;
11491 const CharacterLiteral *CharExpr =
11492 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11493
11494 if (!CharExpr) {
11495 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11496 StringRefExpr = RHSExpr;
11497 }
11498
11499 if (!CharExpr || !StringRefExpr)
11500 return;
11501
11502 const QualType StringType = StringRefExpr->getType();
11503
11504 // Return if not a PointerType.
11505 if (!StringType->isAnyPointerType())
11506 return;
11507
11508 // Return if not a CharacterType.
11509 if (!StringType->getPointeeType()->isAnyCharacterType())
11510 return;
11511
11512 ASTContext &Ctx = Self.getASTContext();
11513 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11514
11515 const QualType CharType = CharExpr->getType();
11516 if (!CharType->isAnyCharacterType() &&
11517 CharType->isIntegerType() &&
11518 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11519 Self.Diag(OpLoc, diag::warn_string_plus_char)
11520 << DiagRange << Ctx.CharTy;
11521 } else {
11522 Self.Diag(OpLoc, diag::warn_string_plus_char)
11523 << DiagRange << CharExpr->getType();
11524 }
11525
11526 // Only print a fixit for str + char, not for char + str.
11527 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11528 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11529 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11530 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11531 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11532 << FixItHint::CreateInsertion(EndLoc, "]");
11533 } else {
11534 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11535 }
11536}
11537
11538/// Emit error when two pointers are incompatible.
11539static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11540 Expr *LHSExpr, Expr *RHSExpr) {
11541 assert(LHSExpr->getType()->isAnyPointerType())(static_cast <bool> (LHSExpr->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11541, __extension__ __PRETTY_FUNCTION__
))
;
11542 assert(RHSExpr->getType()->isAnyPointerType())(static_cast <bool> (RHSExpr->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11542, __extension__ __PRETTY_FUNCTION__
))
;
11543 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11544 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11545 << RHSExpr->getSourceRange();
11546}
11547
11548// C99 6.5.6
11549QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11550 SourceLocation Loc, BinaryOperatorKind Opc,
11551 QualType* CompLHSTy) {
11552 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11553
11554 if (LHS.get()->getType()->isVectorType() ||
11555 RHS.get()->getType()->isVectorType()) {
11556 QualType compType =
11557 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11558 /*AllowBothBool*/ getLangOpts().AltiVec,
11559 /*AllowBoolConversions*/ getLangOpts().ZVector,
11560 /*AllowBooleanOperation*/ false,
11561 /*ReportInvalid*/ true);
11562 if (CompLHSTy) *CompLHSTy = compType;
11563 return compType;
11564 }
11565
11566 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11567 RHS.get()->getType()->isVLSTBuiltinType()) {
11568 QualType compType =
11569 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11570 if (CompLHSTy)
11571 *CompLHSTy = compType;
11572 return compType;
11573 }
11574
11575 if (LHS.get()->getType()->isConstantMatrixType() ||
11576 RHS.get()->getType()->isConstantMatrixType()) {
11577 QualType compType =
11578 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11579 if (CompLHSTy)
11580 *CompLHSTy = compType;
11581 return compType;
11582 }
11583
11584 QualType compType = UsualArithmeticConversions(
11585 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11586 if (LHS.isInvalid() || RHS.isInvalid())
11587 return QualType();
11588
11589 // Diagnose "string literal" '+' int and string '+' "char literal".
11590 if (Opc == BO_Add) {
11591 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11592 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11593 }
11594
11595 // handle the common case first (both operands are arithmetic).
11596 if (!compType.isNull() && compType->isArithmeticType()) {
11597 if (CompLHSTy) *CompLHSTy = compType;
11598 return compType;
11599 }
11600
11601 // Type-checking. Ultimately the pointer's going to be in PExp;
11602 // note that we bias towards the LHS being the pointer.
11603 Expr *PExp = LHS.get(), *IExp = RHS.get();
11604
11605 bool isObjCPointer;
11606 if (PExp->getType()->isPointerType()) {
11607 isObjCPointer = false;
11608 } else if (PExp->getType()->isObjCObjectPointerType()) {
11609 isObjCPointer = true;
11610 } else {
11611 std::swap(PExp, IExp);
11612 if (PExp->getType()->isPointerType()) {
11613 isObjCPointer = false;
11614 } else if (PExp->getType()->isObjCObjectPointerType()) {
11615 isObjCPointer = true;
11616 } else {
11617 return InvalidOperands(Loc, LHS, RHS);
11618 }
11619 }
11620 assert(PExp->getType()->isAnyPointerType())(static_cast <bool> (PExp->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("PExp->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11620, __extension__ __PRETTY_FUNCTION__
))
;
11621
11622 if (!IExp->getType()->isIntegerType())
11623 return InvalidOperands(Loc, LHS, RHS);
11624
11625 // Adding to a null pointer results in undefined behavior.
11626 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11627 Context, Expr::NPC_ValueDependentIsNotNull)) {
11628 // In C++ adding zero to a null pointer is defined.
11629 Expr::EvalResult KnownVal;
11630 if (!getLangOpts().CPlusPlus ||
11631 (!IExp->isValueDependent() &&
11632 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11633 KnownVal.Val.getInt() != 0))) {
11634 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11635 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11636 Context, BO_Add, PExp, IExp);
11637 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11638 }
11639 }
11640
11641 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11642 return QualType();
11643
11644 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11645 return QualType();
11646
11647 // Check array bounds for pointer arithemtic
11648 CheckArrayAccess(PExp, IExp);
11649
11650 if (CompLHSTy) {
11651 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11652 if (LHSTy.isNull()) {
11653 LHSTy = LHS.get()->getType();
11654 if (Context.isPromotableIntegerType(LHSTy))
11655 LHSTy = Context.getPromotedIntegerType(LHSTy);
11656 }
11657 *CompLHSTy = LHSTy;
11658 }
11659
11660 return PExp->getType();
11661}
11662
11663// C99 6.5.6
11664QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11665 SourceLocation Loc,
11666 QualType* CompLHSTy) {
11667 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11668
11669 if (LHS.get()->getType()->isVectorType() ||
11670 RHS.get()->getType()->isVectorType()) {
11671 QualType compType =
11672 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11673 /*AllowBothBool*/ getLangOpts().AltiVec,
11674 /*AllowBoolConversions*/ getLangOpts().ZVector,
11675 /*AllowBooleanOperation*/ false,
11676 /*ReportInvalid*/ true);
11677 if (CompLHSTy) *CompLHSTy = compType;
11678 return compType;
11679 }
11680
11681 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11682 RHS.get()->getType()->isVLSTBuiltinType()) {
11683 QualType compType =
11684 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11685 if (CompLHSTy)
11686 *CompLHSTy = compType;
11687 return compType;
11688 }
11689
11690 if (LHS.get()->getType()->isConstantMatrixType() ||
11691 RHS.get()->getType()->isConstantMatrixType()) {
11692 QualType compType =
11693 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11694 if (CompLHSTy)
11695 *CompLHSTy = compType;
11696 return compType;
11697 }
11698
11699 QualType compType = UsualArithmeticConversions(
11700 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11701 if (LHS.isInvalid() || RHS.isInvalid())
11702 return QualType();
11703
11704 // Enforce type constraints: C99 6.5.6p3.
11705
11706 // Handle the common case first (both operands are arithmetic).
11707 if (!compType.isNull() && compType->isArithmeticType()) {
11708 if (CompLHSTy) *CompLHSTy = compType;
11709 return compType;
11710 }
11711
11712 // Either ptr - int or ptr - ptr.
11713 if (LHS.get()->getType()->isAnyPointerType()) {
11714 QualType lpointee = LHS.get()->getType()->getPointeeType();
11715
11716 // Diagnose bad cases where we step over interface counts.
11717 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11718 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11719 return QualType();
11720
11721 // The result type of a pointer-int computation is the pointer type.
11722 if (RHS.get()->getType()->isIntegerType()) {
11723 // Subtracting from a null pointer should produce a warning.
11724 // The last argument to the diagnose call says this doesn't match the
11725 // GNU int-to-pointer idiom.
11726 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11727 Expr::NPC_ValueDependentIsNotNull)) {
11728 // In C++ adding zero to a null pointer is defined.
11729 Expr::EvalResult KnownVal;
11730 if (!getLangOpts().CPlusPlus ||
11731 (!RHS.get()->isValueDependent() &&
11732 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11733 KnownVal.Val.getInt() != 0))) {
11734 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11735 }
11736 }
11737
11738 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11739 return QualType();
11740
11741 // Check array bounds for pointer arithemtic
11742 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11743 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11744
11745 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11746 return LHS.get()->getType();
11747 }
11748
11749 // Handle pointer-pointer subtractions.
11750 if (const PointerType *RHSPTy
11751 = RHS.get()->getType()->getAs<PointerType>()) {
11752 QualType rpointee = RHSPTy->getPointeeType();
11753
11754 if (getLangOpts().CPlusPlus) {
11755 // Pointee types must be the same: C++ [expr.add]
11756 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11757 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11758 }
11759 } else {
11760 // Pointee types must be compatible C99 6.5.6p3
11761 if (!Context.typesAreCompatible(
11762 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11763 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11764 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11765 return QualType();
11766 }
11767 }
11768
11769 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11770 LHS.get(), RHS.get()))
11771 return QualType();
11772
11773 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11774 Context, Expr::NPC_ValueDependentIsNotNull);
11775 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11776 Context, Expr::NPC_ValueDependentIsNotNull);
11777
11778 // Subtracting nullptr or from nullptr is suspect
11779 if (LHSIsNullPtr)
11780 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11781 if (RHSIsNullPtr)
11782 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11783
11784 // The pointee type may have zero size. As an extension, a structure or
11785 // union may have zero size or an array may have zero length. In this
11786 // case subtraction does not make sense.
11787 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11788 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11789 if (ElementSize.isZero()) {
11790 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11791 << rpointee.getUnqualifiedType()
11792 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11793 }
11794 }
11795
11796 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11797 return Context.getPointerDiffType();
11798 }
11799 }
11800
11801 return InvalidOperands(Loc, LHS, RHS);
11802}
11803
11804static bool isScopedEnumerationType(QualType T) {
11805 if (const EnumType *ET = T->getAs<EnumType>())
11806 return ET->getDecl()->isScoped();
11807 return false;
11808}
11809
11810static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11811 SourceLocation Loc, BinaryOperatorKind Opc,
11812 QualType LHSType) {
11813 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11814 // so skip remaining warnings as we don't want to modify values within Sema.
11815 if (S.getLangOpts().OpenCL)
11816 return;
11817
11818 // Check right/shifter operand
11819 Expr::EvalResult RHSResult;
11820 if (RHS.get()->isValueDependent() ||
11821 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11822 return;
11823 llvm::APSInt Right = RHSResult.Val.getInt();
11824
11825 if (Right.isNegative()) {
11826 S.DiagRuntimeBehavior(Loc, RHS.get(),
11827 S.PDiag(diag::warn_shift_negative)
11828 << RHS.get()->getSourceRange());
11829 return;
11830 }
11831
11832 QualType LHSExprType = LHS.get()->getType();
11833 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11834 if (LHSExprType->isBitIntType())
11835 LeftSize = S.Context.getIntWidth(LHSExprType);
11836 else if (LHSExprType->isFixedPointType()) {
11837 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11838 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11839 }
11840 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11841 if (Right.uge(LeftBits)) {
11842 S.DiagRuntimeBehavior(Loc, RHS.get(),
11843 S.PDiag(diag::warn_shift_gt_typewidth)
11844 << RHS.get()->getSourceRange());
11845 return;
11846 }
11847
11848 // FIXME: We probably need to handle fixed point types specially here.
11849 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11850 return;
11851
11852 // When left shifting an ICE which is signed, we can check for overflow which
11853 // according to C++ standards prior to C++2a has undefined behavior
11854 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11855 // more than the maximum value representable in the result type, so never
11856 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11857 // expression is still probably a bug.)
11858 Expr::EvalResult LHSResult;
11859 if (LHS.get()->isValueDependent() ||
11860 LHSType->hasUnsignedIntegerRepresentation() ||
11861 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11862 return;
11863 llvm::APSInt Left = LHSResult.Val.getInt();
11864
11865 // Don't warn if signed overflow is defined, then all the rest of the
11866 // diagnostics will not be triggered because the behavior is defined.
11867 // Also don't warn in C++20 mode (and newer), as signed left shifts
11868 // always wrap and never overflow.
11869 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11870 return;
11871
11872 // If LHS does not have a non-negative value then, the
11873 // behavior is undefined before C++2a. Warn about it.
11874 if (Left.isNegative()) {
11875 S.DiagRuntimeBehavior(Loc, LHS.get(),
11876 S.PDiag(diag::warn_shift_lhs_negative)
11877 << LHS.get()->getSourceRange());
11878 return;
11879 }
11880
11881 llvm::APInt ResultBits =
11882 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11883 if (LeftBits.uge(ResultBits))
11884 return;
11885 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11886 Result = Result.shl(Right);
11887
11888 // Print the bit representation of the signed integer as an unsigned
11889 // hexadecimal number.
11890 SmallString<40> HexResult;
11891 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11892
11893 // If we are only missing a sign bit, this is less likely to result in actual
11894 // bugs -- if the result is cast back to an unsigned type, it will have the
11895 // expected value. Thus we place this behind a different warning that can be
11896 // turned off separately if needed.
11897 if (LeftBits == ResultBits - 1) {
11898 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11899 << HexResult << LHSType
11900 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11901 return;
11902 }
11903
11904 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11905 << HexResult.str() << Result.getSignificantBits() << LHSType
11906 << Left.getBitWidth() << LHS.get()->getSourceRange()
11907 << RHS.get()->getSourceRange();
11908}
11909
11910/// Return the resulting type when a vector is shifted
11911/// by a scalar or vector shift amount.
11912static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11913 SourceLocation Loc, bool IsCompAssign) {
11914 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11915 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11916 !LHS.get()->getType()->isVectorType()) {
11917 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11918 << RHS.get()->getType() << LHS.get()->getType()
11919 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11920 return QualType();
11921 }
11922
11923 if (!IsCompAssign) {
11924 LHS = S.UsualUnaryConversions(LHS.get());
11925 if (LHS.isInvalid()) return QualType();
11926 }
11927
11928 RHS = S.UsualUnaryConversions(RHS.get());
11929 if (RHS.isInvalid()) return QualType();
11930
11931 QualType LHSType = LHS.get()->getType();
11932 // Note that LHS might be a scalar because the routine calls not only in
11933 // OpenCL case.
11934 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11935 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11936
11937 // Note that RHS might not be a vector.
11938 QualType RHSType = RHS.get()->getType();
11939 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11940 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11941
11942 // Do not allow shifts for boolean vectors.
11943 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11944 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11945 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11946 << LHS.get()->getType() << RHS.get()->getType()
11947 << LHS.get()->getSourceRange();
11948 return QualType();
11949 }
11950
11951 // The operands need to be integers.
11952 if (!LHSEleType->isIntegerType()) {
11953 S.Diag(Loc, diag::err_typecheck_expect_int)
11954 << LHS.get()->getType() << LHS.get()->getSourceRange();
11955 return QualType();
11956 }
11957
11958 if (!RHSEleType->isIntegerType()) {
11959 S.Diag(Loc, diag::err_typecheck_expect_int)
11960 << RHS.get()->getType() << RHS.get()->getSourceRange();
11961 return QualType();
11962 }
11963
11964 if (!LHSVecTy) {
11965 assert(RHSVecTy)(static_cast <bool> (RHSVecTy) ? void (0) : __assert_fail
("RHSVecTy", "clang/lib/Sema/SemaExpr.cpp", 11965, __extension__
__PRETTY_FUNCTION__))
;
11966 if (IsCompAssign)
11967 return RHSType;
11968 if (LHSEleType != RHSEleType) {
11969 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11970 LHSEleType = RHSEleType;
11971 }
11972 QualType VecTy =
11973 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11974 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11975 LHSType = VecTy;
11976 } else if (RHSVecTy) {
11977 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11978 // are applied component-wise. So if RHS is a vector, then ensure
11979 // that the number of elements is the same as LHS...
11980 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11981 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11982 << LHS.get()->getType() << RHS.get()->getType()
11983 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11984 return QualType();
11985 }
11986 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11987 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11988 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11989 if (LHSBT != RHSBT &&
11990 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11991 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11992 << LHS.get()->getType() << RHS.get()->getType()
11993 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11994 }
11995 }
11996 } else {
11997 // ...else expand RHS to match the number of elements in LHS.
11998 QualType VecTy =
11999 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12000 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12001 }
12002
12003 return LHSType;
12004}
12005
12006static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12007 ExprResult &RHS, SourceLocation Loc,
12008 bool IsCompAssign) {
12009 if (!IsCompAssign) {
12010 LHS = S.UsualUnaryConversions(LHS.get());
12011 if (LHS.isInvalid())
12012 return QualType();
12013 }
12014
12015 RHS = S.UsualUnaryConversions(RHS.get());
12016 if (RHS.isInvalid())
12017 return QualType();
12018
12019 QualType LHSType = LHS.get()->getType();
12020 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12021 QualType LHSEleType = LHSType->isVLSTBuiltinType()
12022 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12023 : LHSType;
12024
12025 // Note that RHS might not be a vector
12026 QualType RHSType = RHS.get()->getType();
12027 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
12028 QualType RHSEleType = RHSType->isVLSTBuiltinType()
12029 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12030 : RHSType;
12031
12032 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12033 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12034 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12035 << LHSType << RHSType << LHS.get()->getSourceRange();
12036 return QualType();
12037 }
12038
12039 if (!LHSEleType->isIntegerType()) {
12040 S.Diag(Loc, diag::err_typecheck_expect_int)
12041 << LHS.get()->getType() << LHS.get()->getSourceRange();
12042 return QualType();
12043 }
12044
12045 if (!RHSEleType->isIntegerType()) {
12046 S.Diag(Loc, diag::err_typecheck_expect_int)
12047 << RHS.get()->getType() << RHS.get()->getSourceRange();
12048 return QualType();
12049 }
12050
12051 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
12052 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12053 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12054 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12055 << LHSType << RHSType << LHS.get()->getSourceRange()
12056 << RHS.get()->getSourceRange();
12057 return QualType();
12058 }
12059
12060 if (!LHSType->isVLSTBuiltinType()) {
12061 assert(RHSType->isVLSTBuiltinType())(static_cast <bool> (RHSType->isVLSTBuiltinType()) ?
void (0) : __assert_fail ("RHSType->isVLSTBuiltinType()",
"clang/lib/Sema/SemaExpr.cpp", 12061, __extension__ __PRETTY_FUNCTION__
))
;
12062 if (IsCompAssign)
12063 return RHSType;
12064 if (LHSEleType != RHSEleType) {
12065 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12066 LHSEleType = RHSEleType;
12067 }
12068 const llvm::ElementCount VecSize =
12069 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12070 QualType VecTy =
12071 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12072 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12073 LHSType = VecTy;
12074 } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) {
12075 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12076 S.Context.getTypeSize(LHSBuiltinTy)) {
12077 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12078 << LHSType << RHSType << LHS.get()->getSourceRange()
12079 << RHS.get()->getSourceRange();
12080 return QualType();
12081 }
12082 } else {
12083 const llvm::ElementCount VecSize =
12084 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12085 if (LHSEleType != RHSEleType) {
12086 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12087 RHSEleType = LHSEleType;
12088 }
12089 QualType VecTy =
12090 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12091 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12092 }
12093
12094 return LHSType;
12095}
12096
12097// C99 6.5.7
12098QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12099 SourceLocation Loc, BinaryOperatorKind Opc,
12100 bool IsCompAssign) {
12101 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12102
12103 // Vector shifts promote their scalar inputs to vector type.
12104 if (LHS.get()->getType()->isVectorType() ||
12105 RHS.get()->getType()->isVectorType()) {
12106 if (LangOpts.ZVector) {
12107 // The shift operators for the z vector extensions work basically
12108 // like general shifts, except that neither the LHS nor the RHS is
12109 // allowed to be a "vector bool".
12110 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12111 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
12112 return InvalidOperands(Loc, LHS, RHS);
12113 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12114 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
12115 return InvalidOperands(Loc, LHS, RHS);
12116 }
12117 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12118 }
12119
12120 if (LHS.get()->getType()->isVLSTBuiltinType() ||
12121 RHS.get()->getType()->isVLSTBuiltinType())
12122 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12123
12124 // Shifts don't perform usual arithmetic conversions, they just do integer
12125 // promotions on each operand. C99 6.5.7p3
12126
12127 // For the LHS, do usual unary conversions, but then reset them away
12128 // if this is a compound assignment.
12129 ExprResult OldLHS = LHS;
12130 LHS = UsualUnaryConversions(LHS.get());
12131 if (LHS.isInvalid())
12132 return QualType();
12133 QualType LHSType = LHS.get()->getType();
12134 if (IsCompAssign) LHS = OldLHS;
12135
12136 // The RHS is simpler.
12137 RHS = UsualUnaryConversions(RHS.get());
12138 if (RHS.isInvalid())
12139 return QualType();
12140 QualType RHSType = RHS.get()->getType();
12141
12142 // C99 6.5.7p2: Each of the operands shall have integer type.
12143 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12144 if ((!LHSType->isFixedPointOrIntegerType() &&
12145 !LHSType->hasIntegerRepresentation()) ||
12146 !RHSType->hasIntegerRepresentation())
12147 return InvalidOperands(Loc, LHS, RHS);
12148
12149 // C++0x: Don't allow scoped enums. FIXME: Use something better than
12150 // hasIntegerRepresentation() above instead of this.
12151 if (isScopedEnumerationType(LHSType) ||
12152 isScopedEnumerationType(RHSType)) {
12153 return InvalidOperands(Loc, LHS, RHS);
12154 }
12155 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12156
12157 // "The type of the result is that of the promoted left operand."
12158 return LHSType;
12159}
12160
12161/// Diagnose bad pointer comparisons.
12162static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12163 ExprResult &LHS, ExprResult &RHS,
12164 bool IsError) {
12165 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12166 : diag::ext_typecheck_comparison_of_distinct_pointers)
12167 << LHS.get()->getType() << RHS.get()->getType()
12168 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12169}
12170
12171/// Returns false if the pointers are converted to a composite type,
12172/// true otherwise.
12173static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12174 ExprResult &LHS, ExprResult &RHS) {
12175 // C++ [expr.rel]p2:
12176 // [...] Pointer conversions (4.10) and qualification
12177 // conversions (4.4) are performed on pointer operands (or on
12178 // a pointer operand and a null pointer constant) to bring
12179 // them to their composite pointer type. [...]
12180 //
12181 // C++ [expr.eq]p1 uses the same notion for (in)equality
12182 // comparisons of pointers.
12183
12184 QualType LHSType = LHS.get()->getType();
12185 QualType RHSType = RHS.get()->getType();
12186 assert(LHSType->isPointerType() || RHSType->isPointerType() ||(static_cast <bool> (LHSType->isPointerType() || RHSType
->isPointerType() || LHSType->isMemberPointerType() || RHSType
->isMemberPointerType()) ? void (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 12187, __extension__ __PRETTY_FUNCTION__
))
12187 LHSType->isMemberPointerType() || RHSType->isMemberPointerType())(static_cast <bool> (LHSType->isPointerType() || RHSType
->isPointerType() || LHSType->isMemberPointerType() || RHSType
->isMemberPointerType()) ? void (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 12187, __extension__ __PRETTY_FUNCTION__
))
;
12188
12189 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12190 if (T.isNull()) {
12191 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12192 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12193 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12194 else
12195 S.InvalidOperands(Loc, LHS, RHS);
12196 return true;
12197 }
12198
12199 return false;
12200}
12201
12202static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12203 ExprResult &LHS,
12204 ExprResult &RHS,
12205 bool IsError) {
12206 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12207 : diag::ext_typecheck_comparison_of_fptr_to_void)
12208 << LHS.get()->getType() << RHS.get()->getType()
12209 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12210}
12211
12212static bool isObjCObjectLiteral(ExprResult &E) {
12213 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12214 case Stmt::ObjCArrayLiteralClass:
12215 case Stmt::ObjCDictionaryLiteralClass:
12216 case Stmt::ObjCStringLiteralClass:
12217 case Stmt::ObjCBoxedExprClass:
12218 return true;
12219 default:
12220 // Note that ObjCBoolLiteral is NOT an object literal!
12221 return false;
12222 }
12223}
12224
12225static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12226 const ObjCObjectPointerType *Type =
12227 LHS->getType()->getAs<ObjCObjectPointerType>();
12228
12229 // If this is not actually an Objective-C object, bail out.
12230 if (!Type)
12231 return false;
12232
12233 // Get the LHS object's interface type.
12234 QualType InterfaceType = Type->getPointeeType();
12235
12236 // If the RHS isn't an Objective-C object, bail out.
12237 if (!RHS->getType()->isObjCObjectPointerType())
12238 return false;
12239
12240 // Try to find the -isEqual: method.
12241 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
12242 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
12243 InterfaceType,
12244 /*IsInstance=*/true);
12245 if (!Method) {
12246 if (Type->isObjCIdType()) {
12247 // For 'id', just check the global pool.
12248 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
12249 /*receiverId=*/true);
12250 } else {
12251 // Check protocols.
12252 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
12253 /*IsInstance=*/true);
12254 }
12255 }
12256
12257 if (!Method)
12258 return false;
12259
12260 QualType T = Method->parameters()[0]->getType();
12261 if (!T->isObjCObjectPointerType())
12262 return false;
12263
12264 QualType R = Method->getReturnType();
12265 if (!R->isScalarType())
12266 return false;
12267
12268 return true;
12269}
12270
12271Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
12272 FromE = FromE->IgnoreParenImpCasts();
12273 switch (FromE->getStmtClass()) {
12274 default:
12275 break;
12276 case Stmt::ObjCStringLiteralClass:
12277 // "string literal"
12278 return LK_String;
12279 case Stmt::ObjCArrayLiteralClass:
12280 // "array literal"
12281 return LK_Array;
12282 case Stmt::ObjCDictionaryLiteralClass:
12283 // "dictionary literal"
12284 return LK_Dictionary;
12285 case Stmt::BlockExprClass:
12286 return LK_Block;
12287 case Stmt::ObjCBoxedExprClass: {
12288 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
12289 switch (Inner->getStmtClass()) {
12290 case Stmt::IntegerLiteralClass:
12291 case Stmt::FloatingLiteralClass:
12292 case Stmt::CharacterLiteralClass:
12293 case Stmt::ObjCBoolLiteralExprClass:
12294 case Stmt::CXXBoolLiteralExprClass:
12295 // "numeric literal"
12296 return LK_Numeric;
12297 case Stmt::ImplicitCastExprClass: {
12298 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
12299 // Boolean literals can be represented by implicit casts.
12300 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
12301 return LK_Numeric;
12302 break;
12303 }
12304 default:
12305 break;
12306 }
12307 return LK_Boxed;
12308 }
12309 }
12310 return LK_None;
12311}
12312
12313static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12314 ExprResult &LHS, ExprResult &RHS,
12315 BinaryOperator::Opcode Opc){
12316 Expr *Literal;
12317 Expr *Other;
12318 if (isObjCObjectLiteral(LHS)) {
12319 Literal = LHS.get();
12320 Other = RHS.get();
12321 } else {
12322 Literal = RHS.get();
12323 Other = LHS.get();
12324 }
12325
12326 // Don't warn on comparisons against nil.
12327 Other = Other->IgnoreParenCasts();
12328 if (Other->isNullPointerConstant(S.getASTContext(),
12329 Expr::NPC_ValueDependentIsNotNull))
12330 return;
12331
12332 // This should be kept in sync with warn_objc_literal_comparison.
12333 // LK_String should always be after the other literals, since it has its own
12334 // warning flag.
12335 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
12336 assert(LiteralKind != Sema::LK_Block)(static_cast <bool> (LiteralKind != Sema::LK_Block) ? void
(0) : __assert_fail ("LiteralKind != Sema::LK_Block", "clang/lib/Sema/SemaExpr.cpp"
, 12336, __extension__ __PRETTY_FUNCTION__))
;
12337 if (LiteralKind == Sema::LK_None) {
12338 llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind"
, "clang/lib/Sema/SemaExpr.cpp", 12338)
;
12339 }
12340
12341 if (LiteralKind == Sema::LK_String)
12342 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12343 << Literal->getSourceRange();
12344 else
12345 S.Diag(Loc, diag::warn_objc_literal_comparison)
12346 << LiteralKind << Literal->getSourceRange();
12347
12348 if (BinaryOperator::isEqualityOp(Opc) &&
12349 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12350 SourceLocation Start = LHS.get()->getBeginLoc();
12351 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
12352 CharSourceRange OpRange =
12353 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12354
12355 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12356 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12357 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12358 << FixItHint::CreateInsertion(End, "]");
12359 }
12360}
12361
12362/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12363static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12364 ExprResult &RHS, SourceLocation Loc,
12365 BinaryOperatorKind Opc) {
12366 // Check that left hand side is !something.
12367 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12368 if (!UO || UO->getOpcode() != UO_LNot) return;
12369
12370 // Only check if the right hand side is non-bool arithmetic type.
12371 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12372
12373 // Make sure that the something in !something is not bool.
12374 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12375 if (SubExpr->isKnownToHaveBooleanValue()) return;
12376
12377 // Emit warning.
12378 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12379 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12380 << Loc << IsBitwiseOp;
12381
12382 // First note suggest !(x < y)
12383 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12384 SourceLocation FirstClose = RHS.get()->getEndLoc();
12385 FirstClose = S.getLocForEndOfToken(FirstClose);
12386 if (FirstClose.isInvalid())
12387 FirstOpen = SourceLocation();
12388 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12389 << IsBitwiseOp
12390 << FixItHint::CreateInsertion(FirstOpen, "(")
12391 << FixItHint::CreateInsertion(FirstClose, ")");
12392
12393 // Second note suggests (!x) < y
12394 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12395 SourceLocation SecondClose = LHS.get()->getEndLoc();
12396 SecondClose = S.getLocForEndOfToken(SecondClose);
12397 if (SecondClose.isInvalid())
12398 SecondOpen = SourceLocation();
12399 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12400 << FixItHint::CreateInsertion(SecondOpen, "(")
12401 << FixItHint::CreateInsertion(SecondClose, ")");
12402}
12403
12404// Returns true if E refers to a non-weak array.
12405static bool checkForArray(const Expr *E) {
12406 const ValueDecl *D = nullptr;
12407 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12408 D = DR->getDecl();
12409 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12410 if (Mem->isImplicitAccess())
12411 D = Mem->getMemberDecl();
12412 }
12413 if (!D)
12414 return false;
12415 return D->getType()->isArrayType() && !D->isWeak();
12416}
12417
12418/// Diagnose some forms of syntactically-obvious tautological comparison.
12419static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12420 Expr *LHS, Expr *RHS,
12421 BinaryOperatorKind Opc) {
12422 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12423 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12424
12425 QualType LHSType = LHS->getType();
12426 QualType RHSType = RHS->getType();
12427 if (LHSType->hasFloatingRepresentation() ||
12428 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12429 S.inTemplateInstantiation())
12430 return;
12431
12432 // Comparisons between two array types are ill-formed for operator<=>, so
12433 // we shouldn't emit any additional warnings about it.
12434 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12435 return;
12436
12437 // For non-floating point types, check for self-comparisons of the form
12438 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12439 // often indicate logic errors in the program.
12440 //
12441 // NOTE: Don't warn about comparison expressions resulting from macro
12442 // expansion. Also don't warn about comparisons which are only self
12443 // comparisons within a template instantiation. The warnings should catch
12444 // obvious cases in the definition of the template anyways. The idea is to
12445 // warn when the typed comparison operator will always evaluate to the same
12446 // result.
12447
12448 // Used for indexing into %select in warn_comparison_always
12449 enum {
12450 AlwaysConstant,
12451 AlwaysTrue,
12452 AlwaysFalse,
12453 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12454 };
12455
12456 // C++2a [depr.array.comp]:
12457 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12458 // operands of array type are deprecated.
12459 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12460 RHSStripped->getType()->isArrayType()) {
12461 S.Diag(Loc, diag::warn_depr_array_comparison)
12462 << LHS->getSourceRange() << RHS->getSourceRange()
12463 << LHSStripped->getType() << RHSStripped->getType();
12464 // Carry on to produce the tautological comparison warning, if this
12465 // expression is potentially-evaluated, we can resolve the array to a
12466 // non-weak declaration, and so on.
12467 }
12468
12469 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12470 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12471 unsigned Result;
12472 switch (Opc) {
12473 case BO_EQ:
12474 case BO_LE:
12475 case BO_GE:
12476 Result = AlwaysTrue;
12477 break;
12478 case BO_NE:
12479 case BO_LT:
12480 case BO_GT:
12481 Result = AlwaysFalse;
12482 break;
12483 case BO_Cmp:
12484 Result = AlwaysEqual;
12485 break;
12486 default:
12487 Result = AlwaysConstant;
12488 break;
12489 }
12490 S.DiagRuntimeBehavior(Loc, nullptr,
12491 S.PDiag(diag::warn_comparison_always)
12492 << 0 /*self-comparison*/
12493 << Result);
12494 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12495 // What is it always going to evaluate to?
12496 unsigned Result;
12497 switch (Opc) {
12498 case BO_EQ: // e.g. array1 == array2
12499 Result = AlwaysFalse;
12500 break;
12501 case BO_NE: // e.g. array1 != array2
12502 Result = AlwaysTrue;
12503 break;
12504 default: // e.g. array1 <= array2
12505 // The best we can say is 'a constant'
12506 Result = AlwaysConstant;
12507 break;
12508 }
12509 S.DiagRuntimeBehavior(Loc, nullptr,
12510 S.PDiag(diag::warn_comparison_always)
12511 << 1 /*array comparison*/
12512 << Result);
12513 }
12514 }
12515
12516 if (isa<CastExpr>(LHSStripped))
12517 LHSStripped = LHSStripped->IgnoreParenCasts();
12518 if (isa<CastExpr>(RHSStripped))
12519 RHSStripped = RHSStripped->IgnoreParenCasts();
12520
12521 // Warn about comparisons against a string constant (unless the other
12522 // operand is null); the user probably wants string comparison function.
12523 Expr *LiteralString = nullptr;
12524 Expr *LiteralStringStripped = nullptr;
12525 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12526 !RHSStripped->isNullPointerConstant(S.Context,
12527 Expr::NPC_ValueDependentIsNull)) {
12528 LiteralString = LHS;
12529 LiteralStringStripped = LHSStripped;
12530 } else if ((isa<StringLiteral>(RHSStripped) ||
12531 isa<ObjCEncodeExpr>(RHSStripped)) &&
12532 !LHSStripped->isNullPointerConstant(S.Context,
12533 Expr::NPC_ValueDependentIsNull)) {
12534 LiteralString = RHS;
12535 LiteralStringStripped = RHSStripped;
12536 }
12537
12538 if (LiteralString) {
12539 S.DiagRuntimeBehavior(Loc, nullptr,
12540 S.PDiag(diag::warn_stringcompare)
12541 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12542 << LiteralString->getSourceRange());
12543 }
12544}
12545
12546static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12547 switch (CK) {
12548 default: {
12549#ifndef NDEBUG
12550 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12551 << "\n";
12552#endif
12553 llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "clang/lib/Sema/SemaExpr.cpp"
, 12553)
;
12554 }
12555 case CK_UserDefinedConversion:
12556 return ICK_Identity;
12557 case CK_LValueToRValue:
12558 return ICK_Lvalue_To_Rvalue;
12559 case CK_ArrayToPointerDecay:
12560 return ICK_Array_To_Pointer;
12561 case CK_FunctionToPointerDecay:
12562 return ICK_Function_To_Pointer;
12563 case CK_IntegralCast:
12564 return ICK_Integral_Conversion;
12565 case CK_FloatingCast:
12566 return ICK_Floating_Conversion;
12567 case CK_IntegralToFloating:
12568 case CK_FloatingToIntegral:
12569 return ICK_Floating_Integral;
12570 case CK_IntegralComplexCast:
12571 case CK_FloatingComplexCast:
12572 case CK_FloatingComplexToIntegralComplex:
12573 case CK_IntegralComplexToFloatingComplex:
12574 return ICK_Complex_Conversion;
12575 case CK_FloatingComplexToReal:
12576 case CK_FloatingRealToComplex:
12577 case CK_IntegralComplexToReal:
12578 case CK_IntegralRealToComplex:
12579 return ICK_Complex_Real;
12580 }
12581}
12582
12583static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12584 QualType FromType,
12585 SourceLocation Loc) {
12586 // Check for a narrowing implicit conversion.
12587 StandardConversionSequence SCS;
12588 SCS.setAsIdentityConversion();
12589 SCS.setToType(0, FromType);
12590 SCS.setToType(1, ToType);
12591 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12592 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12593
12594 APValue PreNarrowingValue;
12595 QualType PreNarrowingType;
12596 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12597 PreNarrowingType,
12598 /*IgnoreFloatToIntegralConversion*/ true)) {
12599 case NK_Dependent_Narrowing:
12600 // Implicit conversion to a narrower type, but the expression is
12601 // value-dependent so we can't tell whether it's actually narrowing.
12602 case NK_Not_Narrowing:
12603 return false;
12604
12605 case NK_Constant_Narrowing:
12606 // Implicit conversion to a narrower type, and the value is not a constant
12607 // expression.
12608 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12609 << /*Constant*/ 1
12610 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12611 return true;
12612
12613 case NK_Variable_Narrowing:
12614 // Implicit conversion to a narrower type, and the value is not a constant
12615 // expression.
12616 case NK_Type_Narrowing:
12617 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12618 << /*Constant*/ 0 << FromType << ToType;
12619 // TODO: It's not a constant expression, but what if the user intended it
12620 // to be? Can we produce notes to help them figure out why it isn't?
12621 return true;
12622 }
12623 llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch",
"clang/lib/Sema/SemaExpr.cpp", 12623)
;
12624}
12625
12626static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12627 ExprResult &LHS,
12628 ExprResult &RHS,
12629 SourceLocation Loc) {
12630 QualType LHSType = LHS.get()->getType();
12631 QualType RHSType = RHS.get()->getType();
12632 // Dig out the original argument type and expression before implicit casts
12633 // were applied. These are the types/expressions we need to check the
12634 // [expr.spaceship] requirements against.
12635 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12636 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12637 QualType LHSStrippedType = LHSStripped.get()->getType();
12638 QualType RHSStrippedType = RHSStripped.get()->getType();
12639
12640 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12641 // other is not, the program is ill-formed.
12642 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12643 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12644 return QualType();
12645 }
12646
12647 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12648 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12649 RHSStrippedType->isEnumeralType();
12650 if (NumEnumArgs == 1) {
12651 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12652 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12653 if (OtherTy->hasFloatingRepresentation()) {
12654 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12655 return QualType();
12656 }
12657 }
12658 if (NumEnumArgs == 2) {
12659 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12660 // type E, the operator yields the result of converting the operands
12661 // to the underlying type of E and applying <=> to the converted operands.
12662 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12663 S.InvalidOperands(Loc, LHS, RHS);
12664 return QualType();
12665 }
12666 QualType IntType =
12667 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12668 assert(IntType->isArithmeticType())(static_cast <bool> (IntType->isArithmeticType()) ? void
(0) : __assert_fail ("IntType->isArithmeticType()", "clang/lib/Sema/SemaExpr.cpp"
, 12668, __extension__ __PRETTY_FUNCTION__))
;
12669
12670 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12671 // promote the boolean type, and all other promotable integer types, to
12672 // avoid this.
12673 if (S.Context.isPromotableIntegerType(IntType))
12674 IntType = S.Context.getPromotedIntegerType(IntType);
12675
12676 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12677 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12678 LHSType = RHSType = IntType;
12679 }
12680
12681 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12682 // usual arithmetic conversions are applied to the operands.
12683 QualType Type =
12684 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12685 if (LHS.isInvalid() || RHS.isInvalid())
12686 return QualType();
12687 if (Type.isNull())
12688 return S.InvalidOperands(Loc, LHS, RHS);
12689
12690 std::optional<ComparisonCategoryType> CCT =
12691 getComparisonCategoryForBuiltinCmp(Type);
12692 if (!CCT)
12693 return S.InvalidOperands(Loc, LHS, RHS);
12694
12695 bool HasNarrowing = checkThreeWayNarrowingConversion(
12696 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12697 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12698 RHS.get()->getBeginLoc());
12699 if (HasNarrowing)
12700 return QualType();
12701
12702 assert(!Type.isNull() && "composite type for <=> has not been set")(static_cast <bool> (!Type.isNull() && "composite type for <=> has not been set"
) ? void (0) : __assert_fail ("!Type.isNull() && \"composite type for <=> has not been set\""
, "clang/lib/Sema/SemaExpr.cpp", 12702, __extension__ __PRETTY_FUNCTION__
))
;
12703
12704 return S.CheckComparisonCategoryType(
12705 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12706}
12707
12708static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12709 ExprResult &RHS,
12710 SourceLocation Loc,
12711 BinaryOperatorKind Opc) {
12712 if (Opc == BO_Cmp)
12713 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12714
12715 // C99 6.5.8p3 / C99 6.5.9p4
12716 QualType Type =
12717 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12718 if (LHS.isInvalid() || RHS.isInvalid())
12719 return QualType();
12720 if (Type.isNull())
12721 return S.InvalidOperands(Loc, LHS, RHS);
12722 assert(Type->isArithmeticType() || Type->isEnumeralType())(static_cast <bool> (Type->isArithmeticType() || Type
->isEnumeralType()) ? void (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()"
, "clang/lib/Sema/SemaExpr.cpp", 12722, __extension__ __PRETTY_FUNCTION__
))
;
12723
12724 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12725 return S.InvalidOperands(Loc, LHS, RHS);
12726
12727 // Check for comparisons of floating point operands using != and ==.
12728 if (Type->hasFloatingRepresentation())
12729 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12730
12731 // The result of comparisons is 'bool' in C++, 'int' in C.
12732 return S.Context.getLogicalOperationType();
12733}
12734
12735void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12736 if (!NullE.get()->getType()->isAnyPointerType())
12737 return;
12738 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12739 if (!E.get()->getType()->isAnyPointerType() &&
12740 E.get()->isNullPointerConstant(Context,
12741 Expr::NPC_ValueDependentIsNotNull) ==
12742 Expr::NPCK_ZeroExpression) {
12743 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12744 if (CL->getValue() == 0)
12745 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12746 << NullValue
12747 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12748 NullValue ? "NULL" : "(void *)0");
12749 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12750 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12751 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12752 if (T == Context.CharTy)
12753 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12754 << NullValue
12755 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12756 NullValue ? "NULL" : "(void *)0");
12757 }
12758 }
12759}
12760
12761// C99 6.5.8, C++ [expr.rel]
12762QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12763 SourceLocation Loc,
12764 BinaryOperatorKind Opc) {
12765 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12766 bool IsThreeWay = Opc == BO_Cmp;
12767 bool IsOrdered = IsRelational || IsThreeWay;
12768 auto IsAnyPointerType = [](ExprResult E) {
12769 QualType Ty = E.get()->getType();
12770 return Ty->isPointerType() || Ty->isMemberPointerType();
12771 };
12772
12773 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12774 // type, array-to-pointer, ..., conversions are performed on both operands to
12775 // bring them to their composite type.
12776 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12777 // any type-related checks.
12778 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12779 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12780 if (LHS.isInvalid())
12781 return QualType();
12782 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12783 if (RHS.isInvalid())
12784 return QualType();
12785 } else {
12786 LHS = DefaultLvalueConversion(LHS.get());
12787 if (LHS.isInvalid())
12788 return QualType();
12789 RHS = DefaultLvalueConversion(RHS.get());
12790 if (RHS.isInvalid())
12791 return QualType();
12792 }
12793
12794 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12795 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12796 CheckPtrComparisonWithNullChar(LHS, RHS);
12797 CheckPtrComparisonWithNullChar(RHS, LHS);
12798 }
12799
12800 // Handle vector comparisons separately.
12801 if (LHS.get()->getType()->isVectorType() ||
12802 RHS.get()->getType()->isVectorType())
12803 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12804
12805 if (LHS.get()->getType()->isVLSTBuiltinType() ||
12806 RHS.get()->getType()->isVLSTBuiltinType())
12807 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12808
12809 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12810 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12811
12812 QualType LHSType = LHS.get()->getType();
12813 QualType RHSType = RHS.get()->getType();
12814 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12815 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12816 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12817
12818 const Expr::NullPointerConstantKind LHSNullKind =
12819 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12820 const Expr::NullPointerConstantKind RHSNullKind =
12821 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12822 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12823 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12824
12825 auto computeResultTy = [&]() {
12826 if (Opc != BO_Cmp)
12827 return Context.getLogicalOperationType();
12828 assert(getLangOpts().CPlusPlus)(static_cast <bool> (getLangOpts().CPlusPlus) ? void (0
) : __assert_fail ("getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 12828, __extension__ __PRETTY_FUNCTION__))
;
12829 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))(static_cast <bool> (Context.hasSameType(LHS.get()->
getType(), RHS.get()->getType())) ? void (0) : __assert_fail
("Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())"
, "clang/lib/Sema/SemaExpr.cpp", 12829, __extension__ __PRETTY_FUNCTION__
))
;
12830
12831 QualType CompositeTy = LHS.get()->getType();
12832 assert(!CompositeTy->isReferenceType())(static_cast <bool> (!CompositeTy->isReferenceType()
) ? void (0) : __assert_fail ("!CompositeTy->isReferenceType()"
, "clang/lib/Sema/SemaExpr.cpp", 12832, __extension__ __PRETTY_FUNCTION__
))
;
12833
12834 std::optional<ComparisonCategoryType> CCT =
12835 getComparisonCategoryForBuiltinCmp(CompositeTy);
12836 if (!CCT)
12837 return InvalidOperands(Loc, LHS, RHS);
12838
12839 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12840 // P0946R0: Comparisons between a null pointer constant and an object
12841 // pointer result in std::strong_equality, which is ill-formed under
12842 // P1959R0.
12843 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12844 << (LHSIsNull ? LHS.get()->getSourceRange()
12845 : RHS.get()->getSourceRange());
12846 return QualType();
12847 }
12848
12849 return CheckComparisonCategoryType(
12850 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12851 };
12852
12853 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12854 bool IsEquality = Opc == BO_EQ;
12855 if (RHSIsNull)
12856 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12857 RHS.get()->getSourceRange());
12858 else
12859 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12860 LHS.get()->getSourceRange());
12861 }
12862
12863 if (IsOrdered && LHSType->isFunctionPointerType() &&
12864 RHSType->isFunctionPointerType()) {
12865 // Valid unless a relational comparison of function pointers
12866 bool IsError = Opc == BO_Cmp;
12867 auto DiagID =
12868 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12869 : getLangOpts().CPlusPlus
12870 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12871 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12872 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12873 << RHS.get()->getSourceRange();
12874 if (IsError)
12875 return QualType();
12876 }
12877
12878 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12879 (RHSType->isIntegerType() && !RHSIsNull)) {
12880 // Skip normal pointer conversion checks in this case; we have better
12881 // diagnostics for this below.
12882 } else if (getLangOpts().CPlusPlus) {
12883 // Equality comparison of a function pointer to a void pointer is invalid,
12884 // but we allow it as an extension.
12885 // FIXME: If we really want to allow this, should it be part of composite
12886 // pointer type computation so it works in conditionals too?
12887 if (!IsOrdered &&
12888 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12889 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12890 // This is a gcc extension compatibility comparison.
12891 // In a SFINAE context, we treat this as a hard error to maintain
12892 // conformance with the C++ standard.
12893 diagnoseFunctionPointerToVoidComparison(
12894 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12895
12896 if (isSFINAEContext())
12897 return QualType();
12898
12899 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12900 return computeResultTy();
12901 }
12902
12903 // C++ [expr.eq]p2:
12904 // If at least one operand is a pointer [...] bring them to their
12905 // composite pointer type.
12906 // C++ [expr.spaceship]p6
12907 // If at least one of the operands is of pointer type, [...] bring them
12908 // to their composite pointer type.
12909 // C++ [expr.rel]p2:
12910 // If both operands are pointers, [...] bring them to their composite
12911 // pointer type.
12912 // For <=>, the only valid non-pointer types are arrays and functions, and
12913 // we already decayed those, so this is really the same as the relational
12914 // comparison rule.
12915 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12916 (IsOrdered ? 2 : 1) &&
12917 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12918 RHSType->isObjCObjectPointerType()))) {
12919 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12920 return QualType();
12921 return computeResultTy();
12922 }
12923 } else if (LHSType->isPointerType() &&
12924 RHSType->isPointerType()) { // C99 6.5.8p2
12925 // All of the following pointer-related warnings are GCC extensions, except
12926 // when handling null pointer constants.
12927 QualType LCanPointeeTy =
12928 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12929 QualType RCanPointeeTy =
12930 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12931
12932 // C99 6.5.9p2 and C99 6.5.8p2
12933 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12934 RCanPointeeTy.getUnqualifiedType())) {
12935 if (IsRelational) {
12936 // Pointers both need to point to complete or incomplete types
12937 if ((LCanPointeeTy->isIncompleteType() !=
12938 RCanPointeeTy->isIncompleteType()) &&
12939 !getLangOpts().C11) {
12940 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12941 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12942 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12943 << RCanPointeeTy->isIncompleteType();
12944 }
12945 }
12946 } else if (!IsRelational &&
12947 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12948 // Valid unless comparison between non-null pointer and function pointer
12949 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12950 && !LHSIsNull && !RHSIsNull)
12951 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12952 /*isError*/false);
12953 } else {
12954 // Invalid
12955 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12956 }
12957 if (LCanPointeeTy != RCanPointeeTy) {
12958 // Treat NULL constant as a special case in OpenCL.
12959 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12960 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12961 Diag(Loc,
12962 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12963 << LHSType << RHSType << 0 /* comparison */
12964 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12965 }
12966 }
12967 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12968 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12969 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12970 : CK_BitCast;
12971 if (LHSIsNull && !RHSIsNull)
12972 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12973 else
12974 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12975 }
12976 return computeResultTy();
12977 }
12978
12979
12980 // C++ [expr.eq]p4:
12981 // Two operands of type std::nullptr_t or one operand of type
12982 // std::nullptr_t and the other a null pointer constant compare
12983 // equal.
12984 // C2x 6.5.9p5:
12985 // If both operands have type nullptr_t or one operand has type nullptr_t
12986 // and the other is a null pointer constant, they compare equal.
12987 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12988 if (LHSType->isNullPtrType()) {
12989 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12990 return computeResultTy();
12991 }
12992 if (RHSType->isNullPtrType()) {
12993 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12994 return computeResultTy();
12995 }
12996 }
12997
12998 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12999 // C2x 6.5.9p6:
13000 // Otherwise, at least one operand is a pointer. If one is a pointer and
13001 // the other is a null pointer constant, the null pointer constant is
13002 // converted to the type of the pointer.
13003 if (LHSIsNull && RHSType->isPointerType()) {
13004 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13005 return computeResultTy();
13006 }
13007 if (RHSIsNull && LHSType->isPointerType()) {
13008 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13009 return computeResultTy();
13010 }
13011 }
13012
13013 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13014 // These aren't covered by the composite pointer type rules.
13015 if (!IsOrdered && RHSType->isNullPtrType() &&
13016 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13017 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13018 return computeResultTy();
13019 }
13020 if (!IsOrdered && LHSType->isNullPtrType() &&
13021 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13022 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13023 return computeResultTy();
13024 }
13025
13026 if (getLangOpts().CPlusPlus) {
13027 if (IsRelational &&
13028 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13029 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13030 // HACK: Relational comparison of nullptr_t against a pointer type is
13031 // invalid per DR583, but we allow it within std::less<> and friends,
13032 // since otherwise common uses of it break.
13033 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13034 // friends to have std::nullptr_t overload candidates.
13035 DeclContext *DC = CurContext;
13036 if (isa<FunctionDecl>(DC))
13037 DC = DC->getParent();
13038 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13039 if (CTSD->isInStdNamespace() &&
13040 llvm::StringSwitch<bool>(CTSD->getName())
13041 .Cases("less", "less_equal", "greater", "greater_equal", true)
13042 .Default(false)) {
13043 if (RHSType->isNullPtrType())
13044 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13045 else
13046 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13047 return computeResultTy();
13048 }
13049 }
13050 }
13051
13052 // C++ [expr.eq]p2:
13053 // If at least one operand is a pointer to member, [...] bring them to
13054 // their composite pointer type.
13055 if (!IsOrdered &&
13056 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13057 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13058 return QualType();
13059 else
13060 return computeResultTy();
13061 }
13062 }
13063
13064 // Handle block pointer types.
13065 if (!IsOrdered && LHSType->isBlockPointerType() &&
13066 RHSType->isBlockPointerType()) {
13067 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13068 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13069
13070 if (!LHSIsNull && !RHSIsNull &&
13071 !Context.typesAreCompatible(lpointee, rpointee)) {
13072 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13073 << LHSType << RHSType << LHS.get()->getSourceRange()
13074 << RHS.get()->getSourceRange();
13075 }
13076 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13077 return computeResultTy();
13078 }
13079
13080 // Allow block pointers to be compared with null pointer constants.
13081 if (!IsOrdered
13082 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13083 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13084 if (!LHSIsNull && !RHSIsNull) {
13085 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13086 ->getPointeeType()->isVoidType())
13087 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13088 ->getPointeeType()->isVoidType())))
13089 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13090 << LHSType << RHSType << LHS.get()->getSourceRange()
13091 << RHS.get()->getSourceRange();
13092 }
13093 if (LHSIsNull && !RHSIsNull)
13094 LHS = ImpCastExprToType(LHS.get(), RHSType,
13095 RHSType->isPointerType() ? CK_BitCast
13096 : CK_AnyPointerToBlockPointerCast);
13097 else
13098 RHS = ImpCastExprToType(RHS.get(), LHSType,
13099 LHSType->isPointerType() ? CK_BitCast
13100 : CK_AnyPointerToBlockPointerCast);
13101 return computeResultTy();
13102 }
13103
13104 if (LHSType->isObjCObjectPointerType() ||
13105 RHSType->isObjCObjectPointerType()) {
13106 const PointerType *LPT = LHSType->getAs<PointerType>();
13107 const PointerType *RPT = RHSType->getAs<PointerType>();
13108 if (LPT || RPT) {
13109 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13110 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13111
13112 if (!LPtrToVoid && !RPtrToVoid &&
13113 !Context.typesAreCompatible(LHSType, RHSType)) {
13114 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13115 /*isError*/false);
13116 }
13117 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13118 // the RHS, but we have test coverage for this behavior.
13119 // FIXME: Consider using convertPointersToCompositeType in C++.
13120 if (LHSIsNull && !RHSIsNull) {
13121 Expr *E = LHS.get();
13122 if (getLangOpts().ObjCAutoRefCount)
13123 CheckObjCConversion(SourceRange(), RHSType, E,
13124 CCK_ImplicitConversion);
13125 LHS = ImpCastExprToType(E, RHSType,
13126 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13127 }
13128 else {
13129 Expr *E = RHS.get();
13130 if (getLangOpts().ObjCAutoRefCount)
13131 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
13132 /*Diagnose=*/true,
13133 /*DiagnoseCFAudited=*/false, Opc);
13134 RHS = ImpCastExprToType(E, LHSType,
13135 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13136 }
13137 return computeResultTy();
13138 }
13139 if (LHSType->isObjCObjectPointerType() &&
13140 RHSType->isObjCObjectPointerType()) {
13141 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13142 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13143 /*isError*/false);
13144 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
13145 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13146
13147 if (LHSIsNull && !RHSIsNull)
13148 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13149 else
13150 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13151 return computeResultTy();
13152 }
13153
13154 if (!IsOrdered && LHSType->isBlockPointerType() &&
13155 RHSType->isBlockCompatibleObjCPointerType(Context)) {
13156 LHS = ImpCastExprToType(LHS.get(), RHSType,
13157 CK_BlockPointerToObjCPointerCast);
13158 return computeResultTy();
13159 } else if (!IsOrdered &&
13160 LHSType->isBlockCompatibleObjCPointerType(Context) &&
13161 RHSType->isBlockPointerType()) {
13162 RHS = ImpCastExprToType(RHS.get(), LHSType,
13163 CK_BlockPointerToObjCPointerCast);
13164 return computeResultTy();
13165 }
13166 }
13167 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13168 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13169 unsigned DiagID = 0;
13170 bool isError = false;
13171 if (LangOpts.DebuggerSupport) {
13172 // Under a debugger, allow the comparison of pointers to integers,
13173 // since users tend to want to compare addresses.
13174 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13175 (RHSIsNull && RHSType->isIntegerType())) {
13176 if (IsOrdered) {
13177 isError = getLangOpts().CPlusPlus;
13178 DiagID =
13179 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13180 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13181 }
13182 } else if (getLangOpts().CPlusPlus) {
13183 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13184 isError = true;
13185 } else if (IsOrdered)
13186 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13187 else
13188 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13189
13190 if (DiagID) {
13191 Diag(Loc, DiagID)
13192 << LHSType << RHSType << LHS.get()->getSourceRange()
13193 << RHS.get()->getSourceRange();
13194 if (isError)
13195 return QualType();
13196 }
13197
13198 if (LHSType->isIntegerType())
13199 LHS = ImpCastExprToType(LHS.get(), RHSType,
13200 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13201 else
13202 RHS = ImpCastExprToType(RHS.get(), LHSType,
13203 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13204 return computeResultTy();
13205 }
13206
13207 // Handle block pointers.
13208 if (!IsOrdered && RHSIsNull
13209 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13210 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13211 return computeResultTy();
13212 }
13213 if (!IsOrdered && LHSIsNull
13214 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13215 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13216 return computeResultTy();
13217 }
13218
13219 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13220 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13221 return computeResultTy();
13222 }
13223
13224 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13225 return computeResultTy();
13226 }
13227
13228 if (LHSIsNull && RHSType->isQueueT()) {
13229 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13230 return computeResultTy();
13231 }
13232
13233 if (LHSType->isQueueT() && RHSIsNull) {
13234 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13235 return computeResultTy();
13236 }
13237 }
13238
13239 return InvalidOperands(Loc, LHS, RHS);
13240}
13241
13242// Return a signed ext_vector_type that is of identical size and number of
13243// elements. For floating point vectors, return an integer type of identical
13244// size and number of elements. In the non ext_vector_type case, search from
13245// the largest type to the smallest type to avoid cases where long long == long,
13246// where long gets picked over long long.
13247QualType Sema::GetSignedVectorType(QualType V) {
13248 const VectorType *VTy = V->castAs<VectorType>();
13249 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13250
13251 if (isa<ExtVectorType>(VTy)) {
13252 if (VTy->isExtVectorBoolType())
13253 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13254 if (TypeSize == Context.getTypeSize(Context.CharTy))
13255 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13256 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13257 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13258 if (TypeSize == Context.getTypeSize(Context.IntTy))
13259 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13260 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13261 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13262 if (TypeSize == Context.getTypeSize(Context.LongTy))
13263 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13264 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&(static_cast <bool> (TypeSize == Context.getTypeSize(Context
.LongLongTy) && "Unhandled vector element size in vector compare"
) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\""
, "clang/lib/Sema/SemaExpr.cpp", 13265, __extension__ __PRETTY_FUNCTION__
))
13265 "Unhandled vector element size in vector compare")(static_cast <bool> (TypeSize == Context.getTypeSize(Context
.LongLongTy) && "Unhandled vector element size in vector compare"
) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\""
, "clang/lib/Sema/SemaExpr.cpp", 13265, __extension__ __PRETTY_FUNCTION__
))
;
13266 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13267 }
13268
13269 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13270 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13271 VectorType::GenericVector);
13272 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13273 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13274 VectorType::GenericVector);
13275 if (TypeSize == Context.getTypeSize(Context.LongTy))
13276 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13277 VectorType::GenericVector);
13278 if (TypeSize == Context.getTypeSize(Context.IntTy))
13279 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13280 VectorType::GenericVector);
13281 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13282 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13283 VectorType::GenericVector);
13284 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&(static_cast <bool> (TypeSize == Context.getTypeSize(Context
.CharTy) && "Unhandled vector element size in vector compare"
) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\""
, "clang/lib/Sema/SemaExpr.cpp", 13285, __extension__ __PRETTY_FUNCTION__
))
13285 "Unhandled vector element size in vector compare")(static_cast <bool> (TypeSize == Context.getTypeSize(Context
.CharTy) && "Unhandled vector element size in vector compare"
) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\""
, "clang/lib/Sema/SemaExpr.cpp", 13285, __extension__ __PRETTY_FUNCTION__
))
;
13286 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13287 VectorType::GenericVector);
13288}
13289
13290QualType Sema::GetSignedSizelessVectorType(QualType V) {
13291 const BuiltinType *VTy = V->castAs<BuiltinType>();
13292 assert(VTy->isSizelessBuiltinType() && "expected sizeless type")(static_cast <bool> (VTy->isSizelessBuiltinType() &&
"expected sizeless type") ? void (0) : __assert_fail ("VTy->isSizelessBuiltinType() && \"expected sizeless type\""
, "clang/lib/Sema/SemaExpr.cpp", 13292, __extension__ __PRETTY_FUNCTION__
))
;
13293
13294 const QualType ETy = V->getSveEltType(Context);
13295 const auto TypeSize = Context.getTypeSize(ETy);
13296
13297 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13298 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13299 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13300}
13301
13302/// CheckVectorCompareOperands - vector comparisons are a clang extension that
13303/// operates on extended vector types. Instead of producing an IntTy result,
13304/// like a scalar comparison, a vector comparison produces a vector of integer
13305/// types.
13306QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13307 SourceLocation Loc,
13308 BinaryOperatorKind Opc) {
13309 if (Opc == BO_Cmp) {
13310 Diag(Loc, diag::err_three_way_vector_comparison);
13311 return QualType();
13312 }
13313
13314 // Check to make sure we're operating on vectors of the same type and width,
13315 // Allowing one side to be a scalar of element type.
13316 QualType vType =
13317 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13318 /*AllowBothBool*/ true,
13319 /*AllowBoolConversions*/ getLangOpts().ZVector,
13320 /*AllowBooleanOperation*/ true,
13321 /*ReportInvalid*/ true);
13322 if (vType.isNull())
13323 return vType;
13324
13325 QualType LHSType = LHS.get()->getType();
13326
13327 // Determine the return type of a vector compare. By default clang will return
13328 // a scalar for all vector compares except vector bool and vector pixel.
13329 // With the gcc compiler we will always return a vector type and with the xl
13330 // compiler we will always return a scalar type. This switch allows choosing
13331 // which behavior is prefered.
13332 if (getLangOpts().AltiVec) {
13333 switch (getLangOpts().getAltivecSrcCompat()) {
13334 case LangOptions::AltivecSrcCompatKind::Mixed:
13335 // If AltiVec, the comparison results in a numeric type, i.e.
13336 // bool for C++, int for C
13337 if (vType->castAs<VectorType>()->getVectorKind() ==
13338 VectorType::AltiVecVector)
13339 return Context.getLogicalOperationType();
13340 else
13341 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13342 break;
13343 case LangOptions::AltivecSrcCompatKind::GCC:
13344 // For GCC we always return the vector type.
13345 break;
13346 case LangOptions::AltivecSrcCompatKind::XL:
13347 return Context.getLogicalOperationType();
13348 break;
13349 }
13350 }
13351
13352 // For non-floating point types, check for self-comparisons of the form
13353 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13354 // often indicate logic errors in the program.
13355 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13356
13357 // Check for comparisons of floating point operands using != and ==.
13358 if (LHSType->hasFloatingRepresentation()) {
13359 assert(RHS.get()->getType()->hasFloatingRepresentation())(static_cast <bool> (RHS.get()->getType()->hasFloatingRepresentation
()) ? void (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()"
, "clang/lib/Sema/SemaExpr.cpp", 13359, __extension__ __PRETTY_FUNCTION__
))
;
13360 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13361 }
13362
13363 // Return a signed type for the vector.
13364 return GetSignedVectorType(vType);
13365}
13366
13367QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13368 ExprResult &RHS,
13369 SourceLocation Loc,
13370 BinaryOperatorKind Opc) {
13371 if (Opc == BO_Cmp) {
13372 Diag(Loc, diag::err_three_way_vector_comparison);
13373 return QualType();
13374 }
13375
13376 // Check to make sure we're operating on vectors of the same type and width,
13377 // Allowing one side to be a scalar of element type.
13378 QualType vType = CheckSizelessVectorOperands(
13379 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
13380
13381 if (vType.isNull())
13382 return vType;
13383
13384 QualType LHSType = LHS.get()->getType();
13385
13386 // For non-floating point types, check for self-comparisons of the form
13387 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13388 // often indicate logic errors in the program.
13389 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13390
13391 // Check for comparisons of floating point operands using != and ==.
13392 if (LHSType->hasFloatingRepresentation()) {
13393 assert(RHS.get()->getType()->hasFloatingRepresentation())(static_cast <bool> (RHS.get()->getType()->hasFloatingRepresentation
()) ? void (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()"
, "clang/lib/Sema/SemaExpr.cpp", 13393, __extension__ __PRETTY_FUNCTION__
))
;
13394 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13395 }
13396
13397 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13398 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13399
13400 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13401 RHSBuiltinTy->isSVEBool())
13402 return LHSType;
13403
13404 // Return a signed type for the vector.
13405 return GetSignedSizelessVectorType(vType);
13406}
13407
13408static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13409 const ExprResult &XorRHS,
13410 const SourceLocation Loc) {
13411 // Do not diagnose macros.
13412 if (Loc.isMacroID())
13413 return;
13414
13415 // Do not diagnose if both LHS and RHS are macros.
13416 if (XorLHS.get()->getExprLoc().isMacroID() &&
13417 XorRHS.get()->getExprLoc().isMacroID())
13418 return;
13419
13420 bool Negative = false;
13421 bool ExplicitPlus = false;
13422 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13423 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13424
13425 if (!LHSInt)
13426 return;
13427 if (!RHSInt) {
13428 // Check negative literals.
13429 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13430 UnaryOperatorKind Opc = UO->getOpcode();
13431 if (Opc != UO_Minus && Opc != UO_Plus)
13432 return;
13433 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13434 if (!RHSInt)
13435 return;
13436 Negative = (Opc == UO_Minus);
13437 ExplicitPlus = !Negative;
13438 } else {
13439 return;
13440 }
13441 }
13442
13443 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13444 llvm::APInt RightSideValue = RHSInt->getValue();
13445 if (LeftSideValue != 2 && LeftSideValue != 10)
13446 return;
13447
13448 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13449 return;
13450
13451 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13452 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13453 llvm::StringRef ExprStr =
13454 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
13455
13456 CharSourceRange XorRange =
13457 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
13458 llvm::StringRef XorStr =
13459 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
13460 // Do not diagnose if xor keyword/macro is used.
13461 if (XorStr == "xor")
13462 return;
13463
13464 std::string LHSStr = std::string(Lexer::getSourceText(
13465 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13466 S.getSourceManager(), S.getLangOpts()));
13467 std::string RHSStr = std::string(Lexer::getSourceText(
13468 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13469 S.getSourceManager(), S.getLangOpts()));
13470
13471 if (Negative) {
13472 RightSideValue = -RightSideValue;
13473 RHSStr = "-" + RHSStr;
13474 } else if (ExplicitPlus) {
13475 RHSStr = "+" + RHSStr;
13476 }
13477
13478 StringRef LHSStrRef = LHSStr;
13479 StringRef RHSStrRef = RHSStr;
13480 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13481 // literals.
13482 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
13483 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
13484 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
13485 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
13486 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
13487 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
13488 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13489 return;
13490
13491 bool SuggestXor =
13492 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13493 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13494 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13495 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13496 std::string SuggestedExpr = "1 << " + RHSStr;
13497 bool Overflow = false;
13498 llvm::APInt One = (LeftSideValue - 1);
13499 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13500 if (Overflow) {
13501 if (RightSideIntValue < 64)
13502 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13503 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13504 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13505 else if (RightSideIntValue == 64)
13506 S.Diag(Loc, diag::warn_xor_used_as_pow)
13507 << ExprStr << toString(XorValue, 10, true);
13508 else
13509 return;
13510 } else {
13511 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13512 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13513 << toString(PowValue, 10, true)
13514 << FixItHint::CreateReplacement(
13515 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13516 }
13517
13518 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13519 << ("0x2 ^ " + RHSStr) << SuggestXor;
13520 } else if (LeftSideValue == 10) {
13521 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13522 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13523 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13524 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13525 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13526 << ("0xA ^ " + RHSStr) << SuggestXor;
13527 }
13528}
13529
13530QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13531 SourceLocation Loc) {
13532 // Ensure that either both operands are of the same vector type, or
13533 // one operand is of a vector type and the other is of its element type.
13534 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13535 /*AllowBothBool*/ true,
13536 /*AllowBoolConversions*/ false,
13537 /*AllowBooleanOperation*/ false,
13538 /*ReportInvalid*/ false);
13539 if (vType.isNull())
13540 return InvalidOperands(Loc, LHS, RHS);
13541 if (getLangOpts().OpenCL &&
13542 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13543 vType->hasFloatingRepresentation())
13544 return InvalidOperands(Loc, LHS, RHS);
13545 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13546 // usage of the logical operators && and || with vectors in C. This
13547 // check could be notionally dropped.
13548 if (!getLangOpts().CPlusPlus &&
13549 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13550 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13551
13552 return GetSignedVectorType(LHS.get()->getType());
13553}
13554
13555QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13556 SourceLocation Loc,
13557 bool IsCompAssign) {
13558 if (!IsCompAssign) {
13559 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13560 if (LHS.isInvalid())
13561 return QualType();
13562 }
13563 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13564 if (RHS.isInvalid())
13565 return QualType();
13566
13567 // For conversion purposes, we ignore any qualifiers.
13568 // For example, "const float" and "float" are equivalent.
13569 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13570 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13571
13572 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13573 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13574 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast <bool> ((LHSMatType || RHSMatType) &&
"At least one operand must be a matrix") ? void (0) : __assert_fail
("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\""
, "clang/lib/Sema/SemaExpr.cpp", 13574, __extension__ __PRETTY_FUNCTION__
))
;
13575
13576 if (Context.hasSameType(LHSType, RHSType))
13577 return Context.getCommonSugaredType(LHSType, RHSType);
13578
13579 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13580 // case we have to return InvalidOperands.
13581 ExprResult OriginalLHS = LHS;
13582 ExprResult OriginalRHS = RHS;
13583 if (LHSMatType && !RHSMatType) {
13584 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13585 if (!RHS.isInvalid())
13586 return LHSType;
13587
13588 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13589 }
13590
13591 if (!LHSMatType && RHSMatType) {
13592 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13593 if (!LHS.isInvalid())
13594 return RHSType;
13595 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13596 }
13597
13598 return InvalidOperands(Loc, LHS, RHS);
13599}
13600
13601QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13602 SourceLocation Loc,
13603 bool IsCompAssign) {
13604 if (!IsCompAssign) {
13605 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13606 if (LHS.isInvalid())
13607 return QualType();
13608 }
13609 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13610 if (RHS.isInvalid())
13611 return QualType();
13612
13613 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13614 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13615 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast <bool> ((LHSMatType || RHSMatType) &&
"At least one operand must be a matrix") ? void (0) : __assert_fail
("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\""
, "clang/lib/Sema/SemaExpr.cpp", 13615, __extension__ __PRETTY_FUNCTION__
))
;
13616
13617 if (LHSMatType && RHSMatType) {
13618 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13619 return InvalidOperands(Loc, LHS, RHS);
13620
13621 if (Context.hasSameType(LHSMatType, RHSMatType))
13622 return Context.getCommonSugaredType(
13623 LHS.get()->getType().getUnqualifiedType(),
13624 RHS.get()->getType().getUnqualifiedType());
13625
13626 QualType LHSELTy = LHSMatType->getElementType(),
13627 RHSELTy = RHSMatType->getElementType();
13628 if (!Context.hasSameType(LHSELTy, RHSELTy))
13629 return InvalidOperands(Loc, LHS, RHS);
13630
13631 return Context.getConstantMatrixType(
13632 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13633 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13634 }
13635 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13636}
13637
13638static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13639 switch (Opc) {
13640 default:
13641 return false;
13642 case BO_And:
13643 case BO_AndAssign:
13644 case BO_Or:
13645 case BO_OrAssign:
13646 case BO_Xor:
13647 case BO_XorAssign:
13648 return true;
13649 }
13650}
13651
13652inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13653 SourceLocation Loc,
13654 BinaryOperatorKind Opc) {
13655 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13656
13657 bool IsCompAssign =
13658 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13659
13660 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13661
13662 if (LHS.get()->getType()->isVectorType() ||
13663 RHS.get()->getType()->isVectorType()) {
13664 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13665 RHS.get()->getType()->hasIntegerRepresentation())
13666 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13667 /*AllowBothBool*/ true,
13668 /*AllowBoolConversions*/ getLangOpts().ZVector,
13669 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13670 /*ReportInvalid*/ true);
13671 return InvalidOperands(Loc, LHS, RHS);
13672 }
13673
13674 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13675 RHS.get()->getType()->isVLSTBuiltinType()) {
13676 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13677 RHS.get()->getType()->hasIntegerRepresentation())
13678 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13679 ACK_BitwiseOp);
13680 return InvalidOperands(Loc, LHS, RHS);
13681 }
13682
13683 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13684 RHS.get()->getType()->isVLSTBuiltinType()) {
13685 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13686 RHS.get()->getType()->hasIntegerRepresentation())
13687 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13688 ACK_BitwiseOp);
13689 return InvalidOperands(Loc, LHS, RHS);
13690 }
13691
13692 if (Opc == BO_And)
13693 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13694
13695 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13696 RHS.get()->getType()->hasFloatingRepresentation())
13697 return InvalidOperands(Loc, LHS, RHS);
13698
13699 ExprResult LHSResult = LHS, RHSResult = RHS;
13700 QualType compType = UsualArithmeticConversions(
13701 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13702 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13703 return QualType();
13704 LHS = LHSResult.get();
13705 RHS = RHSResult.get();
13706
13707 if (Opc == BO_Xor)
13708 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13709
13710 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13711 return compType;
13712 return InvalidOperands(Loc, LHS, RHS);
13713}
13714
13715// C99 6.5.[13,14]
13716inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13717 SourceLocation Loc,
13718 BinaryOperatorKind Opc) {
13719 // Check vector operands differently.
13720 if (LHS.get()->getType()->isVectorType() ||
13721 RHS.get()->getType()->isVectorType())
13722 return CheckVectorLogicalOperands(LHS, RHS, Loc);
13723
13724 bool EnumConstantInBoolContext = false;
13725 for (const ExprResult &HS : {LHS, RHS}) {
13726 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13727 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13728 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13729 EnumConstantInBoolContext = true;
13730 }
13731 }
13732
13733 if (EnumConstantInBoolContext)
13734 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13735
13736 // Diagnose cases where the user write a logical and/or but probably meant a
13737 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13738 // is a constant.
13739 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13740 !LHS.get()->getType()->isBooleanType() &&
13741 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13742 // Don't warn in macros or template instantiations.
13743 !Loc.isMacroID() && !inTemplateInstantiation()) {
13744 // If the RHS can be constant folded, and if it constant folds to something
13745 // that isn't 0 or 1 (which indicate a potential logical operation that
13746 // happened to fold to true/false) then warn.
13747 // Parens on the RHS are ignored.
13748 Expr::EvalResult EVResult;
13749 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13750 llvm::APSInt Result = EVResult.Val.getInt();
13751 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13752 !RHS.get()->getExprLoc().isMacroID()) ||
13753 (Result != 0 && Result != 1)) {
13754 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13755 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13756 // Suggest replacing the logical operator with the bitwise version
13757 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13758 << (Opc == BO_LAnd ? "&" : "|")
13759 << FixItHint::CreateReplacement(
13760 SourceRange(Loc, getLocForEndOfToken(Loc)),
13761 Opc == BO_LAnd ? "&" : "|");
13762 if (Opc == BO_LAnd)
13763 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13764 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13765 << FixItHint::CreateRemoval(
13766 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13767 RHS.get()->getEndLoc()));
13768 }
13769 }
13770 }
13771
13772 if (!Context.getLangOpts().CPlusPlus) {
13773 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13774 // not operate on the built-in scalar and vector float types.
13775 if (Context.getLangOpts().OpenCL &&
13776 Context.getLangOpts().OpenCLVersion < 120) {
13777 if (LHS.get()->getType()->isFloatingType() ||
13778 RHS.get()->getType()->isFloatingType())
13779 return InvalidOperands(Loc, LHS, RHS);
13780 }
13781
13782 LHS = UsualUnaryConversions(LHS.get());
13783 if (LHS.isInvalid())
13784 return QualType();
13785
13786 RHS = UsualUnaryConversions(RHS.get());
13787 if (RHS.isInvalid())
13788 return QualType();
13789
13790 if (!LHS.get()->getType()->isScalarType() ||
13791 !RHS.get()->getType()->isScalarType())
13792 return InvalidOperands(Loc, LHS, RHS);
13793
13794 return Context.IntTy;
13795 }
13796
13797 // The following is safe because we only use this method for
13798 // non-overloadable operands.
13799
13800 // C++ [expr.log.and]p1
13801 // C++ [expr.log.or]p1
13802 // The operands are both contextually converted to type bool.
13803 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13804 if (LHSRes.isInvalid())
13805 return InvalidOperands(Loc, LHS, RHS);
13806 LHS = LHSRes;
13807
13808 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13809 if (RHSRes.isInvalid())
13810 return InvalidOperands(Loc, LHS, RHS);
13811 RHS = RHSRes;
13812
13813 // C++ [expr.log.and]p2
13814 // C++ [expr.log.or]p2
13815 // The result is a bool.
13816 return Context.BoolTy;
13817}
13818
13819static bool IsReadonlyMessage(Expr *E, Sema &S) {
13820 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13821 if (!ME) return false;
13822 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13823 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13824 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13825 if (!Base) return false;
13826 return Base->getMethodDecl() != nullptr;
13827}
13828
13829/// Is the given expression (which must be 'const') a reference to a
13830/// variable which was originally non-const, but which has become
13831/// 'const' due to being captured within a block?
13832enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13833static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13834 assert(E->isLValue() && E->getType().isConstQualified())(static_cast <bool> (E->isLValue() && E->
getType().isConstQualified()) ? void (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()"
, "clang/lib/Sema/SemaExpr.cpp", 13834, __extension__ __PRETTY_FUNCTION__
))
;
13835 E = E->IgnoreParens();
13836
13837 // Must be a reference to a declaration from an enclosing scope.
13838 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13839 if (!DRE) return NCCK_None;
13840 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13841
13842 // The declaration must be a variable which is not declared 'const'.
13843 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13844 if (!var) return NCCK_None;
13845 if (var->getType().isConstQualified()) return NCCK_None;
13846 assert(var->hasLocalStorage() && "capture added 'const' to non-local?")(static_cast <bool> (var->hasLocalStorage() &&
"capture added 'const' to non-local?") ? void (0) : __assert_fail
("var->hasLocalStorage() && \"capture added 'const' to non-local?\""
, "clang/lib/Sema/SemaExpr.cpp", 13846, __extension__ __PRETTY_FUNCTION__
))
;
13847
13848 // Decide whether the first capture was for a block or a lambda.
13849 DeclContext *DC = S.CurContext, *Prev = nullptr;
13850 // Decide whether the first capture was for a block or a lambda.
13851 while (DC) {
13852 // For init-capture, it is possible that the variable belongs to the
13853 // template pattern of the current context.
13854 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13855 if (var->isInitCapture() &&
13856 FD->getTemplateInstantiationPattern() == var->getDeclContext())
13857 break;
13858 if (DC == var->getDeclContext())
13859 break;
13860 Prev = DC;
13861 DC = DC->getParent();
13862 }
13863 // Unless we have an init-capture, we've gone one step too far.
13864 if (!var->isInitCapture())
13865 DC = Prev;
13866 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13867}
13868
13869static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13870 Ty = Ty.getNonReferenceType();
13871 if (IsDereference && Ty->isPointerType())
13872 Ty = Ty->getPointeeType();
13873 return !Ty.isConstQualified();
13874}
13875
13876// Update err_typecheck_assign_const and note_typecheck_assign_const
13877// when this enum is changed.
13878enum {
13879 ConstFunction,
13880 ConstVariable,
13881 ConstMember,
13882 ConstMethod,
13883 NestedConstMember,
13884 ConstUnknown, // Keep as last element
13885};
13886
13887/// Emit the "read-only variable not assignable" error and print notes to give
13888/// more information about why the variable is not assignable, such as pointing
13889/// to the declaration of a const variable, showing that a method is const, or
13890/// that the function is returning a const reference.
13891static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13892 SourceLocation Loc) {
13893 SourceRange ExprRange = E->getSourceRange();
13894
13895 // Only emit one error on the first const found. All other consts will emit
13896 // a note to the error.
13897 bool DiagnosticEmitted = false;
13898
13899 // Track if the current expression is the result of a dereference, and if the
13900 // next checked expression is the result of a dereference.
13901 bool IsDereference = false;
13902 bool NextIsDereference = false;
13903
13904 // Loop to process MemberExpr chains.
13905 while (true) {
13906 IsDereference = NextIsDereference;
13907
13908 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13909 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13910 NextIsDereference = ME->isArrow();
13911 const ValueDecl *VD = ME->getMemberDecl();
13912 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13913 // Mutable fields can be modified even if the class is const.
13914 if (Field->isMutable()) {
13915 assert(DiagnosticEmitted && "Expected diagnostic not emitted.")(static_cast <bool> (DiagnosticEmitted && "Expected diagnostic not emitted."
) ? void (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\""
, "clang/lib/Sema/SemaExpr.cpp", 13915, __extension__ __PRETTY_FUNCTION__
))
;
13916 break;
13917 }
13918
13919 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13920 if (!DiagnosticEmitted) {
13921 S.Diag(Loc, diag::err_typecheck_assign_const)
13922 << ExprRange << ConstMember << false /*static*/ << Field
13923 << Field->getType();
13924 DiagnosticEmitted = true;
13925 }
13926 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13927 << ConstMember << false /*static*/ << Field << Field->getType()
13928 << Field->getSourceRange();
13929 }
13930 E = ME->getBase();
13931 continue;
13932 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13933 if (VDecl->getType().isConstQualified()) {
13934 if (!DiagnosticEmitted) {
13935 S.Diag(Loc, diag::err_typecheck_assign_const)
13936 << ExprRange << ConstMember << true /*static*/ << VDecl
13937 << VDecl->getType();
13938 DiagnosticEmitted = true;
13939 }
13940 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13941 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13942 << VDecl->getSourceRange();
13943 }
13944 // Static fields do not inherit constness from parents.
13945 break;
13946 }
13947 break; // End MemberExpr
13948 } else if (const ArraySubscriptExpr *ASE =
13949 dyn_cast<ArraySubscriptExpr>(E)) {
13950 E = ASE->getBase()->IgnoreParenImpCasts();
13951 continue;
13952 } else if (const ExtVectorElementExpr *EVE =
13953 dyn_cast<ExtVectorElementExpr>(E)) {
13954 E = EVE->getBase()->IgnoreParenImpCasts();
13955 continue;
13956 }
13957 break;
13958 }
13959
13960 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13961 // Function calls
13962 const FunctionDecl *FD = CE->getDirectCallee();
13963 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13964 if (!DiagnosticEmitted) {
13965 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13966 << ConstFunction << FD;
13967 DiagnosticEmitted = true;
13968 }
13969 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13970 diag::note_typecheck_assign_const)
13971 << ConstFunction << FD << FD->getReturnType()
13972 << FD->getReturnTypeSourceRange();
13973 }
13974 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13975 // Point to variable declaration.
13976 if (const ValueDecl *VD = DRE->getDecl()) {
13977 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13978 if (!DiagnosticEmitted) {
13979 S.Diag(Loc, diag::err_typecheck_assign_const)
13980 << ExprRange << ConstVariable << VD << VD->getType();
13981 DiagnosticEmitted = true;
13982 }
13983 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13984 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13985 }
13986 }
13987 } else if (isa<CXXThisExpr>(E)) {
13988 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13989 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13990 if (MD->isConst()) {
13991 if (!DiagnosticEmitted) {
13992 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13993 << ConstMethod << MD;
13994 DiagnosticEmitted = true;
13995 }
13996 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13997 << ConstMethod << MD << MD->getSourceRange();
13998 }
13999 }
14000 }
14001 }
14002
14003 if (DiagnosticEmitted)
14004 return;
14005
14006 // Can't determine a more specific message, so display the generic error.
14007 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14008}
14009
14010enum OriginalExprKind {
14011 OEK_Variable,
14012 OEK_Member,
14013 OEK_LValue
14014};
14015
14016static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14017 const RecordType *Ty,
14018 SourceLocation Loc, SourceRange Range,
14019 OriginalExprKind OEK,
14020 bool &DiagnosticEmitted) {
14021 std::vector<const RecordType *> RecordTypeList;
14022 RecordTypeList.push_back(Ty);
14023 unsigned NextToCheckIndex = 0;
14024 // We walk the record hierarchy breadth-first to ensure that we print
14025 // diagnostics in field nesting order.
14026 while (RecordTypeList.size() > NextToCheckIndex) {
14027 bool IsNested = NextToCheckIndex > 0;
14028 for (const FieldDecl *Field :
14029 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
14030 // First, check every field for constness.
14031 QualType FieldTy = Field->getType();
14032 if (FieldTy.isConstQualified()) {
14033 if (!DiagnosticEmitted) {
14034 S.Diag(Loc, diag::err_typecheck_assign_const)
14035 << Range << NestedConstMember << OEK << VD
14036 << IsNested << Field;
14037 DiagnosticEmitted = true;
14038 }
14039 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14040 << NestedConstMember << IsNested << Field
14041 << FieldTy << Field->getSourceRange();
14042 }
14043
14044 // Then we append it to the list to check next in order.
14045 FieldTy = FieldTy.getCanonicalType();
14046 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
14047 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14048 RecordTypeList.push_back(FieldRecTy);
14049 }
14050 }
14051 ++NextToCheckIndex;
14052 }
14053}
14054
14055/// Emit an error for the case where a record we are trying to assign to has a
14056/// const-qualified field somewhere in its hierarchy.
14057static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14058 SourceLocation Loc) {
14059 QualType Ty = E->getType();
14060 assert(Ty->isRecordType() && "lvalue was not record?")(static_cast <bool> (Ty->isRecordType() && "lvalue was not record?"
) ? void (0) : __assert_fail ("Ty->isRecordType() && \"lvalue was not record?\""
, "clang/lib/Sema/SemaExpr.cpp", 14060, __extension__ __PRETTY_FUNCTION__
))
;
14061 SourceRange Range = E->getSourceRange();
14062 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
14063 bool DiagEmitted = false;
14064
14065 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14066 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14067 Range, OEK_Member, DiagEmitted);
14068 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14069 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14070 Range, OEK_Variable, DiagEmitted);
14071 else
14072 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14073 Range, OEK_LValue, DiagEmitted);
14074 if (!DiagEmitted)
14075 DiagnoseConstAssignment(S, E, Loc);
14076}
14077
14078/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14079/// emit an error and return true. If so, return false.
14080static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14081 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!E->hasPlaceholderType(BuiltinType
::PseudoObject)) ? void (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)"
, "clang/lib/Sema/SemaExpr.cpp", 14081, __extension__ __PRETTY_FUNCTION__
))
;
14082
14083 S.CheckShadowingDeclModification(E, Loc);
14084
14085 SourceLocation OrigLoc = Loc;
14086 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
14087 &Loc);
14088 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14089 IsLV = Expr::MLV_InvalidMessageExpression;
14090 if (IsLV == Expr::MLV_Valid)
14091 return false;
14092
14093 unsigned DiagID = 0;
14094 bool NeedType = false;
14095 switch (IsLV) { // C99 6.5.16p2
14096 case Expr::MLV_ConstQualified:
14097 // Use a specialized diagnostic when we're assigning to an object
14098 // from an enclosing function or block.
14099 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14100 if (NCCK == NCCK_Block)
14101 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14102 else
14103 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14104 break;
14105 }
14106
14107 // In ARC, use some specialized diagnostics for occasions where we
14108 // infer 'const'. These are always pseudo-strong variables.
14109 if (S.getLangOpts().ObjCAutoRefCount) {
14110 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14111 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14112 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14113
14114 // Use the normal diagnostic if it's pseudo-__strong but the
14115 // user actually wrote 'const'.
14116 if (var->isARCPseudoStrong() &&
14117 (!var->getTypeSourceInfo() ||
14118 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14119 // There are three pseudo-strong cases:
14120 // - self
14121 ObjCMethodDecl *method = S.getCurMethodDecl();
14122 if (method && var == method->getSelfDecl()) {
14123 DiagID = method->isClassMethod()
14124 ? diag::err_typecheck_arc_assign_self_class_method
14125 : diag::err_typecheck_arc_assign_self;
14126
14127 // - Objective-C externally_retained attribute.
14128 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14129 isa<ParmVarDecl>(var)) {
14130 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14131
14132 // - fast enumeration variables
14133 } else {
14134 DiagID = diag::err_typecheck_arr_assign_enumeration;
14135 }
14136
14137 SourceRange Assign;
14138 if (Loc != OrigLoc)
14139 Assign = SourceRange(OrigLoc, OrigLoc);
14140 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14141 // We need to preserve the AST regardless, so migration tool
14142 // can do its job.
14143 return false;
14144 }
14145 }
14146 }
14147
14148 // If none of the special cases above are triggered, then this is a
14149 // simple const assignment.
14150 if (DiagID == 0) {
14151 DiagnoseConstAssignment(S, E, Loc);
14152 return true;
14153 }
14154
14155 break;
14156 case Expr::MLV_ConstAddrSpace:
14157 DiagnoseConstAssignment(S, E, Loc);
14158 return true;
14159 case Expr::MLV_ConstQualifiedField:
14160 DiagnoseRecursiveConstFields(S, E, Loc);
14161 return true;
14162 case Expr::MLV_ArrayType:
14163 case Expr::MLV_ArrayTemporary:
14164 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14165 NeedType = true;
14166 break;
14167 case Expr::MLV_NotObjectType:
14168 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14169 NeedType = true;
14170 break;
14171 case Expr::MLV_LValueCast:
14172 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14173 break;
14174 case Expr::MLV_Valid:
14175 llvm_unreachable("did not take early return for MLV_Valid")::llvm::llvm_unreachable_internal("did not take early return for MLV_Valid"
, "clang/lib/Sema/SemaExpr.cpp", 14175)
;
14176 case Expr::MLV_InvalidExpression:
14177 case Expr::MLV_MemberFunction:
14178 case Expr::MLV_ClassTemporary:
14179 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14180 break;
14181 case Expr::MLV_IncompleteType:
14182 case Expr::MLV_IncompleteVoidType:
14183 return S.RequireCompleteType(Loc, E->getType(),
14184 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14185 case Expr::MLV_DuplicateVectorComponents:
14186 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14187 break;
14188 case Expr::MLV_NoSetterProperty:
14189 llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently"
, "clang/lib/Sema/SemaExpr.cpp", 14189)
;
14190 case Expr::MLV_InvalidMessageExpression:
14191 DiagID = diag::err_readonly_message_assignment;
14192 break;
14193 case Expr::MLV_SubObjCPropertySetting:
14194 DiagID = diag::err_no_subobject_property_setting;
14195 break;
14196 }
14197
14198 SourceRange Assign;
14199 if (Loc != OrigLoc)
14200 Assign = SourceRange(OrigLoc, OrigLoc);
14201 if (NeedType)
14202 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14203 else
14204 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14205 return true;
14206}
14207
14208static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14209 SourceLocation Loc,
14210 Sema &Sema) {
14211 if (Sema.inTemplateInstantiation())
14212 return;
14213 if (Sema.isUnevaluatedContext())
14214 return;
14215 if (Loc.isInvalid() || Loc.isMacroID())
14216 return;
14217 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14218 return;
14219
14220 // C / C++ fields
14221 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14222 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14223 if (ML && MR) {
14224 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14225 return;
14226 const ValueDecl *LHSDecl =
14227 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
14228 const ValueDecl *RHSDecl =
14229 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
14230 if (LHSDecl != RHSDecl)
14231 return;
14232 if (LHSDecl->getType().isVolatileQualified())
14233 return;
14234 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14235 if (RefTy->getPointeeType().isVolatileQualified())
14236 return;
14237
14238 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14239 }
14240
14241 // Objective-C instance variables
14242 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14243 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14244 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14245 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14246 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14247 if (RL && RR && RL->getDecl() == RR->getDecl())
14248 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14249 }
14250}
14251
14252// C99 6.5.16.1
14253QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14254 SourceLocation Loc,
14255 QualType CompoundType,
14256 BinaryOperatorKind Opc) {
14257 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!LHSExpr->hasPlaceholderType(BuiltinType
::PseudoObject)) ? void (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)"
, "clang/lib/Sema/SemaExpr.cpp", 14257, __extension__ __PRETTY_FUNCTION__
))
;
14258
14259 // Verify that LHS is a modifiable lvalue, and emit error if not.
14260 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14261 return QualType();
14262
14263 QualType LHSType = LHSExpr->getType();
14264 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14265 CompoundType;
14266 // OpenCL v1.2 s6.1.1.1 p2:
14267 // The half data type can only be used to declare a pointer to a buffer that
14268 // contains half values
14269 if (getLangOpts().OpenCL &&
14270 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14271 LHSType->isHalfType()) {
14272 Diag(Loc, diag::err_opencl_half_load_store) << 1
14273 << LHSType.getUnqualifiedType();
14274 return QualType();
14275 }
14276
14277 AssignConvertType ConvTy;
14278 if (CompoundType.isNull()) {
14279 Expr *RHSCheck = RHS.get();
14280
14281 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14282
14283 QualType LHSTy(LHSType);
14284 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14285 if (RHS.isInvalid())
14286 return QualType();
14287 // Special case of NSObject attributes on c-style pointer types.
14288 if (ConvTy == IncompatiblePointer &&
14289 ((Context.isObjCNSObjectType(LHSType) &&
14290 RHSType->isObjCObjectPointerType()) ||
14291 (Context.isObjCNSObjectType(RHSType) &&
14292 LHSType->isObjCObjectPointerType())))
14293 ConvTy = Compatible;
14294
14295 if (ConvTy == Compatible &&
14296 LHSType->isObjCObjectType())
14297 Diag(Loc, diag::err_objc_object_assignment)
14298 << LHSType;
14299
14300 // If the RHS is a unary plus or minus, check to see if they = and + are
14301 // right next to each other. If so, the user may have typo'd "x =+ 4"
14302 // instead of "x += 4".
14303 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14304 RHSCheck = ICE->getSubExpr();
14305 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14306 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14307 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14308 // Only if the two operators are exactly adjacent.
14309 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14310 // And there is a space or other character before the subexpr of the
14311 // unary +/-. We don't want to warn on "x=-1".
14312 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14313 UO->getSubExpr()->getBeginLoc().isFileID()) {
14314 Diag(Loc, diag::warn_not_compound_assign)
14315 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14316 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14317 }
14318 }
14319
14320 if (ConvTy == Compatible) {
14321 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14322 // Warn about retain cycles where a block captures the LHS, but
14323 // not if the LHS is a simple variable into which the block is
14324 // being stored...unless that variable can be captured by reference!
14325 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14326 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14327 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14328 checkRetainCycles(LHSExpr, RHS.get());
14329 }
14330
14331 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14332 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14333 // It is safe to assign a weak reference into a strong variable.
14334 // Although this code can still have problems:
14335 // id x = self.weakProp;
14336 // id y = self.weakProp;
14337 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14338 // paths through the function. This should be revisited if
14339 // -Wrepeated-use-of-weak is made flow-sensitive.
14340 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14341 // variable, which will be valid for the current autorelease scope.
14342 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14343 RHS.get()->getBeginLoc()))
14344 getCurFunction()->markSafeWeakUse(RHS.get());
14345
14346 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14347 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14348 }
14349 }
14350 } else {
14351 // Compound assignment "x += y"
14352 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14353 }
14354
14355 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
14356 RHS.get(), AA_Assigning))
14357 return QualType();
14358
14359 CheckForNullPointerDereference(*this, LHSExpr);
14360
14361 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14362 if (CompoundType.isNull()) {
14363 // C++2a [expr.ass]p5:
14364 // A simple-assignment whose left operand is of a volatile-qualified
14365 // type is deprecated unless the assignment is either a discarded-value
14366 // expression or an unevaluated operand
14367 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14368 }
14369 }
14370
14371 // C11 6.5.16p3: The type of an assignment expression is the type of the
14372 // left operand would have after lvalue conversion.
14373 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14374 // qualified type, the value has the unqualified version of the type of the
14375 // lvalue; additionally, if the lvalue has atomic type, the value has the
14376 // non-atomic version of the type of the lvalue.
14377 // C++ 5.17p1: the type of the assignment expression is that of its left
14378 // operand.
14379 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14380}
14381
14382// Scenarios to ignore if expression E is:
14383// 1. an explicit cast expression into void
14384// 2. a function call expression that returns void
14385static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14386 E = E->IgnoreParens();
14387
14388 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14389 if (CE->getCastKind() == CK_ToVoid) {
14390 return true;
14391 }
14392
14393 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14394 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14395 CE->getSubExpr()->getType()->isDependentType()) {
14396 return true;
14397 }
14398 }
14399
14400 if (const auto *CE = dyn_cast<CallExpr>(E))
14401 return CE->getCallReturnType(Context)->isVoidType();
14402 return false;
14403}
14404
14405// Look for instances where it is likely the comma operator is confused with
14406// another operator. There is an explicit list of acceptable expressions for
14407// the left hand side of the comma operator, otherwise emit a warning.
14408void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14409 // No warnings in macros
14410 if (Loc.isMacroID())
14411 return;
14412
14413 // Don't warn in template instantiations.
14414 if (inTemplateInstantiation())
14415 return;
14416
14417 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14418 // instead, skip more than needed, then call back into here with the
14419 // CommaVisitor in SemaStmt.cpp.
14420 // The listed locations are the initialization and increment portions
14421 // of a for loop. The additional checks are on the condition of
14422 // if statements, do/while loops, and for loops.
14423 // Differences in scope flags for C89 mode requires the extra logic.
14424 const unsigned ForIncrementFlags =
14425 getLangOpts().C99 || getLangOpts().CPlusPlus
14426 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14427 : Scope::ContinueScope | Scope::BreakScope;
14428 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14429 const unsigned ScopeFlags = getCurScope()->getFlags();
14430 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14431 (ScopeFlags & ForInitFlags) == ForInitFlags)
14432 return;
14433
14434 // If there are multiple comma operators used together, get the RHS of the
14435 // of the comma operator as the LHS.
14436 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14437 if (BO->getOpcode() != BO_Comma)
14438 break;
14439 LHS = BO->getRHS();
14440 }
14441
14442 // Only allow some expressions on LHS to not warn.
14443 if (IgnoreCommaOperand(LHS, Context))
14444 return;
14445
14446 Diag(Loc, diag::warn_comma_operator);
14447 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14448 << LHS->getSourceRange()
14449 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
14450 LangOpts.CPlusPlus ? "static_cast<void>("
14451 : "(void)(")
14452 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14453 ")");
14454}
14455
14456// C99 6.5.17
14457static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14458 SourceLocation Loc) {
14459 LHS = S.CheckPlaceholderExpr(LHS.get());
14460 RHS = S.CheckPlaceholderExpr(RHS.get());
14461 if (LHS.isInvalid() || RHS.isInvalid())
14462 return QualType();
14463
14464 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14465 // operands, but not unary promotions.
14466 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14467
14468 // So we treat the LHS as a ignored value, and in C++ we allow the
14469 // containing site to determine what should be done with the RHS.
14470 LHS = S.IgnoredValueConversions(LHS.get());
14471 if (LHS.isInvalid())
14472 return QualType();
14473
14474 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14475
14476 if (!S.getLangOpts().CPlusPlus) {
14477 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
14478 if (RHS.isInvalid())
14479 return QualType();
14480 if (!RHS.get()->getType()->isVoidType())
14481 S.RequireCompleteType(Loc, RHS.get()->getType(),
14482 diag::err_incomplete_type);
14483 }
14484
14485 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14486 S.DiagnoseCommaOperator(LHS.get(), Loc);
14487
14488 return RHS.get()->getType();
14489}
14490
14491/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14492/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14493static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14494 ExprValueKind &VK,
14495 ExprObjectKind &OK,
14496 SourceLocation OpLoc,
14497 bool IsInc, bool IsPrefix) {
14498 if (Op->isTypeDependent())
14499 return S.Context.DependentTy;
14500
14501 QualType ResType = Op->getType();
14502 // Atomic types can be used for increment / decrement where the non-atomic
14503 // versions can, so ignore the _Atomic() specifier for the purpose of
14504 // checking.
14505 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14506 ResType = ResAtomicType->getValueType();
14507
14508 assert(!ResType.isNull() && "no type for increment/decrement expression")(static_cast <bool> (!ResType.isNull() && "no type for increment/decrement expression"
) ? void (0) : __assert_fail ("!ResType.isNull() && \"no type for increment/decrement expression\""
, "clang/lib/Sema/SemaExpr.cpp", 14508, __extension__ __PRETTY_FUNCTION__
))
;
14509
14510 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14511 // Decrement of bool is not allowed.
14512 if (!IsInc) {
14513 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14514 return QualType();
14515 }
14516 // Increment of bool sets it to true, but is deprecated.
14517 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14518 : diag::warn_increment_bool)
14519 << Op->getSourceRange();
14520 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14521 // Error on enum increments and decrements in C++ mode
14522 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14523 return QualType();
14524 } else if (ResType->isRealType()) {
14525 // OK!
14526 } else if (ResType->isPointerType()) {
14527 // C99 6.5.2.4p2, 6.5.6p2
14528 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14529 return QualType();
14530 } else if (ResType->isObjCObjectPointerType()) {
14531 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14532 // Otherwise, we just need a complete type.
14533 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14534 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14535 return QualType();
14536 } else if (ResType->isAnyComplexType()) {
14537 // C99 does not support ++/-- on complex types, we allow as an extension.
14538 S.Diag(OpLoc, diag::ext_integer_increment_complex)
14539 << ResType << Op->getSourceRange();
14540 } else if (ResType->isPlaceholderType()) {
14541 ExprResult PR = S.CheckPlaceholderExpr(Op);
14542 if (PR.isInvalid()) return QualType();
14543 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14544 IsInc, IsPrefix);
14545 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14546 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14547 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14548 (ResType->castAs<VectorType>()->getVectorKind() !=
14549 VectorType::AltiVecBool)) {
14550 // The z vector extensions allow ++ and -- for non-bool vectors.
14551 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
14552 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14553 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14554 } else {
14555 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14556 << ResType << int(IsInc) << Op->getSourceRange();
14557 return QualType();
14558 }
14559 // At this point, we know we have a real, complex or pointer type.
14560 // Now make sure the operand is a modifiable lvalue.
14561 if (CheckForModifiableLvalue(Op, OpLoc, S))
14562 return QualType();
14563 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14564 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14565 // An operand with volatile-qualified type is deprecated
14566 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14567 << IsInc << ResType;
14568 }
14569 // In C++, a prefix increment is the same type as the operand. Otherwise
14570 // (in C or with postfix), the increment is the unqualified type of the
14571 // operand.
14572 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14573 VK = VK_LValue;
14574 OK = Op->getObjectKind();
14575 return ResType;
14576 } else {
14577 VK = VK_PRValue;
14578 return ResType.getUnqualifiedType();
14579 }
14580}
14581
14582
14583/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14584/// This routine allows us to typecheck complex/recursive expressions
14585/// where the declaration is needed for type checking. We only need to
14586/// handle cases when the expression references a function designator
14587/// or is an lvalue. Here are some examples:
14588/// - &(x) => x
14589/// - &*****f => f for f a function designator.
14590/// - &s.xx => s
14591/// - &s.zz[1].yy -> s, if zz is an array
14592/// - *(x + 1) -> x, if x is an array
14593/// - &"123"[2] -> 0
14594/// - & __real__ x -> x
14595///
14596/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14597/// members.
14598static ValueDecl *getPrimaryDecl(Expr *E) {
14599 switch (E->getStmtClass()) {
14600 case Stmt::DeclRefExprClass:
14601 return cast<DeclRefExpr>(E)->getDecl();
14602 case Stmt::MemberExprClass:
14603 // If this is an arrow operator, the address is an offset from
14604 // the base's value, so the object the base refers to is
14605 // irrelevant.
14606 if (cast<MemberExpr>(E)->isArrow())
14607 return nullptr;
14608 // Otherwise, the expression refers to a part of the base
14609 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14610 case Stmt::ArraySubscriptExprClass: {
14611 // FIXME: This code shouldn't be necessary! We should catch the implicit
14612 // promotion of register arrays earlier.
14613 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14614 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14615 if (ICE->getSubExpr()->getType()->isArrayType())
14616 return getPrimaryDecl(ICE->getSubExpr());
14617 }
14618 return nullptr;
14619 }
14620 case Stmt::UnaryOperatorClass: {
14621 UnaryOperator *UO = cast<UnaryOperator>(E);
14622
14623 switch(UO->getOpcode()) {
14624 case UO_Real:
14625 case UO_Imag:
14626 case UO_Extension:
14627 return getPrimaryDecl(UO->getSubExpr());
14628 default:
14629 return nullptr;
14630 }
14631 }
14632 case Stmt::ParenExprClass:
14633 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14634 case Stmt::ImplicitCastExprClass:
14635 // If the result of an implicit cast is an l-value, we care about
14636 // the sub-expression; otherwise, the result here doesn't matter.
14637 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14638 case Stmt::CXXUuidofExprClass:
14639 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14640 default:
14641 return nullptr;
14642 }
14643}
14644
14645namespace {
14646enum {
14647 AO_Bit_Field = 0,
14648 AO_Vector_Element = 1,
14649 AO_Property_Expansion = 2,
14650 AO_Register_Variable = 3,
14651 AO_Matrix_Element = 4,
14652 AO_No_Error = 5
14653};
14654}
14655/// Diagnose invalid operand for address of operations.
14656///
14657/// \param Type The type of operand which cannot have its address taken.
14658static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14659 Expr *E, unsigned Type) {
14660 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14661}
14662
14663/// CheckAddressOfOperand - The operand of & must be either a function
14664/// designator or an lvalue designating an object. If it is an lvalue, the
14665/// object cannot be declared with storage class register or be a bit field.
14666/// Note: The usual conversions are *not* applied to the operand of the &
14667/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14668/// In C++, the operand might be an overloaded function name, in which case
14669/// we allow the '&' but retain the overloaded-function type.
14670QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14671 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14672 if (PTy->getKind() == BuiltinType::Overload) {
14673 Expr *E = OrigOp.get()->IgnoreParens();
14674 if (!isa<OverloadExpr>(E)) {
14675 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)(static_cast <bool> (cast<UnaryOperator>(E)->getOpcode
() == UO_AddrOf) ? void (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf"
, "clang/lib/Sema/SemaExpr.cpp", 14675, __extension__ __PRETTY_FUNCTION__
))
;
14676 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14677 << OrigOp.get()->getSourceRange();
14678 return QualType();
14679 }
14680
14681 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14682 if (isa<UnresolvedMemberExpr>(Ovl))
14683 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14684 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14685 << OrigOp.get()->getSourceRange();
14686 return QualType();
14687 }
14688
14689 return Context.OverloadTy;
14690 }
14691
14692 if (PTy->getKind() == BuiltinType::UnknownAny)
14693 return Context.UnknownAnyTy;
14694
14695 if (PTy->getKind() == BuiltinType::BoundMember) {
14696 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14697 << OrigOp.get()->getSourceRange();
14698 return QualType();
14699 }
14700
14701 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14702 if (OrigOp.isInvalid()) return QualType();
14703 }
14704
14705 if (OrigOp.get()->isTypeDependent())
14706 return Context.DependentTy;
14707
14708 assert(!OrigOp.get()->hasPlaceholderType())(static_cast <bool> (!OrigOp.get()->hasPlaceholderType
()) ? void (0) : __assert_fail ("!OrigOp.get()->hasPlaceholderType()"
, "clang/lib/Sema/SemaExpr.cpp", 14708, __extension__ __PRETTY_FUNCTION__
))
;
14709
14710 // Make sure to ignore parentheses in subsequent checks
14711 Expr *op = OrigOp.get()->IgnoreParens();
14712
14713 // In OpenCL captures for blocks called as lambda functions
14714 // are located in the private address space. Blocks used in
14715 // enqueue_kernel can be located in a different address space
14716 // depending on a vendor implementation. Thus preventing
14717 // taking an address of the capture to avoid invalid AS casts.
14718 if (LangOpts.OpenCL) {
14719 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14720 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14721 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14722 return QualType();
14723 }
14724 }
14725
14726 if (getLangOpts().C99) {
14727 // Implement C99-only parts of addressof rules.
14728 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14729 if (uOp->getOpcode() == UO_Deref)
14730 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14731 // (assuming the deref expression is valid).
14732 return uOp->getSubExpr()->getType();
14733 }
14734 // Technically, there should be a check for array subscript
14735 // expressions here, but the result of one is always an lvalue anyway.
14736 }
14737 ValueDecl *dcl = getPrimaryDecl(op);
14738
14739 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14740 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14741 op->getBeginLoc()))
14742 return QualType();
14743
14744 Expr::LValueClassification lval = op->ClassifyLValue(Context);
14745 unsigned AddressOfError = AO_No_Error;
14746
14747 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14748 bool sfinae = (bool)isSFINAEContext();
14749 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14750 : diag::ext_typecheck_addrof_temporary)
14751 << op->getType() << op->getSourceRange();
14752 if (sfinae)
14753 return QualType();
14754 // Materialize the temporary as an lvalue so that we can take its address.
14755 OrigOp = op =
14756 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14757 } else if (isa<ObjCSelectorExpr>(op)) {
14758 return Context.getPointerType(op->getType());
14759 } else if (lval == Expr::LV_MemberFunction) {
14760 // If it's an instance method, make a member pointer.
14761 // The expression must have exactly the form &A::foo.
14762
14763 // If the underlying expression isn't a decl ref, give up.
14764 if (!isa<DeclRefExpr>(op)) {
14765 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14766 << OrigOp.get()->getSourceRange();
14767 return QualType();
14768 }
14769 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14770 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14771
14772 // The id-expression was parenthesized.
14773 if (OrigOp.get() != DRE) {
14774 Diag(OpLoc, diag::err_parens_pointer_member_function)
14775 << OrigOp.get()->getSourceRange();
14776
14777 // The method was named without a qualifier.
14778 } else if (!DRE->getQualifier()) {
14779 if (MD->getParent()->getName().empty())
14780 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14781 << op->getSourceRange();
14782 else {
14783 SmallString<32> Str;
14784 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14785 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14786 << op->getSourceRange()
14787 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14788 }
14789 }
14790
14791 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14792 if (isa<CXXDestructorDecl>(MD))
14793 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14794
14795 QualType MPTy = Context.getMemberPointerType(
14796 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14797 // Under the MS ABI, lock down the inheritance model now.
14798 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14799 (void)isCompleteType(OpLoc, MPTy);
14800 return MPTy;
14801 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14802 // C99 6.5.3.2p1
14803 // The operand must be either an l-value or a function designator
14804 if (!op->getType()->isFunctionType()) {
14805 // Use a special diagnostic for loads from property references.
14806 if (isa<PseudoObjectExpr>(op)) {
14807 AddressOfError = AO_Property_Expansion;
14808 } else {
14809 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14810 << op->getType() << op->getSourceRange();
14811 return QualType();
14812 }
14813 }
14814 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14815 // The operand cannot be a bit-field
14816 AddressOfError = AO_Bit_Field;
14817 } else if (op->getObjectKind() == OK_VectorComponent) {
14818 // The operand cannot be an element of a vector
14819 AddressOfError = AO_Vector_Element;
14820 } else if (op->getObjectKind() == OK_MatrixComponent) {
14821 // The operand cannot be an element of a matrix.
14822 AddressOfError = AO_Matrix_Element;
14823 } else if (dcl) { // C99 6.5.3.2p1
14824 // We have an lvalue with a decl. Make sure the decl is not declared
14825 // with the register storage-class specifier.
14826 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14827 // in C++ it is not error to take address of a register
14828 // variable (c++03 7.1.1P3)
14829 if (vd->getStorageClass() == SC_Register &&
14830 !getLangOpts().CPlusPlus) {
14831 AddressOfError = AO_Register_Variable;
14832 }
14833 } else if (isa<MSPropertyDecl>(dcl)) {
14834 AddressOfError = AO_Property_Expansion;
14835 } else if (isa<FunctionTemplateDecl>(dcl)) {
14836 return Context.OverloadTy;
14837 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14838 // Okay: we can take the address of a field.
14839 // Could be a pointer to member, though, if there is an explicit
14840 // scope qualifier for the class.
14841 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14842 DeclContext *Ctx = dcl->getDeclContext();
14843 if (Ctx && Ctx->isRecord()) {
14844 if (dcl->getType()->isReferenceType()) {
14845 Diag(OpLoc,
14846 diag::err_cannot_form_pointer_to_member_of_reference_type)
14847 << dcl->getDeclName() << dcl->getType();
14848 return QualType();
14849 }
14850
14851 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14852 Ctx = Ctx->getParent();
14853
14854 QualType MPTy = Context.getMemberPointerType(
14855 op->getType(),
14856 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14857 // Under the MS ABI, lock down the inheritance model now.
14858 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14859 (void)isCompleteType(OpLoc, MPTy);
14860 return MPTy;
14861 }
14862 }
14863 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
14864 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
14865 llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type"
, "clang/lib/Sema/SemaExpr.cpp", 14865)
;
14866 }
14867
14868 if (AddressOfError != AO_No_Error) {
14869 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14870 return QualType();
14871 }
14872
14873 if (lval == Expr::LV_IncompleteVoidType) {
14874 // Taking the address of a void variable is technically illegal, but we
14875 // allow it in cases which are otherwise valid.
14876 // Example: "extern void x; void* y = &x;".
14877 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14878 }
14879
14880 // If the operand has type "type", the result has type "pointer to type".
14881 if (op->getType()->isObjCObjectType())
14882 return Context.getObjCObjectPointerType(op->getType());
14883
14884 if (Context.getTargetInfo().getTriple().isWasm() &&
14885 op->getType()->isWebAssemblyReferenceType()) {
14886 Diag(OpLoc, diag::err_wasm_ca_reference)
14887 << 1 << OrigOp.get()->getSourceRange();
14888 return QualType();
14889 }
14890
14891 CheckAddressOfPackedMember(op);
14892
14893 return Context.getPointerType(op->getType());
14894}
14895
14896static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14897 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14898 if (!DRE)
14899 return;
14900 const Decl *D = DRE->getDecl();
14901 if (!D)
14902 return;
14903 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14904 if (!Param)
14905 return;
14906 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14907 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14908 return;
14909 if (FunctionScopeInfo *FD = S.getCurFunction())
14910 FD->ModifiedNonNullParams.insert(Param);
14911}
14912
14913/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14914static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14915 SourceLocation OpLoc,
14916 bool IsAfterAmp = false) {
14917 if (Op->isTypeDependent())
14918 return S.Context.DependentTy;
14919
14920 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14921 if (ConvResult.isInvalid())
14922 return QualType();
14923 Op = ConvResult.get();
14924 QualType OpTy = Op->getType();
14925 QualType Result;
14926
14927 if (isa<CXXReinterpretCastExpr>(Op)) {
14928 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14929 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14930 Op->getSourceRange());
14931 }
14932
14933 if (const PointerType *PT = OpTy->getAs<PointerType>())
14934 {
14935 Result = PT->getPointeeType();
14936 }
14937 else if (const ObjCObjectPointerType *OPT =
14938 OpTy->getAs<ObjCObjectPointerType>())
14939 Result = OPT->getPointeeType();
14940 else {
14941 ExprResult PR = S.CheckPlaceholderExpr(Op);
14942 if (PR.isInvalid()) return QualType();
14943 if (PR.get() != Op)
14944 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14945 }
14946
14947 if (Result.isNull()) {
14948 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14949 << OpTy << Op->getSourceRange();
14950 return QualType();
14951 }
14952
14953 if (Result->isVoidType()) {
14954 // C++ [expr.unary.op]p1:
14955 // [...] the expression to which [the unary * operator] is applied shall
14956 // be a pointer to an object type, or a pointer to a function type
14957 LangOptions LO = S.getLangOpts();
14958 if (LO.CPlusPlus)
14959 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer_cpp)
14960 << OpTy << Op->getSourceRange();
14961 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14962 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14963 << OpTy << Op->getSourceRange();
14964 }
14965
14966 // Dereferences are usually l-values...
14967 VK = VK_LValue;
14968
14969 // ...except that certain expressions are never l-values in C.
14970 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14971 VK = VK_PRValue;
14972
14973 return Result;
14974}
14975
14976BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14977 BinaryOperatorKind Opc;
14978 switch (Kind) {
14979 default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "clang/lib/Sema/SemaExpr.cpp"
, 14979)
;
14980 case tok::periodstar: Opc = BO_PtrMemD; break;
14981 case tok::arrowstar: Opc = BO_PtrMemI; break;
14982 case tok::star: Opc = BO_Mul; break;
14983 case tok::slash: Opc = BO_Div; break;
14984 case tok::percent: Opc = BO_Rem; break;
14985 case tok::plus: Opc = BO_Add; break;
14986 case tok::minus: Opc = BO_Sub; break;
14987 case tok::lessless: Opc = BO_Shl; break;
14988 case tok::greatergreater: Opc = BO_Shr; break;
14989 case tok::lessequal: Opc = BO_LE; break;
14990 case tok::less: Opc = BO_LT; break;
14991 case tok::greaterequal: Opc = BO_GE; break;
14992 case tok::greater: Opc = BO_GT; break;
14993 case tok::exclaimequal: Opc = BO_NE; break;
14994 case tok::equalequal: Opc = BO_EQ; break;
14995 case tok::spaceship: Opc = BO_Cmp; break;
14996 case tok::amp: Opc = BO_And; break;
14997 case tok::caret: Opc = BO_Xor; break;
14998 case tok::pipe: Opc = BO_Or; break;
14999 case tok::ampamp: Opc = BO_LAnd; break;
15000 case tok::pipepipe: Opc = BO_LOr; break;
15001 case tok::equal: Opc = BO_Assign; break;
15002 case tok::starequal: Opc = BO_MulAssign; break;
15003 case tok::slashequal: Opc = BO_DivAssign; break;
15004 case tok::percentequal: Opc = BO_RemAssign; break;
15005 case tok::plusequal: Opc = BO_AddAssign; break;
15006 case tok::minusequal: Opc = BO_SubAssign; break;
15007 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15008 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15009 case tok::ampequal: Opc = BO_AndAssign; break;
15010 case tok::caretequal: Opc = BO_XorAssign; break;
15011 case tok::pipeequal: Opc = BO_OrAssign; break;
15012 case tok::comma: Opc = BO_Comma; break;
15013 }
15014 return Opc;
15015}
15016
15017static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15018 tok::TokenKind Kind) {
15019 UnaryOperatorKind Opc;
15020 switch (Kind) {
15021 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp"
, 15021)
;
15022 case tok::plusplus: Opc = UO_PreInc; break;
15023 case tok::minusminus: Opc = UO_PreDec; break;
15024 case tok::amp: Opc = UO_AddrOf; break;
15025 case tok::star: Opc = UO_Deref; break;
15026 case tok::plus: Opc = UO_Plus; break;
15027 case tok::minus: Opc = UO_Minus; break;
15028 case tok::tilde: Opc = UO_Not; break;
15029 case tok::exclaim: Opc = UO_LNot; break;
15030 case tok::kw___real: Opc = UO_Real; break;
15031 case tok::kw___imag: Opc = UO_Imag; break;
15032 case tok::kw___extension__: Opc = UO_Extension; break;
15033 }
15034 return Opc;
15035}
15036
15037const FieldDecl *
15038Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15039 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15040 // common for setters.
15041 // struct A {
15042 // int X;
15043 // -void setX(int X) { X = X; }
15044 // +void setX(int X) { this->X = X; }
15045 // };
15046
15047 // Only consider parameters for self assignment fixes.
15048 if (!isa<ParmVarDecl>(SelfAssigned))
15049 return nullptr;
15050 const auto *Method =
15051 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15052 if (!Method)
15053 return nullptr;
15054
15055 const CXXRecordDecl *Parent = Method->getParent();
15056 // In theory this is fixable if the lambda explicitly captures this, but
15057 // that's added complexity that's rarely going to be used.
15058 if (Parent->isLambda())
15059 return nullptr;
15060
15061 // FIXME: Use an actual Lookup operation instead of just traversing fields
15062 // in order to get base class fields.
15063 auto Field =
15064 llvm::find_if(Parent->fields(),
15065 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15066 return F->getDeclName() == Name;
15067 });
15068 return (Field != Parent->field_end()) ? *Field : nullptr;
15069}
15070
15071/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15072/// This warning suppressed in the event of macro expansions.
15073static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15074 SourceLocation OpLoc, bool IsBuiltin) {
15075 if (S.inTemplateInstantiation())
15076 return;
15077 if (S.isUnevaluatedContext())
15078 return;
15079 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15080 return;
15081 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15082 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15083 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15084 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15085 if (!LHSDeclRef || !RHSDeclRef ||
15086 LHSDeclRef->getLocation().isMacroID() ||
15087 RHSDeclRef->getLocation().isMacroID())
15088 return;
15089 const ValueDecl *LHSDecl =
15090 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15091 const ValueDecl *RHSDecl =
15092 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15093 if (LHSDecl != RHSDecl)
15094 return;
15095 if (LHSDecl->getType().isVolatileQualified())
15096 return;
15097 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15098 if (RefTy->getPointeeType().isVolatileQualified())
15099 return;
15100
15101 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15102 : diag::warn_self_assignment_overloaded)
15103 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15104 << RHSExpr->getSourceRange();
15105 if (const FieldDecl *SelfAssignField =
15106 S.getSelfAssignmentClassMemberCandidate(RHSDecl))
15107 Diag << 1 << SelfAssignField
15108 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15109 else
15110 Diag << 0;
15111}
15112
15113/// Check if a bitwise-& is performed on an Objective-C pointer. This
15114/// is usually indicative of introspection within the Objective-C pointer.
15115static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15116 SourceLocation OpLoc) {
15117 if (!S.getLangOpts().ObjC)
15118 return;
15119
15120 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15121 const Expr *LHS = L.get();
15122 const Expr *RHS = R.get();
15123
15124 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15125 ObjCPointerExpr = LHS;
15126 OtherExpr = RHS;
15127 }
15128 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15129 ObjCPointerExpr = RHS;
15130 OtherExpr = LHS;
15131 }
15132
15133 // This warning is deliberately made very specific to reduce false
15134 // positives with logic that uses '&' for hashing. This logic mainly
15135 // looks for code trying to introspect into tagged pointers, which
15136 // code should generally never do.
15137 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15138 unsigned Diag = diag::warn_objc_pointer_masking;
15139 // Determine if we are introspecting the result of performSelectorXXX.
15140 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15141 // Special case messages to -performSelector and friends, which
15142 // can return non-pointer values boxed in a pointer value.
15143 // Some clients may wish to silence warnings in this subcase.
15144 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15145 Selector S = ME->getSelector();
15146 StringRef SelArg0 = S.getNameForSlot(0);
15147 if (SelArg0.startswith("performSelector"))
15148 Diag = diag::warn_objc_pointer_masking_performSelector;
15149 }
15150
15151 S.Diag(OpLoc, Diag)
15152 << ObjCPointerExpr->getSourceRange();
15153 }
15154}
15155
15156static NamedDecl *getDeclFromExpr(Expr *E) {
15157 if (!E)
15158 return nullptr;
15159 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
15160 return DRE->getDecl();
15161 if (auto *ME = dyn_cast<MemberExpr>(E))
15162 return ME->getMemberDecl();
15163 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
15164 return IRE->getDecl();
15165 return nullptr;
15166}
15167
15168// This helper function promotes a binary operator's operands (which are of a
15169// half vector type) to a vector of floats and then truncates the result to
15170// a vector of either half or short.
15171static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15172 BinaryOperatorKind Opc, QualType ResultTy,
15173 ExprValueKind VK, ExprObjectKind OK,
15174 bool IsCompAssign, SourceLocation OpLoc,
15175 FPOptionsOverride FPFeatures) {
15176 auto &Context = S.getASTContext();
15177 assert((isVector(ResultTy, Context.HalfTy) ||(static_cast <bool> ((isVector(ResultTy, Context.HalfTy
) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short"
) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "clang/lib/Sema/SemaExpr.cpp", 15179, __extension__ __PRETTY_FUNCTION__
))
15178 isVector(ResultTy, Context.ShortTy)) &&(static_cast <bool> ((isVector(ResultTy, Context.HalfTy
) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short"
) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "clang/lib/Sema/SemaExpr.cpp", 15179, __extension__ __PRETTY_FUNCTION__
))
15179 "Result must be a vector of half or short")(static_cast <bool> ((isVector(ResultTy, Context.HalfTy
) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short"
) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "clang/lib/Sema/SemaExpr.cpp", 15179, __extension__ __PRETTY_FUNCTION__
))
;
15180 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&(static_cast <bool> (isVector(LHS.get()->getType(), Context
.HalfTy) && isVector(RHS.get()->getType(), Context
.HalfTy) && "both operands expected to be a half vector"
) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "clang/lib/Sema/SemaExpr.cpp", 15182, __extension__ __PRETTY_FUNCTION__
))
15181 isVector(RHS.get()->getType(), Context.HalfTy) &&(static_cast <bool> (isVector(LHS.get()->getType(), Context
.HalfTy) && isVector(RHS.get()->getType(), Context
.HalfTy) && "both operands expected to be a half vector"
) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "clang/lib/Sema/SemaExpr.cpp", 15182, __extension__ __PRETTY_FUNCTION__
))
15182 "both operands expected to be a half vector")(static_cast <bool> (isVector(LHS.get()->getType(), Context
.HalfTy) && isVector(RHS.get()->getType(), Context
.HalfTy) && "both operands expected to be a half vector"
) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "clang/lib/Sema/SemaExpr.cpp", 15182, __extension__ __PRETTY_FUNCTION__
))
;
15183
15184 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15185 QualType BinOpResTy = RHS.get()->getType();
15186
15187 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15188 // change BinOpResTy to a vector of ints.
15189 if (isVector(ResultTy, Context.ShortTy))
15190 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15191
15192 if (IsCompAssign)
15193 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15194 ResultTy, VK, OK, OpLoc, FPFeatures,
15195 BinOpResTy, BinOpResTy);
15196
15197 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15198 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15199 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15200 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15201}
15202
15203static std::pair<ExprResult, ExprResult>
15204CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
15205 Expr *RHSExpr) {
15206 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15207 if (!S.Context.isDependenceAllowed()) {
15208 // C cannot handle TypoExpr nodes on either side of a binop because it
15209 // doesn't handle dependent types properly, so make sure any TypoExprs have
15210 // been dealt with before checking the operands.
15211 LHS = S.CorrectDelayedTyposInExpr(LHS);
15212 RHS = S.CorrectDelayedTyposInExpr(
15213 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
15214 [Opc, LHS](Expr *E) {
15215 if (Opc != BO_Assign)
15216 return ExprResult(E);
15217 // Avoid correcting the RHS to the same Expr as the LHS.
15218 Decl *D = getDeclFromExpr(E);
15219 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
15220 });
15221 }
15222 return std::make_pair(LHS, RHS);
15223}
15224
15225/// Returns true if conversion between vectors of halfs and vectors of floats
15226/// is needed.
15227static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15228 Expr *E0, Expr *E1 = nullptr) {
15229 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15230 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15231 return false;
15232
15233 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15234 QualType Ty = E->IgnoreImplicit()->getType();
15235
15236 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15237 // to vectors of floats. Although the element type of the vectors is __fp16,
15238 // the vectors shouldn't be treated as storage-only types. See the
15239 // discussion here: https://reviews.llvm.org/rG825235c140e7
15240 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15241 if (VT->getVectorKind() == VectorType::NeonVector)
15242 return false;
15243 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15244 }
15245 return false;
15246 };
15247
15248 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15249}
15250
15251/// CreateBuiltinBinOp - Creates a new built-in binary operation with
15252/// operator @p Opc at location @c TokLoc. This routine only supports
15253/// built-in operations; ActOnBinOp handles overloaded operators.
15254ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15255 BinaryOperatorKind Opc,
15256 Expr *LHSExpr, Expr *RHSExpr) {
15257 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15258 // The syntax only allows initializer lists on the RHS of assignment,
15259 // so we don't need to worry about accepting invalid code for
15260 // non-assignment operators.
15261 // C++11 5.17p9:
15262 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15263 // of x = {} is x = T().
15264 InitializationKind Kind = InitializationKind::CreateDirectList(
15265 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15266 InitializedEntity Entity =
15267 InitializedEntity::InitializeTemporary(LHSExpr->getType());
15268 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15269 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15270 if (Init.isInvalid())
15271 return Init;
15272 RHSExpr = Init.get();
15273 }
15274
15275 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15276 QualType ResultTy; // Result type of the binary operator.
15277 // The following two variables are used for compound assignment operators
15278 QualType CompLHSTy; // Type of LHS after promotions for computation
15279 QualType CompResultTy; // Type of computation result
15280 ExprValueKind VK = VK_PRValue;
15281 ExprObjectKind OK = OK_Ordinary;
15282 bool ConvertHalfVec = false;
15283
15284 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15285 if (!LHS.isUsable() || !RHS.isUsable())
15286 return ExprError();
15287
15288 if (getLangOpts().OpenCL) {
15289 QualType LHSTy = LHSExpr->getType();
15290 QualType RHSTy = RHSExpr->getType();
15291 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15292 // the ATOMIC_VAR_INIT macro.
15293 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15294 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15295 if (BO_Assign == Opc)
15296 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15297 else
15298 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15299 return ExprError();
15300 }
15301
15302 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15303 // only with a builtin functions and therefore should be disallowed here.
15304 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15305 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15306 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15307 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15308 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15309 return ExprError();
15310 }
15311 }
15312
15313 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15314 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15315
15316 switch (Opc) {
15317 case BO_Assign:
15318 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15319 if (getLangOpts().CPlusPlus &&
15320 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15321 VK = LHS.get()->getValueKind();
15322 OK = LHS.get()->getObjectKind();
15323 }
15324 if (!ResultTy.isNull()) {
15325 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15326 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15327
15328 // Avoid copying a block to the heap if the block is assigned to a local
15329 // auto variable that is declared in the same scope as the block. This
15330 // optimization is unsafe if the local variable is declared in an outer
15331 // scope. For example:
15332 //
15333 // BlockTy b;
15334 // {
15335 // b = ^{...};
15336 // }
15337 // // It is unsafe to invoke the block here if it wasn't copied to the
15338 // // heap.
15339 // b();
15340
15341 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15342 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15343 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15344 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15345 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15346
15347 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15348 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15349 NTCUC_Assignment, NTCUK_Copy);
15350 }
15351 RecordModifiableNonNullParam(*this, LHS.get());
15352 break;
15353 case BO_PtrMemD:
15354 case BO_PtrMemI:
15355 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15356 Opc == BO_PtrMemI);
15357 break;
15358 case BO_Mul:
15359 case BO_Div:
15360 ConvertHalfVec = true;
15361 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
15362 Opc == BO_Div);
15363 break;
15364 case BO_Rem:
15365 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15366 break;
15367 case BO_Add:
15368 ConvertHalfVec = true;
15369 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15370 break;
15371 case BO_Sub:
15372 ConvertHalfVec = true;
15373 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
15374 break;
15375 case BO_Shl:
15376 case BO_Shr:
15377 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15378 break;
15379 case BO_LE:
15380 case BO_LT:
15381 case BO_GE:
15382 case BO_GT:
15383 ConvertHalfVec = true;
15384 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15385 break;
15386 case BO_EQ:
15387 case BO_NE:
15388 ConvertHalfVec = true;
15389 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15390 break;
15391 case BO_Cmp:
15392 ConvertHalfVec = true;
15393 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15394 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())(static_cast <bool> (ResultTy.isNull() || ResultTy->
getAsCXXRecordDecl()) ? void (0) : __assert_fail ("ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()"
, "clang/lib/Sema/SemaExpr.cpp", 15394, __extension__ __PRETTY_FUNCTION__
))
;
15395 break;
15396 case BO_And:
15397 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15398 [[fallthrough]];
15399 case BO_Xor:
15400 case BO_Or:
15401 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15402 break;
15403 case BO_LAnd:
15404 case BO_LOr:
15405 ConvertHalfVec = true;
15406 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15407 break;
15408 case BO_MulAssign:
15409 case BO_DivAssign:
15410 ConvertHalfVec = true;
15411 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
15412 Opc == BO_DivAssign);
15413 CompLHSTy = CompResultTy;
15414 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15415 ResultTy =
15416 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15417 break;
15418 case BO_RemAssign:
15419 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15420 CompLHSTy = CompResultTy;
15421 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15422 ResultTy =
15423 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15424 break;
15425 case BO_AddAssign:
15426 ConvertHalfVec = true;
15427 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15428 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15429 ResultTy =
15430 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15431 break;
15432 case BO_SubAssign:
15433 ConvertHalfVec = true;
15434 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
15435 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15436 ResultTy =
15437 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15438 break;
15439 case BO_ShlAssign:
15440 case BO_ShrAssign:
15441 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15442 CompLHSTy = CompResultTy;
15443 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15444 ResultTy =
15445 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15446 break;
15447 case BO_AndAssign:
15448 case BO_OrAssign: // fallthrough
15449 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15450 [[fallthrough]];
15451 case BO_XorAssign:
15452 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15453 CompLHSTy = CompResultTy;
15454 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15455 ResultTy =
15456 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15457 break;
15458 case BO_Comma:
15459 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15460 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15461 VK = RHS.get()->getValueKind();
15462 OK = RHS.get()->getObjectKind();
15463 }
15464 break;
15465 }
15466 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15467 return ExprError();
15468
15469 // Some of the binary operations require promoting operands of half vector to
15470 // float vectors and truncating the result back to half vector. For now, we do
15471 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15472 // arm64).
15473 assert((static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get
()->getType(), Context.HalfTy) == isVector(LHS.get()->getType
(), Context.HalfTy)) && "both sides are half vectors or neither sides are"
) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\""
, "clang/lib/Sema/SemaExpr.cpp", 15476, __extension__ __PRETTY_FUNCTION__
))
15474 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get
()->getType(), Context.HalfTy) == isVector(LHS.get()->getType
(), Context.HalfTy)) && "both sides are half vectors or neither sides are"
) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\""
, "clang/lib/Sema/SemaExpr.cpp", 15476, __extension__ __PRETTY_FUNCTION__
))
15475 isVector(LHS.get()->getType(), Context.HalfTy)) &&(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get
()->getType(), Context.HalfTy) == isVector(LHS.get()->getType
(), Context.HalfTy)) && "both sides are half vectors or neither sides are"
) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\""
, "clang/lib/Sema/SemaExpr.cpp", 15476, __extension__ __PRETTY_FUNCTION__
))
15476 "both sides are half vectors or neither sides are")(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get
()->getType(), Context.HalfTy) == isVector(LHS.get()->getType
(), Context.HalfTy)) && "both sides are half vectors or neither sides are"
) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\""
, "clang/lib/Sema/SemaExpr.cpp", 15476, __extension__ __PRETTY_FUNCTION__
))
;
15477 ConvertHalfVec =
15478 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15479
15480 // Check for array bounds violations for both sides of the BinaryOperator
15481 CheckArrayAccess(LHS.get());
15482 CheckArrayAccess(RHS.get());
15483
15484 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15485 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15486 &Context.Idents.get("object_setClass"),
15487 SourceLocation(), LookupOrdinaryName);
15488 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15489 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15490 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15491 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
15492 "object_setClass(")
15493 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15494 ",")
15495 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15496 }
15497 else
15498 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15499 }
15500 else if (const ObjCIvarRefExpr *OIRE =
15501 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15502 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15503
15504 // Opc is not a compound assignment if CompResultTy is null.
15505 if (CompResultTy.isNull()) {
15506 if (ConvertHalfVec)
15507 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15508 OpLoc, CurFPFeatureOverrides());
15509 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15510 VK, OK, OpLoc, CurFPFeatureOverrides());
15511 }
15512
15513 // Handle compound assignments.
15514 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15515 OK_ObjCProperty) {
15516 VK = VK_LValue;
15517 OK = LHS.get()->getObjectKind();
15518 }
15519
15520 // The LHS is not converted to the result type for fixed-point compound
15521 // assignment as the common type is computed on demand. Reset the CompLHSTy
15522 // to the LHS type we would have gotten after unary conversions.
15523 if (CompResultTy->isFixedPointType())
15524 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15525
15526 if (ConvertHalfVec)
15527 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15528 OpLoc, CurFPFeatureOverrides());
15529
15530 return CompoundAssignOperator::Create(
15531 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15532 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15533}
15534
15535/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15536/// operators are mixed in a way that suggests that the programmer forgot that
15537/// comparison operators have higher precedence. The most typical example of
15538/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15539static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15540 SourceLocation OpLoc, Expr *LHSExpr,
15541 Expr *RHSExpr) {
15542 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15543 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15544
15545 // Check that one of the sides is a comparison operator and the other isn't.
15546 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15547 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15548 if (isLeftComp == isRightComp)
15549 return;
15550
15551 // Bitwise operations are sometimes used as eager logical ops.
15552 // Don't diagnose this.
15553 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15554 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15555 if (isLeftBitwise || isRightBitwise)
15556 return;
15557
15558 SourceRange DiagRange = isLeftComp
15559 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15560 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15561 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15562 SourceRange ParensRange =
15563 isLeftComp
15564 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15565 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15566
15567 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15568 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15569 SuggestParentheses(Self, OpLoc,
15570 Self.PDiag(diag::note_precedence_silence) << OpStr,
15571 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15572 SuggestParentheses(Self, OpLoc,
15573 Self.PDiag(diag::note_precedence_bitwise_first)
15574 << BinaryOperator::getOpcodeStr(Opc),
15575 ParensRange);
15576}
15577
15578/// It accepts a '&&' expr that is inside a '||' one.
15579/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15580/// in parentheses.
15581static void
15582EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15583 BinaryOperator *Bop) {
15584 assert(Bop->getOpcode() == BO_LAnd)(static_cast <bool> (Bop->getOpcode() == BO_LAnd) ? void
(0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "clang/lib/Sema/SemaExpr.cpp"
, 15584, __extension__ __PRETTY_FUNCTION__))
;
15585 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15586 << Bop->getSourceRange() << OpLoc;
15587 SuggestParentheses(Self, Bop->getOperatorLoc(),
15588 Self.PDiag(diag::note_precedence_silence)
15589 << Bop->getOpcodeStr(),
15590 Bop->getSourceRange());
15591}
15592
15593/// Look for '&&' in the left hand of a '||' expr.
15594static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15595 Expr *LHSExpr, Expr *RHSExpr) {
15596 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15597 if (Bop->getOpcode() == BO_LAnd) {
15598 // If it's "string_literal && a || b" don't warn since the precedence
15599 // doesn't matter.
15600 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15601 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15602 } else if (Bop->getOpcode() == BO_LOr) {
15603 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15604 // If it's "a || b && string_literal || c" we didn't warn earlier for
15605 // "a || b && string_literal", but warn now.
15606 if (RBop->getOpcode() == BO_LAnd &&
15607 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15608 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15609 }
15610 }
15611 }
15612}
15613
15614/// Look for '&&' in the right hand of a '||' expr.
15615static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15616 Expr *LHSExpr, Expr *RHSExpr) {
15617 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15618 if (Bop->getOpcode() == BO_LAnd) {
15619 // If it's "a || b && string_literal" don't warn since the precedence
15620 // doesn't matter.
15621 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15622 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15623 }
15624 }
15625}
15626
15627/// Look for bitwise op in the left or right hand of a bitwise op with
15628/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15629/// the '&' expression in parentheses.
15630static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15631 SourceLocation OpLoc, Expr *SubExpr) {
15632 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15633 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15634 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15635 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15636 << Bop->getSourceRange() << OpLoc;
15637 SuggestParentheses(S, Bop->getOperatorLoc(),
15638 S.PDiag(diag::note_precedence_silence)
15639 << Bop->getOpcodeStr(),
15640 Bop->getSourceRange());
15641 }
15642 }
15643}
15644
15645static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15646 Expr *SubExpr, StringRef Shift) {
15647 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15648 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15649 StringRef Op = Bop->getOpcodeStr();
15650 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15651 << Bop->getSourceRange() << OpLoc << Shift << Op;
15652 SuggestParentheses(S, Bop->getOperatorLoc(),
15653 S.PDiag(diag::note_precedence_silence) << Op,
15654 Bop->getSourceRange());
15655 }
15656 }
15657}
15658
15659static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15660 Expr *LHSExpr, Expr *RHSExpr) {
15661 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15662 if (!OCE)
15663 return;
15664
15665 FunctionDecl *FD = OCE->getDirectCallee();
15666 if (!FD || !FD->isOverloadedOperator())
15667 return;
15668
15669 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15670 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15671 return;
15672
15673 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15674 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15675 << (Kind == OO_LessLess);
15676 SuggestParentheses(S, OCE->getOperatorLoc(),
15677 S.PDiag(diag::note_precedence_silence)
15678 << (Kind == OO_LessLess ? "<<" : ">>"),
15679 OCE->getSourceRange());
15680 SuggestParentheses(
15681 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15682 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15683}
15684
15685/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15686/// precedence.
15687static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15688 SourceLocation OpLoc, Expr *LHSExpr,
15689 Expr *RHSExpr){
15690 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15691 if (BinaryOperator::isBitwiseOp(Opc))
15692 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15693
15694 // Diagnose "arg1 & arg2 | arg3"
15695 if ((Opc == BO_Or || Opc == BO_Xor) &&
15696 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15697 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15698 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15699 }
15700
15701 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15702 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15703 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15704 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15705 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15706 }
15707
15708 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15709 || Opc == BO_Shr) {
15710 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15711 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15712 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15713 }
15714
15715 // Warn on overloaded shift operators and comparisons, such as:
15716 // cout << 5 == 4;
15717 if (BinaryOperator::isComparisonOp(Opc))
15718 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15719}
15720
15721// Binary Operators. 'Tok' is the token for the operator.
15722ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15723 tok::TokenKind Kind,
15724 Expr *LHSExpr, Expr *RHSExpr) {
15725 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15726 assert(LHSExpr && "ActOnBinOp(): missing left expression")(static_cast <bool> (LHSExpr && "ActOnBinOp(): missing left expression"
) ? void (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\""
, "clang/lib/Sema/SemaExpr.cpp", 15726, __extension__ __PRETTY_FUNCTION__
))
;
15727 assert(RHSExpr && "ActOnBinOp(): missing right expression")(static_cast <bool> (RHSExpr && "ActOnBinOp(): missing right expression"
) ? void (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\""
, "clang/lib/Sema/SemaExpr.cpp", 15727, __extension__ __PRETTY_FUNCTION__
))
;
15728
15729 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15730 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15731
15732 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15733}
15734
15735void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15736 UnresolvedSetImpl &Functions) {
15737 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15738 if (OverOp != OO_None && OverOp != OO_Equal)
15739 LookupOverloadedOperatorName(OverOp, S, Functions);
15740
15741 // In C++20 onwards, we may have a second operator to look up.
15742 if (getLangOpts().CPlusPlus20) {
15743 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15744 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15745 }
15746}
15747
15748/// Build an overloaded binary operator expression in the given scope.
15749static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15750 BinaryOperatorKind Opc,
15751 Expr *LHS, Expr *RHS) {
15752 switch (Opc) {
15753 case BO_Assign:
15754 // In the non-overloaded case, we warn about self-assignment (x = x) for
15755 // both simple assignment and certain compound assignments where algebra
15756 // tells us the operation yields a constant result. When the operator is
15757 // overloaded, we can't do the latter because we don't want to assume that
15758 // those algebraic identities still apply; for example, a path-building
15759 // library might use operator/= to append paths. But it's still reasonable
15760 // to assume that simple assignment is just moving/copying values around
15761 // and so self-assignment is likely a bug.
15762 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15763 [[fallthrough]];
15764 case BO_DivAssign:
15765 case BO_RemAssign:
15766 case BO_SubAssign:
15767 case BO_AndAssign:
15768 case BO_OrAssign:
15769 case BO_XorAssign:
15770 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15771 break;
15772 default:
15773 break;
15774 }
15775
15776 // Find all of the overloaded operators visible from this point.
15777 UnresolvedSet<16> Functions;
15778 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15779
15780 // Build the (potentially-overloaded, potentially-dependent)
15781 // binary operation.
15782 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15783}
15784
15785ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15786 BinaryOperatorKind Opc,
15787 Expr *LHSExpr, Expr *RHSExpr) {
15788 ExprResult LHS, RHS;
15789 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15790 if (!LHS.isUsable() || !RHS.isUsable())
15791 return ExprError();
15792 LHSExpr = LHS.get();
15793 RHSExpr = RHS.get();
15794
15795 // We want to end up calling one of checkPseudoObjectAssignment
15796 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15797 // both expressions are overloadable or either is type-dependent),
15798 // or CreateBuiltinBinOp (in any other case). We also want to get
15799 // any placeholder types out of the way.
15800
15801 // Handle pseudo-objects in the LHS.
15802 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15803 // Assignments with a pseudo-object l-value need special analysis.
15804 if (pty->getKind() == BuiltinType::PseudoObject &&
15805 BinaryOperator::isAssignmentOp(Opc))
15806 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15807
15808 // Don't resolve overloads if the other type is overloadable.
15809 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15810 // We can't actually test that if we still have a placeholder,
15811 // though. Fortunately, none of the exceptions we see in that
15812 // code below are valid when the LHS is an overload set. Note
15813 // that an overload set can be dependently-typed, but it never
15814 // instantiates to having an overloadable type.
15815 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15816 if (resolvedRHS.isInvalid()) return ExprError();
15817 RHSExpr = resolvedRHS.get();
15818
15819 if (RHSExpr->isTypeDependent() ||
15820 RHSExpr->getType()->isOverloadableType())
15821 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15822 }
15823
15824 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15825 // template, diagnose the missing 'template' keyword instead of diagnosing
15826 // an invalid use of a bound member function.
15827 //
15828 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15829 // to C++1z [over.over]/1.4, but we already checked for that case above.
15830 if (Opc == BO_LT && inTemplateInstantiation() &&
15831 (pty->getKind() == BuiltinType::BoundMember ||
15832 pty->getKind() == BuiltinType::Overload)) {
15833 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15834 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15835 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15836 return isa<FunctionTemplateDecl>(ND);
15837 })) {
15838 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15839 : OE->getNameLoc(),
15840 diag::err_template_kw_missing)
15841 << OE->getName().getAsString() << "";
15842 return ExprError();
15843 }
15844 }
15845
15846 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15847 if (LHS.isInvalid()) return ExprError();
15848 LHSExpr = LHS.get();
15849 }
15850
15851 // Handle pseudo-objects in the RHS.
15852 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15853 // An overload in the RHS can potentially be resolved by the type
15854 // being assigned to.
15855 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15856 if (getLangOpts().CPlusPlus &&
15857 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15858 LHSExpr->getType()->isOverloadableType()))
15859 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15860
15861 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15862 }
15863
15864 // Don't resolve overloads if the other type is overloadable.
15865 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15866 LHSExpr->getType()->isOverloadableType())
15867 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15868
15869 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15870 if (!resolvedRHS.isUsable()) return ExprError();
15871 RHSExpr = resolvedRHS.get();
15872 }
15873
15874 if (getLangOpts().CPlusPlus) {
15875 // If either expression is type-dependent, always build an
15876 // overloaded op.
15877 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15878 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15879
15880 // Otherwise, build an overloaded op if either expression has an
15881 // overloadable type.
15882 if (LHSExpr->getType()->isOverloadableType() ||
15883 RHSExpr->getType()->isOverloadableType())
15884 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15885 }
15886
15887 if (getLangOpts().RecoveryAST &&
15888 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15889 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 15889, __extension__ __PRETTY_FUNCTION__))
;
15890 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&(static_cast <bool> ((LHSExpr->containsErrors() || RHSExpr
->containsErrors()) && "Should only occur in error-recovery path."
) ? void (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 15891, __extension__ __PRETTY_FUNCTION__
))
15891 "Should only occur in error-recovery path.")(static_cast <bool> ((LHSExpr->containsErrors() || RHSExpr
->containsErrors()) && "Should only occur in error-recovery path."
) ? void (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 15891, __extension__ __PRETTY_FUNCTION__
))
;
15892 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15893 // C [6.15.16] p3:
15894 // An assignment expression has the value of the left operand after the
15895 // assignment, but is not an lvalue.
15896 return CompoundAssignOperator::Create(
15897 Context, LHSExpr, RHSExpr, Opc,
15898 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15899 OpLoc, CurFPFeatureOverrides());
15900 QualType ResultType;
15901 switch (Opc) {
15902 case BO_Assign:
15903 ResultType = LHSExpr->getType().getUnqualifiedType();
15904 break;
15905 case BO_LT:
15906 case BO_GT:
15907 case BO_LE:
15908 case BO_GE:
15909 case BO_EQ:
15910 case BO_NE:
15911 case BO_LAnd:
15912 case BO_LOr:
15913 // These operators have a fixed result type regardless of operands.
15914 ResultType = Context.IntTy;
15915 break;
15916 case BO_Comma:
15917 ResultType = RHSExpr->getType();
15918 break;
15919 default:
15920 ResultType = Context.DependentTy;
15921 break;
15922 }
15923 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15924 VK_PRValue, OK_Ordinary, OpLoc,
15925 CurFPFeatureOverrides());
15926 }
15927
15928 // Build a built-in binary operation.
15929 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15930}
15931
15932static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15933 if (T.isNull() || T->isDependentType())
15934 return false;
15935
15936 if (!Ctx.isPromotableIntegerType(T))
15937 return true;
15938
15939 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15940}
15941
15942ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15943 UnaryOperatorKind Opc, Expr *InputExpr,
15944 bool IsAfterAmp) {
15945 ExprResult Input = InputExpr;
15946 ExprValueKind VK = VK_PRValue;
15947 ExprObjectKind OK = OK_Ordinary;
15948 QualType resultType;
15949 bool CanOverflow = false;
15950
15951 bool ConvertHalfVec = false;
15952 if (getLangOpts().OpenCL) {
15953 QualType Ty = InputExpr->getType();
15954 // The only legal unary operation for atomics is '&'.
15955 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15956 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15957 // only with a builtin functions and therefore should be disallowed here.
15958 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15959 || Ty->isBlockPointerType())) {
15960 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15961 << InputExpr->getType()
15962 << Input.get()->getSourceRange());
15963 }
15964 }
15965
15966 if (getLangOpts().HLSL && OpLoc.isValid()) {
15967 if (Opc == UO_AddrOf)
15968 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15969 if (Opc == UO_Deref)
15970 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15971 }
15972
15973 switch (Opc) {
15974 case UO_PreInc:
15975 case UO_PreDec:
15976 case UO_PostInc:
15977 case UO_PostDec:
15978 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15979 OpLoc,
15980 Opc == UO_PreInc ||
15981 Opc == UO_PostInc,
15982 Opc == UO_PreInc ||
15983 Opc == UO_PreDec);
15984 CanOverflow = isOverflowingIntegerType(Context, resultType);
15985 break;
15986 case UO_AddrOf:
15987 resultType = CheckAddressOfOperand(Input, OpLoc);
15988 CheckAddressOfNoDeref(InputExpr);
15989 RecordModifiableNonNullParam(*this, InputExpr);
15990 break;
15991 case UO_Deref: {
15992 Input = DefaultFunctionArrayLvalueConversion(Input.get());
15993 if (Input.isInvalid()) return ExprError();
15994 resultType =
15995 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15996 break;
15997 }
15998 case UO_Plus:
15999 case UO_Minus:
16000 CanOverflow = Opc == UO_Minus &&
16001 isOverflowingIntegerType(Context, Input.get()->getType());
16002 Input = UsualUnaryConversions(Input.get());
16003 if (Input.isInvalid()) return ExprError();
16004 // Unary plus and minus require promoting an operand of half vector to a
16005 // float vector and truncating the result back to a half vector. For now, we
16006 // do this only when HalfArgsAndReturns is set (that is, when the target is
16007 // arm or arm64).
16008 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16009
16010 // If the operand is a half vector, promote it to a float vector.
16011 if (ConvertHalfVec)
16012 Input = convertVector(Input.get(), Context.FloatTy, *this);
16013 resultType = Input.get()->getType();
16014 if (resultType->isDependentType())
16015 break;
16016 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16017 break;
16018 else if (resultType->isVectorType() &&
16019 // The z vector extensions don't allow + or - with bool vectors.
16020 (!Context.getLangOpts().ZVector ||
16021 resultType->castAs<VectorType>()->getVectorKind() !=
16022 VectorType::AltiVecBool))
16023 break;
16024 else if (resultType->isVLSTBuiltinType()) // SVE vectors allow + and -
16025 break;
16026 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16027 Opc == UO_Plus &&
16028 resultType->isPointerType())
16029 break;
16030
16031 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16032 << resultType << Input.get()->getSourceRange());
16033
16034 case UO_Not: // bitwise complement
16035 Input = UsualUnaryConversions(Input.get());
16036 if (Input.isInvalid())
16037 return ExprError();
16038 resultType = Input.get()->getType();
16039 if (resultType->isDependentType())
16040 break;
16041 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16042 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16043 // C99 does not support '~' for complex conjugation.
16044 Diag(OpLoc, diag::ext_integer_complement_complex)
16045 << resultType << Input.get()->getSourceRange();
16046 else if (resultType->hasIntegerRepresentation())
16047 break;
16048 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16049 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16050 // on vector float types.
16051 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16052 if (!T->isIntegerType())
16053 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16054 << resultType << Input.get()->getSourceRange());
16055 } else {
16056 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16057 << resultType << Input.get()->getSourceRange());
16058 }
16059 break;
16060
16061 case UO_LNot: // logical negation
16062 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16063 Input = DefaultFunctionArrayLvalueConversion(Input.get());
16064 if (Input.isInvalid()) return ExprError();
16065 resultType = Input.get()->getType();
16066
16067 // Though we still have to promote half FP to float...
16068 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16069 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
16070 resultType = Context.FloatTy;
16071 }
16072
16073 if (resultType->isDependentType())
16074 break;
16075 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16076 // C99 6.5.3.3p1: ok, fallthrough;
16077 if (Context.getLangOpts().CPlusPlus) {
16078 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16079 // operand contextually converted to bool.
16080 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16081 ScalarTypeToBooleanCastKind(resultType));
16082 } else if (Context.getLangOpts().OpenCL &&
16083 Context.getLangOpts().OpenCLVersion < 120) {
16084 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16085 // operate on scalar float types.
16086 if (!resultType->isIntegerType() && !resultType->isPointerType())
16087 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16088 << resultType << Input.get()->getSourceRange());
16089 }
16090 } else if (resultType->isExtVectorType()) {
16091 if (Context.getLangOpts().OpenCL &&
16092 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16093 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16094 // operate on vector float types.
16095 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16096 if (!T->isIntegerType())
16097 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16098 << resultType << Input.get()->getSourceRange());
16099 }
16100 // Vector logical not returns the signed variant of the operand type.
16101 resultType = GetSignedVectorType(resultType);
16102 break;
16103 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
16104 const VectorType *VTy = resultType->castAs<VectorType>();
16105 if (VTy->getVectorKind() != VectorType::GenericVector)
16106 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16107 << resultType << Input.get()->getSourceRange());
16108
16109 // Vector logical not returns the signed variant of the operand type.
16110 resultType = GetSignedVectorType(resultType);
16111 break;
16112 } else {
16113 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16114 << resultType << Input.get()->getSourceRange());
16115 }
16116
16117 // LNot always has type int. C99 6.5.3.3p5.
16118 // In C++, it's bool. C++ 5.3.1p8
16119 resultType = Context.getLogicalOperationType();
16120 break;
16121 case UO_Real:
16122 case UO_Imag:
16123 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16124 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
16125 // complex l-values to ordinary l-values and all other values to r-values.
16126 if (Input.isInvalid()) return ExprError();
16127 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16128 if (Input.get()->isGLValue() &&
16129 Input.get()->getObjectKind() == OK_Ordinary)
16130 VK = Input.get()->getValueKind();
16131 } else if (!getLangOpts().CPlusPlus) {
16132 // In C, a volatile scalar is read by __imag. In C++, it is not.
16133 Input = DefaultLvalueConversion(Input.get());
16134 }
16135 break;
16136 case UO_Extension:
16137 resultType = Input.get()->getType();
16138 VK = Input.get()->getValueKind();
16139 OK = Input.get()->getObjectKind();
16140 break;
16141 case UO_Coawait:
16142 // It's unnecessary to represent the pass-through operator co_await in the
16143 // AST; just return the input expression instead.
16144 assert(!Input.get()->getType()->isDependentType() &&(static_cast <bool> (!Input.get()->getType()->isDependentType
() && "the co_await expression must be non-dependant before "
"building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "clang/lib/Sema/SemaExpr.cpp", 16146, __extension__ __PRETTY_FUNCTION__
))
16145 "the co_await expression must be non-dependant before "(static_cast <bool> (!Input.get()->getType()->isDependentType
() && "the co_await expression must be non-dependant before "
"building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "clang/lib/Sema/SemaExpr.cpp", 16146, __extension__ __PRETTY_FUNCTION__
))
16146 "building operator co_await")(static_cast <bool> (!Input.get()->getType()->isDependentType
() && "the co_await expression must be non-dependant before "
"building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "clang/lib/Sema/SemaExpr.cpp", 16146, __extension__ __PRETTY_FUNCTION__
))
;
16147 return Input;
16148 }
16149 if (resultType.isNull() || Input.isInvalid())
16150 return ExprError();
16151
16152 // Check for array bounds violations in the operand of the UnaryOperator,
16153 // except for the '*' and '&' operators that have to be handled specially
16154 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16155 // that are explicitly defined as valid by the standard).
16156 if (Opc != UO_AddrOf && Opc != UO_Deref)
16157 CheckArrayAccess(Input.get());
16158
16159 auto *UO =
16160 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16161 OpLoc, CanOverflow, CurFPFeatureOverrides());
16162
16163 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16164 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16165 !isUnevaluatedContext())
16166 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16167
16168 // Convert the result back to a half vector.
16169 if (ConvertHalfVec)
16170 return convertVector(UO, Context.HalfTy, *this);
16171 return UO;
16172}
16173
16174/// Determine whether the given expression is a qualified member
16175/// access expression, of a form that could be turned into a pointer to member
16176/// with the address-of operator.
16177bool Sema::isQualifiedMemberAccess(Expr *E) {
16178 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16179 if (!DRE->getQualifier())
16180 return false;
16181
16182 ValueDecl *VD = DRE->getDecl();
16183 if (!VD->isCXXClassMember())
16184 return false;
16185
16186 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
16187 return true;
16188 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16189 return Method->isInstance();
16190
16191 return false;
16192 }
16193
16194 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16195 if (!ULE->getQualifier())
16196 return false;
16197
16198 for (NamedDecl *D : ULE->decls()) {
16199 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16200 if (Method->isInstance())
16201 return true;
16202 } else {
16203 // Overload set does not contain methods.
16204 break;
16205 }
16206 }
16207
16208 return false;
16209 }
16210
16211 return false;
16212}
16213
16214ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16215 UnaryOperatorKind Opc, Expr *Input,
16216 bool IsAfterAmp) {
16217 // First things first: handle placeholders so that the
16218 // overloaded-operator check considers the right type.
16219 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16220 // Increment and decrement of pseudo-object references.
16221 if (pty->getKind() == BuiltinType::PseudoObject &&
16222 UnaryOperator::isIncrementDecrementOp(Opc))
16223 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
16224
16225 // extension is always a builtin operator.
16226 if (Opc == UO_Extension)
16227 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16228
16229 // & gets special logic for several kinds of placeholder.
16230 // The builtin code knows what to do.
16231 if (Opc == UO_AddrOf &&
16232 (pty->getKind() == BuiltinType::Overload ||
16233 pty->getKind() == BuiltinType::UnknownAny ||
16234 pty->getKind() == BuiltinType::BoundMember))
16235 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16236
16237 // Anything else needs to be handled now.
16238 ExprResult Result = CheckPlaceholderExpr(Input);
16239 if (Result.isInvalid()) return ExprError();
16240 Input = Result.get();
16241 }
16242
16243 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16244 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16245 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16246 // Find all of the overloaded operators visible from this point.
16247 UnresolvedSet<16> Functions;
16248 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16249 if (S && OverOp != OO_None)
16250 LookupOverloadedOperatorName(OverOp, S, Functions);
16251
16252 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16253 }
16254
16255 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16256}
16257
16258// Unary Operators. 'Tok' is the token for the operator.
16259ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16260 Expr *Input, bool IsAfterAmp) {
16261 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16262 IsAfterAmp);
16263}
16264
16265/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16266ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16267 LabelDecl *TheDecl) {
16268 TheDecl->markUsed(Context);
16269 // Create the AST node. The address of a label always has type 'void*'.
16270 auto *Res = new (Context) AddrLabelExpr(
16271 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16272
16273 if (getCurFunction())
16274 getCurFunction()->AddrLabels.push_back(Res);
16275
16276 return Res;
16277}
16278
16279void Sema::ActOnStartStmtExpr() {
16280 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
16281}
16282
16283void Sema::ActOnStmtExprError() {
16284 // Note that function is also called by TreeTransform when leaving a
16285 // StmtExpr scope without rebuilding anything.
16286
16287 DiscardCleanupsInEvaluationContext();
16288 PopExpressionEvaluationContext();
16289}
16290
16291ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16292 SourceLocation RPLoc) {
16293 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16294}
16295
16296ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16297 SourceLocation RPLoc, unsigned TemplateDepth) {
16298 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")(static_cast <bool> (SubStmt && isa<CompoundStmt
>(SubStmt) && "Invalid action invocation!") ? void
(0) : __assert_fail ("SubStmt && isa<CompoundStmt>(SubStmt) && \"Invalid action invocation!\""
, "clang/lib/Sema/SemaExpr.cpp", 16298, __extension__ __PRETTY_FUNCTION__
))
;
16299 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16300
16301 if (hasAnyUnrecoverableErrorsInThisFunction())
16302 DiscardCleanupsInEvaluationContext();
16303 assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() &&
"cleanups within StmtExpr not correctly bound!") ? void (0) :
__assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\""
, "clang/lib/Sema/SemaExpr.cpp", 16304, __extension__ __PRETTY_FUNCTION__
))
16304 "cleanups within StmtExpr not correctly bound!")(static_cast <bool> (!Cleanup.exprNeedsCleanups() &&
"cleanups within StmtExpr not correctly bound!") ? void (0) :
__assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\""
, "clang/lib/Sema/SemaExpr.cpp", 16304, __extension__ __PRETTY_FUNCTION__
))
;
16305 PopExpressionEvaluationContext();
16306
16307 // FIXME: there are a variety of strange constraints to enforce here, for
16308 // example, it is not possible to goto into a stmt expression apparently.
16309 // More semantic analysis is needed.
16310
16311 // If there are sub-stmts in the compound stmt, take the type of the last one
16312 // as the type of the stmtexpr.
16313 QualType Ty = Context.VoidTy;
16314 bool StmtExprMayBindToTemp = false;
16315 if (!Compound->body_empty()) {
16316 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16317 if (const auto *LastStmt =
16318 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
16319 if (const Expr *Value = LastStmt->getExprStmt()) {
16320 StmtExprMayBindToTemp = true;
16321 Ty = Value->getType();
16322 }
16323 }
16324 }
16325
16326 // FIXME: Check that expression type is complete/non-abstract; statement
16327 // expressions are not lvalues.
16328 Expr *ResStmtExpr =
16329 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16330 if (StmtExprMayBindToTemp)
16331 return MaybeBindToTemporary(ResStmtExpr);
16332 return ResStmtExpr;
16333}
16334
16335ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16336 if (ER.isInvalid())
16337 return ExprError();
16338
16339 // Do function/array conversion on the last expression, but not
16340 // lvalue-to-rvalue. However, initialize an unqualified type.
16341 ER = DefaultFunctionArrayConversion(ER.get());
16342 if (ER.isInvalid())
16343 return ExprError();
16344 Expr *E = ER.get();
16345
16346 if (E->isTypeDependent())
16347 return E;
16348
16349 // In ARC, if the final expression ends in a consume, splice
16350 // the consume out and bind it later. In the alternate case
16351 // (when dealing with a retainable type), the result
16352 // initialization will create a produce. In both cases the
16353 // result will be +1, and we'll need to balance that out with
16354 // a bind.
16355 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16356 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16357 return Cast->getSubExpr();
16358
16359 // FIXME: Provide a better location for the initialization.
16360 return PerformCopyInitialization(
16361 InitializedEntity::InitializeStmtExprResult(
16362 E->getBeginLoc(), E->getType().getUnqualifiedType()),
16363 SourceLocation(), E);
16364}
16365
16366ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16367 TypeSourceInfo *TInfo,
16368 ArrayRef<OffsetOfComponent> Components,
16369 SourceLocation RParenLoc) {
16370 QualType ArgTy = TInfo->getType();
16371 bool Dependent = ArgTy->isDependentType();
16372 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16373
16374 // We must have at least one component that refers to the type, and the first
16375 // one is known to be a field designator. Verify that the ArgTy represents
16376 // a struct/union/class.
16377 if (!Dependent && !ArgTy->isRecordType())
16378 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16379 << ArgTy << TypeRange);
16380
16381 // Type must be complete per C99 7.17p3 because a declaring a variable
16382 // with an incomplete type would be ill-formed.
16383 if (!Dependent
16384 && RequireCompleteType(BuiltinLoc, ArgTy,
16385 diag::err_offsetof_incomplete_type, TypeRange))
16386 return ExprError();
16387
16388 bool DidWarnAboutNonPOD = false;
16389 QualType CurrentType = ArgTy;
16390 SmallVector<OffsetOfNode, 4> Comps;
16391 SmallVector<Expr*, 4> Exprs;
16392 for (const OffsetOfComponent &OC : Components) {
16393 if (OC.isBrackets) {
16394 // Offset of an array sub-field. TODO: Should we allow vector elements?
16395 if (!CurrentType->isDependentType()) {
16396 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16397 if(!AT)
16398 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16399 << CurrentType);
16400 CurrentType = AT->getElementType();
16401 } else
16402 CurrentType = Context.DependentTy;
16403
16404 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16405 if (IdxRval.isInvalid())
16406 return ExprError();
16407 Expr *Idx = IdxRval.get();
16408
16409 // The expression must be an integral expression.
16410 // FIXME: An integral constant expression?
16411 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16412 !Idx->getType()->isIntegerType())
16413 return ExprError(
16414 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16415 << Idx->getSourceRange());
16416
16417 // Record this array index.
16418 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16419 Exprs.push_back(Idx);
16420 continue;
16421 }
16422
16423 // Offset of a field.
16424 if (CurrentType->isDependentType()) {
16425 // We have the offset of a field, but we can't look into the dependent
16426 // type. Just record the identifier of the field.
16427 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16428 CurrentType = Context.DependentTy;
16429 continue;
16430 }
16431
16432 // We need to have a complete type to look into.
16433 if (RequireCompleteType(OC.LocStart, CurrentType,
16434 diag::err_offsetof_incomplete_type))
16435 return ExprError();
16436
16437 // Look for the designated field.
16438 const RecordType *RC = CurrentType->getAs<RecordType>();
16439 if (!RC)
16440 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16441 << CurrentType);
16442 RecordDecl *RD = RC->getDecl();
16443
16444 // C++ [lib.support.types]p5:
16445 // The macro offsetof accepts a restricted set of type arguments in this
16446 // International Standard. type shall be a POD structure or a POD union
16447 // (clause 9).
16448 // C++11 [support.types]p4:
16449 // If type is not a standard-layout class (Clause 9), the results are
16450 // undefined.
16451 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16452 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16453 unsigned DiagID =
16454 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16455 : diag::ext_offsetof_non_pod_type;
16456
16457 if (!IsSafe && !DidWarnAboutNonPOD &&
16458 DiagRuntimeBehavior(BuiltinLoc, nullptr,
16459 PDiag(DiagID)
16460 << SourceRange(Components[0].LocStart, OC.LocEnd)
16461 << CurrentType))
16462 DidWarnAboutNonPOD = true;
16463 }
16464
16465 // Look for the field.
16466 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16467 LookupQualifiedName(R, RD);
16468 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16469 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16470 if (!MemberDecl) {
16471 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16472 MemberDecl = IndirectMemberDecl->getAnonField();
16473 }
16474
16475 if (!MemberDecl)
16476 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
16477 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
16478 OC.LocEnd));
16479
16480 // C99 7.17p3:
16481 // (If the specified member is a bit-field, the behavior is undefined.)
16482 //
16483 // We diagnose this as an error.
16484 if (MemberDecl->isBitField()) {
16485 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16486 << MemberDecl->getDeclName()
16487 << SourceRange(BuiltinLoc, RParenLoc);
16488 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16489 return ExprError();
16490 }
16491
16492 RecordDecl *Parent = MemberDecl->getParent();
16493 if (IndirectMemberDecl)
16494 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16495
16496 // If the member was found in a base class, introduce OffsetOfNodes for
16497 // the base class indirections.
16498 CXXBasePaths Paths;
16499 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16500 Paths)) {
16501 if (Paths.getDetectedVirtual()) {
16502 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16503 << MemberDecl->getDeclName()
16504 << SourceRange(BuiltinLoc, RParenLoc);
16505 return ExprError();
16506 }
16507
16508 CXXBasePath &Path = Paths.front();
16509 for (const CXXBasePathElement &B : Path)
16510 Comps.push_back(OffsetOfNode(B.Base));
16511 }
16512
16513 if (IndirectMemberDecl) {
16514 for (auto *FI : IndirectMemberDecl->chain()) {
16515 assert(isa<FieldDecl>(FI))(static_cast <bool> (isa<FieldDecl>(FI)) ? void (
0) : __assert_fail ("isa<FieldDecl>(FI)", "clang/lib/Sema/SemaExpr.cpp"
, 16515, __extension__ __PRETTY_FUNCTION__))
;
16516 Comps.push_back(OffsetOfNode(OC.LocStart,
16517 cast<FieldDecl>(FI), OC.LocEnd));
16518 }
16519 } else
16520 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16521
16522 CurrentType = MemberDecl->getType().getNonReferenceType();
16523 }
16524
16525 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16526 Comps, Exprs, RParenLoc);
16527}
16528
16529ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16530 SourceLocation BuiltinLoc,
16531 SourceLocation TypeLoc,
16532 ParsedType ParsedArgTy,
16533 ArrayRef<OffsetOfComponent> Components,
16534 SourceLocation RParenLoc) {
16535
16536 TypeSourceInfo *ArgTInfo;
16537 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16538 if (ArgTy.isNull())
16539 return ExprError();
16540
16541 if (!ArgTInfo)
16542 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16543
16544 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16545}
16546
16547
16548ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16549 Expr *CondExpr,
16550 Expr *LHSExpr, Expr *RHSExpr,
16551 SourceLocation RPLoc) {
16552 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(static_cast <bool> ((CondExpr && LHSExpr &&
RHSExpr) && "Missing type argument(s)") ? void (0) :
__assert_fail ("(CondExpr && LHSExpr && RHSExpr) && \"Missing type argument(s)\""
, "clang/lib/Sema/SemaExpr.cpp", 16552, __extension__ __PRETTY_FUNCTION__
))
;
16553
16554 ExprValueKind VK = VK_PRValue;
16555 ExprObjectKind OK = OK_Ordinary;
16556 QualType resType;
16557 bool CondIsTrue = false;
16558 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16559 resType = Context.DependentTy;
16560 } else {
16561 // The conditional expression is required to be a constant expression.
16562 llvm::APSInt condEval(32);
16563 ExprResult CondICE = VerifyIntegerConstantExpression(
16564 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16565 if (CondICE.isInvalid())
16566 return ExprError();
16567 CondExpr = CondICE.get();
16568 CondIsTrue = condEval.getZExtValue();
16569
16570 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16571 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16572
16573 resType = ActiveExpr->getType();
16574 VK = ActiveExpr->getValueKind();
16575 OK = ActiveExpr->getObjectKind();
16576 }
16577
16578 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16579 resType, VK, OK, RPLoc, CondIsTrue);
16580}
16581
16582//===----------------------------------------------------------------------===//
16583// Clang Extensions.
16584//===----------------------------------------------------------------------===//
16585
16586/// ActOnBlockStart - This callback is invoked when a block literal is started.
16587void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16588 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16589
16590 if (LangOpts.CPlusPlus) {
16591 MangleNumberingContext *MCtx;
16592 Decl *ManglingContextDecl;
16593 std::tie(MCtx, ManglingContextDecl) =
16594 getCurrentMangleNumberContext(Block->getDeclContext());
16595 if (MCtx) {
16596 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16597 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16598 }
16599 }
16600
16601 PushBlockScope(CurScope, Block);
16602 CurContext->addDecl(Block);
16603 if (CurScope)
16604 PushDeclContext(CurScope, Block);
16605 else
16606 CurContext = Block;
16607
16608 getCurBlock()->HasImplicitReturnType = true;
16609
16610 // Enter a new evaluation context to insulate the block from any
16611 // cleanups from the enclosing full-expression.
16612 PushExpressionEvaluationContext(
16613 ExpressionEvaluationContext::PotentiallyEvaluated);
16614}
16615
16616void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16617 Scope *CurScope) {
16618 assert(ParamInfo.getIdentifier() == nullptr &&(static_cast <bool> (ParamInfo.getIdentifier() == nullptr
&& "block-id should have no identifier!") ? void (0)
: __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\""
, "clang/lib/Sema/SemaExpr.cpp", 16619, __extension__ __PRETTY_FUNCTION__
))
16619 "block-id should have no identifier!")(static_cast <bool> (ParamInfo.getIdentifier() == nullptr
&& "block-id should have no identifier!") ? void (0)
: __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\""
, "clang/lib/Sema/SemaExpr.cpp", 16619, __extension__ __PRETTY_FUNCTION__
))
;
16620 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral)(static_cast <bool> (ParamInfo.getContext() == DeclaratorContext
::BlockLiteral) ? void (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteral"
, "clang/lib/Sema/SemaExpr.cpp", 16620, __extension__ __PRETTY_FUNCTION__
))
;
16621 BlockScopeInfo *CurBlock = getCurBlock();
16622
16623 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16624 QualType T = Sig->getType();
16625
16626 // FIXME: We should allow unexpanded parameter packs here, but that would,
16627 // in turn, make the block expression contain unexpanded parameter packs.
16628 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16629 // Drop the parameters.
16630 FunctionProtoType::ExtProtoInfo EPI;
16631 EPI.HasTrailingReturn = false;
16632 EPI.TypeQuals.addConst();
16633 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
16634 Sig = Context.getTrivialTypeSourceInfo(T);
16635 }
16636
16637 // GetTypeForDeclarator always produces a function type for a block
16638 // literal signature. Furthermore, it is always a FunctionProtoType
16639 // unless the function was written with a typedef.
16640 assert(T->isFunctionType() &&(static_cast <bool> (T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature"
) ? void (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\""
, "clang/lib/Sema/SemaExpr.cpp", 16641, __extension__ __PRETTY_FUNCTION__
))
16641 "GetTypeForDeclarator made a non-function block signature")(static_cast <bool> (T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature"
) ? void (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\""
, "clang/lib/Sema/SemaExpr.cpp", 16641, __extension__ __PRETTY_FUNCTION__
))
;
16642
16643 // Look for an explicit signature in that function type.
16644 FunctionProtoTypeLoc ExplicitSignature;
16645
16646 if ((ExplicitSignature = Sig->getTypeLoc()
16647 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16648
16649 // Check whether that explicit signature was synthesized by
16650 // GetTypeForDeclarator. If so, don't save that as part of the
16651 // written signature.
16652 if (ExplicitSignature.getLocalRangeBegin() ==
16653 ExplicitSignature.getLocalRangeEnd()) {
16654 // This would be much cheaper if we stored TypeLocs instead of
16655 // TypeSourceInfos.
16656 TypeLoc Result = ExplicitSignature.getReturnLoc();
16657 unsigned Size = Result.getFullDataSize();
16658 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16659 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16660
16661 ExplicitSignature = FunctionProtoTypeLoc();
16662 }
16663 }
16664
16665 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16666 CurBlock->FunctionType = T;
16667
16668 const auto *Fn = T->castAs<FunctionType>();
16669 QualType RetTy = Fn->getReturnType();
16670 bool isVariadic =
16671 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16672
16673 CurBlock->TheDecl->setIsVariadic(isVariadic);
16674
16675 // Context.DependentTy is used as a placeholder for a missing block
16676 // return type. TODO: what should we do with declarators like:
16677 // ^ * { ... }
16678 // If the answer is "apply template argument deduction"....
16679 if (RetTy != Context.DependentTy) {
16680 CurBlock->ReturnType = RetTy;
16681 CurBlock->TheDecl->setBlockMissingReturnType(false);
16682 CurBlock->HasImplicitReturnType = false;
16683 }
16684
16685 // Push block parameters from the declarator if we had them.
16686 SmallVector<ParmVarDecl*, 8> Params;
16687 if (ExplicitSignature) {
16688 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16689 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16690 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16691 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16692 // Diagnose this as an extension in C17 and earlier.
16693 if (!getLangOpts().C2x)
16694 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
16695 }
16696 Params.push_back(Param);
16697 }
16698
16699 // Fake up parameter variables if we have a typedef, like
16700 // ^ fntype { ... }
16701 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16702 for (const auto &I : Fn->param_types()) {
16703 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16704 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16705 Params.push_back(Param);
16706 }
16707 }
16708
16709 // Set the parameters on the block decl.
16710 if (!Params.empty()) {
16711 CurBlock->TheDecl->setParams(Params);
16712 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16713 /*CheckParameterNames=*/false);
16714 }
16715
16716 // Finally we can process decl attributes.
16717 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16718
16719 // Put the parameter variables in scope.
16720 for (auto *AI : CurBlock->TheDecl->parameters()) {
16721 AI->setOwningFunction(CurBlock->TheDecl);
16722
16723 // If this has an identifier, add it to the scope stack.
16724 if (AI->getIdentifier()) {
16725 CheckShadow(CurBlock->TheScope, AI);
16726
16727 PushOnScopeChains(AI, CurBlock->TheScope);
16728 }
16729 }
16730}
16731
16732/// ActOnBlockError - If there is an error parsing a block, this callback
16733/// is invoked to pop the information about the block from the action impl.
16734void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16735 // Leave the expression-evaluation context.
16736 DiscardCleanupsInEvaluationContext();
16737 PopExpressionEvaluationContext();
16738
16739 // Pop off CurBlock, handle nested blocks.
16740 PopDeclContext();
16741 PopFunctionScopeInfo();
16742}
16743
16744/// ActOnBlockStmtExpr - This is called when the body of a block statement
16745/// literal was successfully completed. ^(int x){...}
16746ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16747 Stmt *Body, Scope *CurScope) {
16748 // If blocks are disabled, emit an error.
16749 if (!LangOpts.Blocks)
16750 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16751
16752 // Leave the expression-evaluation context.
16753 if (hasAnyUnrecoverableErrorsInThisFunction())
16754 DiscardCleanupsInEvaluationContext();
16755 assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() &&
"cleanups within block not correctly bound!") ? void (0) : __assert_fail
("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\""
, "clang/lib/Sema/SemaExpr.cpp", 16756, __extension__ __PRETTY_FUNCTION__
))
16756 "cleanups within block not correctly bound!")(static_cast <bool> (!Cleanup.exprNeedsCleanups() &&
"cleanups within block not correctly bound!") ? void (0) : __assert_fail
("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\""
, "clang/lib/Sema/SemaExpr.cpp", 16756, __extension__ __PRETTY_FUNCTION__
))
;
16757 PopExpressionEvaluationContext();
16758
16759 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16760 BlockDecl *BD = BSI->TheDecl;
16761
16762 if (BSI->HasImplicitReturnType)
16763 deduceClosureReturnType(*BSI);
16764
16765 QualType RetTy = Context.VoidTy;
16766 if (!BSI->ReturnType.isNull())
16767 RetTy = BSI->ReturnType;
16768
16769 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16770 QualType BlockTy;
16771
16772 // If the user wrote a function type in some form, try to use that.
16773 if (!BSI->FunctionType.isNull()) {
16774 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16775
16776 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16777 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16778
16779 // Turn protoless block types into nullary block types.
16780 if (isa<FunctionNoProtoType>(FTy)) {
16781 FunctionProtoType::ExtProtoInfo EPI;
16782 EPI.ExtInfo = Ext;
16783 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16784
16785 // Otherwise, if we don't need to change anything about the function type,
16786 // preserve its sugar structure.
16787 } else if (FTy->getReturnType() == RetTy &&
16788 (!NoReturn || FTy->getNoReturnAttr())) {
16789 BlockTy = BSI->FunctionType;
16790
16791 // Otherwise, make the minimal modifications to the function type.
16792 } else {
16793 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16794 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16795 EPI.TypeQuals = Qualifiers();
16796 EPI.ExtInfo = Ext;
16797 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16798 }
16799
16800 // If we don't have a function type, just build one from nothing.
16801 } else {
16802 FunctionProtoType::ExtProtoInfo EPI;
16803 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16804 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16805 }
16806
16807 DiagnoseUnusedParameters(BD->parameters());
16808 BlockTy = Context.getBlockPointerType(BlockTy);
16809
16810 // If needed, diagnose invalid gotos and switches in the block.
16811 if (getCurFunction()->NeedsScopeChecking() &&
16812 !PP.isCodeCompletionEnabled())
16813 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16814
16815 BD->setBody(cast<CompoundStmt>(Body));
16816
16817 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16818 DiagnoseUnguardedAvailabilityViolations(BD);
16819
16820 // Try to apply the named return value optimization. We have to check again
16821 // if we can do this, though, because blocks keep return statements around
16822 // to deduce an implicit return type.
16823 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16824 !BD->isDependentContext())
16825 computeNRVO(Body, BSI);
16826
16827 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16828 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16829 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16830 NTCUK_Destruct|NTCUK_Copy);
16831
16832 PopDeclContext();
16833
16834 // Set the captured variables on the block.
16835 SmallVector<BlockDecl::Capture, 4> Captures;
16836 for (Capture &Cap : BSI->Captures) {
16837 if (Cap.isInvalid() || Cap.isThisCapture())
16838 continue;
16839 // Cap.getVariable() is always a VarDecl because
16840 // blocks cannot capture structured bindings or other ValueDecl kinds.
16841 auto *Var = cast<VarDecl>(Cap.getVariable());
16842 Expr *CopyExpr = nullptr;
16843 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16844 if (const RecordType *Record =
16845 Cap.getCaptureType()->getAs<RecordType>()) {
16846 // The capture logic needs the destructor, so make sure we mark it.
16847 // Usually this is unnecessary because most local variables have
16848 // their destructors marked at declaration time, but parameters are
16849 // an exception because it's technically only the call site that
16850 // actually requires the destructor.
16851 if (isa<ParmVarDecl>(Var))
16852 FinalizeVarWithDestructor(Var, Record);
16853
16854 // Enter a separate potentially-evaluated context while building block
16855 // initializers to isolate their cleanups from those of the block
16856 // itself.
16857 // FIXME: Is this appropriate even when the block itself occurs in an
16858 // unevaluated operand?
16859 EnterExpressionEvaluationContext EvalContext(
16860 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16861
16862 SourceLocation Loc = Cap.getLocation();
16863
16864 ExprResult Result = BuildDeclarationNameExpr(
16865 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16866
16867 // According to the blocks spec, the capture of a variable from
16868 // the stack requires a const copy constructor. This is not true
16869 // of the copy/move done to move a __block variable to the heap.
16870 if (!Result.isInvalid() &&
16871 !Result.get()->getType().isConstQualified()) {
16872 Result = ImpCastExprToType(Result.get(),
16873 Result.get()->getType().withConst(),
16874 CK_NoOp, VK_LValue);
16875 }
16876
16877 if (!Result.isInvalid()) {
16878 Result = PerformCopyInitialization(
16879 InitializedEntity::InitializeBlock(Var->getLocation(),
16880 Cap.getCaptureType()),
16881 Loc, Result.get());
16882 }
16883
16884 // Build a full-expression copy expression if initialization
16885 // succeeded and used a non-trivial constructor. Recover from
16886 // errors by pretending that the copy isn't necessary.
16887 if (!Result.isInvalid() &&
16888 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16889 ->isTrivial()) {
16890 Result = MaybeCreateExprWithCleanups(Result);
16891 CopyExpr = Result.get();
16892 }
16893 }
16894 }
16895
16896 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16897 CopyExpr);
16898 Captures.push_back(NewCap);
16899 }
16900 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16901
16902 // Pop the block scope now but keep it alive to the end of this function.
16903 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16904 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16905
16906 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16907
16908 // If the block isn't obviously global, i.e. it captures anything at
16909 // all, then we need to do a few things in the surrounding context:
16910 if (Result->getBlockDecl()->hasCaptures()) {
16911 // First, this expression has a new cleanup object.
16912 ExprCleanupObjects.push_back(Result->getBlockDecl());
16913 Cleanup.setExprNeedsCleanups(true);
16914
16915 // It also gets a branch-protected scope if any of the captured
16916 // variables needs destruction.
16917 for (const auto &CI : Result->getBlockDecl()->captures()) {
16918 const VarDecl *var = CI.getVariable();
16919 if (var->getType().isDestructedType() != QualType::DK_none) {
16920 setFunctionHasBranchProtectedScope();
16921 break;
16922 }
16923 }
16924 }
16925
16926 if (getCurFunction())
16927 getCurFunction()->addBlock(BD);
16928
16929 return Result;
16930}
16931
16932ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16933 SourceLocation RPLoc) {
16934 TypeSourceInfo *TInfo;
16935 GetTypeFromParser(Ty, &TInfo);
16936 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16937}
16938
16939ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16940 Expr *E, TypeSourceInfo *TInfo,
16941 SourceLocation RPLoc) {
16942 Expr *OrigExpr = E;
16943 bool IsMS = false;
16944
16945 // CUDA device code does not support varargs.
16946 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16947 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16948 CUDAFunctionTarget T = IdentifyCUDATarget(F);
16949 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16950 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16951 }
16952 }
16953
16954 // NVPTX does not support va_arg expression.
16955 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16956 Context.getTargetInfo().getTriple().isNVPTX())
16957 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16958
16959 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16960 // as Microsoft ABI on an actual Microsoft platform, where
16961 // __builtin_ms_va_list and __builtin_va_list are the same.)
16962 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16963 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16964 QualType MSVaListType = Context.getBuiltinMSVaListType();
16965 if (Context.hasSameType(MSVaListType, E->getType())) {
16966 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16967 return ExprError();
16968 IsMS = true;
16969 }
16970 }
16971
16972 // Get the va_list type
16973 QualType VaListType = Context.getBuiltinVaListType();
16974 if (!IsMS) {
16975 if (VaListType->isArrayType()) {
16976 // Deal with implicit array decay; for example, on x86-64,
16977 // va_list is an array, but it's supposed to decay to
16978 // a pointer for va_arg.
16979 VaListType = Context.getArrayDecayedType(VaListType);
16980 // Make sure the input expression also decays appropriately.
16981 ExprResult Result = UsualUnaryConversions(E);
16982 if (Result.isInvalid())
16983 return ExprError();
16984 E = Result.get();
16985 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16986 // If va_list is a record type and we are compiling in C++ mode,
16987 // check the argument using reference binding.
16988 InitializedEntity Entity = InitializedEntity::InitializeParameter(
16989 Context, Context.getLValueReferenceType(VaListType), false);
16990 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16991 if (Init.isInvalid())
16992 return ExprError();
16993 E = Init.getAs<Expr>();
16994 } else {
16995 // Otherwise, the va_list argument must be an l-value because
16996 // it is modified by va_arg.
16997 if (!E->isTypeDependent() &&
16998 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16999 return ExprError();
17000 }
17001 }
17002
17003 if (!IsMS && !E->isTypeDependent() &&
17004 !Context.hasSameType(VaListType, E->getType()))
17005 return ExprError(
17006 Diag(E->getBeginLoc(),
17007 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17008 << OrigExpr->getType() << E->getSourceRange());
17009
17010 if (!TInfo->getType()->isDependentType()) {
17011 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17012 diag::err_second_parameter_to_va_arg_incomplete,
17013 TInfo->getTypeLoc()))
17014 return ExprError();
17015
17016 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
17017 TInfo->getType(),
17018 diag::err_second_parameter_to_va_arg_abstract,
17019 TInfo->getTypeLoc()))
17020 return ExprError();
17021
17022 if (!TInfo->getType().isPODType(Context)) {
17023 Diag(TInfo->getTypeLoc().getBeginLoc(),
17024 TInfo->getType()->isObjCLifetimeType()
17025 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17026 : diag::warn_second_parameter_to_va_arg_not_pod)
17027 << TInfo->getType()
17028 << TInfo->getTypeLoc().getSourceRange();
17029 }
17030
17031 // Check for va_arg where arguments of the given type will be promoted
17032 // (i.e. this va_arg is guaranteed to have undefined behavior).
17033 QualType PromoteType;
17034 if (Context.isPromotableIntegerType(TInfo->getType())) {
17035 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17036 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17037 // and C2x 7.16.1.1p2 says, in part:
17038 // If type is not compatible with the type of the actual next argument
17039 // (as promoted according to the default argument promotions), the
17040 // behavior is undefined, except for the following cases:
17041 // - both types are pointers to qualified or unqualified versions of
17042 // compatible types;
17043 // - one type is a signed integer type, the other type is the
17044 // corresponding unsigned integer type, and the value is
17045 // representable in both types;
17046 // - one type is pointer to qualified or unqualified void and the
17047 // other is a pointer to a qualified or unqualified character type.
17048 // Given that type compatibility is the primary requirement (ignoring
17049 // qualifications), you would think we could call typesAreCompatible()
17050 // directly to test this. However, in C++, that checks for *same type*,
17051 // which causes false positives when passing an enumeration type to
17052 // va_arg. Instead, get the underlying type of the enumeration and pass
17053 // that.
17054 QualType UnderlyingType = TInfo->getType();
17055 if (const auto *ET = UnderlyingType->getAs<EnumType>())
17056 UnderlyingType = ET->getDecl()->getIntegerType();
17057 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17058 /*CompareUnqualified*/ true))
17059 PromoteType = QualType();
17060
17061 // If the types are still not compatible, we need to test whether the
17062 // promoted type and the underlying type are the same except for
17063 // signedness. Ask the AST for the correctly corresponding type and see
17064 // if that's compatible.
17065 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17066 PromoteType->isUnsignedIntegerType() !=
17067 UnderlyingType->isUnsignedIntegerType()) {
17068 UnderlyingType =
17069 UnderlyingType->isUnsignedIntegerType()
17070 ? Context.getCorrespondingSignedType(UnderlyingType)
17071 : Context.getCorrespondingUnsignedType(UnderlyingType);
17072 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17073 /*CompareUnqualified*/ true))
17074 PromoteType = QualType();
17075 }
17076 }
17077 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17078 PromoteType = Context.DoubleTy;
17079 if (!PromoteType.isNull())
17080 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
17081 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17082 << TInfo->getType()
17083 << PromoteType
17084 << TInfo->getTypeLoc().getSourceRange());
17085 }
17086
17087 QualType T = TInfo->getType().getNonLValueExprType(Context);
17088 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17089}
17090
17091ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17092 // The type of __null will be int or long, depending on the size of
17093 // pointers on the target.
17094 QualType Ty;
17095 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17096 if (pw == Context.getTargetInfo().getIntWidth())
17097 Ty = Context.IntTy;
17098 else if (pw == Context.getTargetInfo().getLongWidth())
17099 Ty = Context.LongTy;
17100 else if (pw == Context.getTargetInfo().getLongLongWidth())
17101 Ty = Context.LongLongTy;
17102 else {
17103 llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!"
, "clang/lib/Sema/SemaExpr.cpp", 17103)
;
17104 }
17105
17106 return new (Context) GNUNullExpr(Ty, TokenLoc);
17107}
17108
17109static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17110 CXXRecordDecl *ImplDecl = nullptr;
17111
17112 // Fetch the std::source_location::__impl decl.
17113 if (NamespaceDecl *Std = S.getStdNamespace()) {
17114 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17115 Loc, Sema::LookupOrdinaryName);
17116 if (S.LookupQualifiedName(ResultSL, Std)) {
17117 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17118 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17119 Loc, Sema::LookupOrdinaryName);
17120 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17121 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17122 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17123 }
17124 }
17125 }
17126 }
17127
17128 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17129 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17130 return nullptr;
17131 }
17132
17133 // Verify that __impl is a trivial struct type, with no base classes, and with
17134 // only the four expected fields.
17135 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17136 ImplDecl->getNumBases() != 0) {
17137 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17138 return nullptr;
17139 }
17140
17141 unsigned Count = 0;
17142 for (FieldDecl *F : ImplDecl->fields()) {
17143 StringRef Name = F->getName();
17144
17145 if (Name == "_M_file_name") {
17146 if (F->getType() !=
17147 S.Context.getPointerType(S.Context.CharTy.withConst()))
17148 break;
17149 Count++;
17150 } else if (Name == "_M_function_name") {
17151 if (F->getType() !=
17152 S.Context.getPointerType(S.Context.CharTy.withConst()))
17153 break;
17154 Count++;
17155 } else if (Name == "_M_line") {
17156 if (!F->getType()->isIntegerType())
17157 break;
17158 Count++;
17159 } else if (Name == "_M_column") {
17160 if (!F->getType()->isIntegerType())
17161 break;
17162 Count++;
17163 } else {
17164 Count = 100; // invalid
17165 break;
17166 }
17167 }
17168 if (Count != 4) {
17169 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17170 return nullptr;
17171 }
17172
17173 return ImplDecl;
17174}
17175
17176ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
17177 SourceLocation BuiltinLoc,
17178 SourceLocation RPLoc) {
17179 QualType ResultTy;
17180 switch (Kind) {
17181 case SourceLocExpr::File:
17182 case SourceLocExpr::FileName:
17183 case SourceLocExpr::Function: {
17184 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17185 ResultTy =
17186 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17187 break;
17188 }
17189 case SourceLocExpr::Line:
17190 case SourceLocExpr::Column:
17191 ResultTy = Context.UnsignedIntTy;
17192 break;
17193 case SourceLocExpr::SourceLocStruct:
17194 if (!StdSourceLocationImplDecl) {
17195 StdSourceLocationImplDecl =
17196 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17197 if (!StdSourceLocationImplDecl)
17198 return ExprError();
17199 }
17200 ResultTy = Context.getPointerType(
17201 Context.getRecordType(StdSourceLocationImplDecl).withConst());
17202 break;
17203 }
17204
17205 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17206}
17207
17208ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
17209 QualType ResultTy,
17210 SourceLocation BuiltinLoc,
17211 SourceLocation RPLoc,
17212 DeclContext *ParentContext) {
17213 return new (Context)
17214 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17215}
17216
17217bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
17218 bool Diagnose) {
17219 if (!getLangOpts().ObjC)
17220 return false;
17221
17222 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
17223 if (!PT)
17224 return false;
17225 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
17226
17227 // Ignore any parens, implicit casts (should only be
17228 // array-to-pointer decays), and not-so-opaque values. The last is
17229 // important for making this trigger for property assignments.
17230 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
17231 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
17232 if (OV->getSourceExpr())
17233 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
17234
17235 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
17236 if (!PT->isObjCIdType() &&
17237 !(ID && ID->getIdentifier()->isStr("NSString")))
17238 return false;
17239 if (!SL->isOrdinary())
17240 return false;
17241
17242 if (Diagnose) {
17243 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
17244 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
17245 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
17246 }
17247 return true;
17248 }
17249
17250 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
17251 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
17252 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
17253 !SrcExpr->isNullPointerConstant(
17254 getASTContext(), Expr::NPC_NeverValueDependent)) {
17255 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
17256 return false;
17257 if (Diagnose) {
17258 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
17259 << /*number*/1
17260 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
17261 Expr *NumLit =
17262 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
17263 if (NumLit)
17264 Exp = NumLit;
17265 }
17266 return true;
17267 }
17268
17269 return false;
17270}
17271
17272static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17273 const Expr *SrcExpr) {
17274 if (!DstType->isFunctionPointerType() ||
17275 !SrcExpr->getType()->isFunctionType())
17276 return false;
17277
17278 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17279 if (!DRE)
17280 return false;
17281
17282 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17283 if (!FD)
17284 return false;
17285
17286 return !S.checkAddressOfFunctionIsAvailable(FD,
17287 /*Complain=*/true,
17288 SrcExpr->getBeginLoc());
17289}
17290
17291bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17292 SourceLocation Loc,
17293 QualType DstType, QualType SrcType,
17294 Expr *SrcExpr, AssignmentAction Action,
17295 bool *Complained) {
17296 if (Complained)
17297 *Complained = false;
17298
17299 // Decode the result (notice that AST's are still created for extensions).
17300 bool CheckInferredResultType = false;
17301 bool isInvalid = false;
17302 unsigned DiagKind = 0;
17303 ConversionFixItGenerator ConvHints;
17304 bool MayHaveConvFixit = false;
17305 bool MayHaveFunctionDiff = false;
17306 const ObjCInterfaceDecl *IFace = nullptr;
17307 const ObjCProtocolDecl *PDecl = nullptr;
17308
17309 switch (ConvTy) {
17310 case Compatible:
17311 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17312 return false;
17313
17314 case PointerToInt:
17315 if (getLangOpts().CPlusPlus) {
17316 DiagKind = diag::err_typecheck_convert_pointer_int;
17317 isInvalid = true;
17318 } else {
17319 DiagKind = diag::ext_typecheck_convert_pointer_int;
17320 }
17321 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17322 MayHaveConvFixit = true;
17323 break;
17324 case IntToPointer:
17325 if (getLangOpts().CPlusPlus) {
17326 DiagKind = diag::err_typecheck_convert_int_pointer;
17327 isInvalid = true;
17328 } else {
17329 DiagKind = diag::ext_typecheck_convert_int_pointer;
17330 }
17331 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17332 MayHaveConvFixit = true;
17333 break;
17334 case IncompatibleFunctionPointerStrict:
17335 DiagKind =
17336 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17337 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17338 MayHaveConvFixit = true;
17339 break;
17340 case IncompatibleFunctionPointer:
17341 if (getLangOpts().CPlusPlus) {
17342 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17343 isInvalid = true;
17344 } else {
17345 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17346 }
17347 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17348 MayHaveConvFixit = true;
17349 break;
17350 case IncompatiblePointer:
17351 if (Action == AA_Passing_CFAudited) {
17352 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17353 } else if (getLangOpts().CPlusPlus) {
17354 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17355 isInvalid = true;
17356 } else {
17357 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17358 }
17359 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17360 SrcType->isObjCObjectPointerType();
17361 if (!CheckInferredResultType) {
17362 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17363 } else if (CheckInferredResultType) {
17364 SrcType = SrcType.getUnqualifiedType();
17365 DstType = DstType.getUnqualifiedType();
17366 }
17367 MayHaveConvFixit = true;
17368 break;
17369 case IncompatiblePointerSign:
17370 if (getLangOpts().CPlusPlus) {
17371 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17372 isInvalid = true;
17373 } else {
17374 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17375 }
17376 break;
17377 case FunctionVoidPointer:
17378 if (getLangOpts().CPlusPlus) {
17379 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17380 isInvalid = true;
17381 } else {
17382 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17383 }
17384 break;
17385 case IncompatiblePointerDiscardsQualifiers: {
17386 // Perform array-to-pointer decay if necessary.
17387 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17388
17389 isInvalid = true;
17390
17391 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17392 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17393 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17394 DiagKind = diag::err_typecheck_incompatible_address_space;
17395 break;
17396
17397 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17398 DiagKind = diag::err_typecheck_incompatible_ownership;
17399 break;
17400 }
17401
17402 llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!"
, "clang/lib/Sema/SemaExpr.cpp", 17402)
;
17403 // fallthrough
17404 }
17405 case CompatiblePointerDiscardsQualifiers:
17406 // If the qualifiers lost were because we were applying the
17407 // (deprecated) C++ conversion from a string literal to a char*
17408 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17409 // Ideally, this check would be performed in
17410 // checkPointerTypesForAssignment. However, that would require a
17411 // bit of refactoring (so that the second argument is an
17412 // expression, rather than a type), which should be done as part
17413 // of a larger effort to fix checkPointerTypesForAssignment for
17414 // C++ semantics.
17415 if (getLangOpts().CPlusPlus &&
17416 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
17417 return false;
17418 if (getLangOpts().CPlusPlus) {
17419 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17420 isInvalid = true;
17421 } else {
17422 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17423 }
17424
17425 break;
17426 case IncompatibleNestedPointerQualifiers:
17427 if (getLangOpts().CPlusPlus) {
17428 isInvalid = true;
17429 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17430 } else {
17431 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17432 }
17433 break;
17434 case IncompatibleNestedPointerAddressSpaceMismatch:
17435 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17436 isInvalid = true;
17437 break;
17438 case IntToBlockPointer:
17439 DiagKind = diag::err_int_to_block_pointer;
17440 isInvalid = true;
17441 break;
17442 case IncompatibleBlockPointer:
17443 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17444 isInvalid = true;
17445 break;
17446 case IncompatibleObjCQualifiedId: {
17447 if (SrcType->isObjCQualifiedIdType()) {
17448 const ObjCObjectPointerType *srcOPT =
17449 SrcType->castAs<ObjCObjectPointerType>();
17450 for (auto *srcProto : srcOPT->quals()) {
17451 PDecl = srcProto;
17452 break;
17453 }
17454 if (const ObjCInterfaceType *IFaceT =
17455 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17456 IFace = IFaceT->getDecl();
17457 }
17458 else if (DstType->isObjCQualifiedIdType()) {
17459 const ObjCObjectPointerType *dstOPT =
17460 DstType->castAs<ObjCObjectPointerType>();
17461 for (auto *dstProto : dstOPT->quals()) {
17462 PDecl = dstProto;
17463 break;
17464 }
17465 if (const ObjCInterfaceType *IFaceT =
17466 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17467 IFace = IFaceT->getDecl();
17468 }
17469 if (getLangOpts().CPlusPlus) {
17470 DiagKind = diag::err_incompatible_qualified_id;
17471 isInvalid = true;
17472 } else {
17473 DiagKind = diag::warn_incompatible_qualified_id;
17474 }
17475 break;
17476 }
17477 case IncompatibleVectors:
17478 if (getLangOpts().CPlusPlus) {
17479 DiagKind = diag::err_incompatible_vectors;
17480 isInvalid = true;
17481 } else {
17482 DiagKind = diag::warn_incompatible_vectors;
17483 }
17484 break;
17485 case IncompatibleObjCWeakRef:
17486 DiagKind = diag::err_arc_weak_unavailable_assign;
17487 isInvalid = true;
17488 break;
17489 case Incompatible:
17490 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17491 if (Complained)
17492 *Complained = true;
17493 return true;
17494 }
17495
17496 DiagKind = diag::err_typecheck_convert_incompatible;
17497 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17498 MayHaveConvFixit = true;
17499 isInvalid = true;
17500 MayHaveFunctionDiff = true;
17501 break;
17502 }
17503
17504 QualType FirstType, SecondType;
17505 switch (Action) {
17506 case AA_Assigning:
17507 case AA_Initializing:
17508 // The destination type comes first.
17509 FirstType = DstType;
17510 SecondType = SrcType;
17511 break;
17512
17513 case AA_Returning:
17514 case AA_Passing:
17515 case AA_Passing_CFAudited:
17516 case AA_Converting:
17517 case AA_Sending:
17518 case AA_Casting:
17519 // The source type comes first.
17520 FirstType = SrcType;
17521 SecondType = DstType;
17522 break;
17523 }
17524
17525 PartialDiagnostic FDiag = PDiag(DiagKind);
17526 AssignmentAction ActionForDiag = Action;
17527 if (Action == AA_Passing_CFAudited)
17528 ActionForDiag = AA_Passing;
17529
17530 FDiag << FirstType << SecondType << ActionForDiag
17531 << SrcExpr->getSourceRange();
17532
17533 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17534 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17535 auto isPlainChar = [](const clang::Type *Type) {
17536 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17537 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17538 };
17539 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17540 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17541 }
17542
17543 // If we can fix the conversion, suggest the FixIts.
17544 if (!ConvHints.isNull()) {
17545 for (FixItHint &H : ConvHints.Hints)
17546 FDiag << H;
17547 }
17548
17549 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17550
17551 if (MayHaveFunctionDiff)
17552 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17553
17554 Diag(Loc, FDiag);
17555 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17556 DiagKind == diag::err_incompatible_qualified_id) &&
17557 PDecl && IFace && !IFace->hasDefinition())
17558 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17559 << IFace << PDecl;
17560
17561 if (SecondType == Context.OverloadTy)
17562 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
17563 FirstType, /*TakingAddress=*/true);
17564
17565 if (CheckInferredResultType)
17566 EmitRelatedResultTypeNote(SrcExpr);
17567
17568 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17569 EmitRelatedResultTypeNoteForReturn(DstType);
17570
17571 if (Complained)
17572 *Complained = true;
17573 return isInvalid;
17574}
17575
17576ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17577 llvm::APSInt *Result,
17578 AllowFoldKind CanFold) {
17579 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17580 public:
17581 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17582 QualType T) override {
17583 return S.Diag(Loc, diag::err_ice_not_integral)
17584 << T << S.LangOpts.CPlusPlus;
17585 }
17586 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17587 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17588 }
17589 } Diagnoser;
17590
17591 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17592}
17593
17594ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17595 llvm::APSInt *Result,
17596 unsigned DiagID,
17597 AllowFoldKind CanFold) {
17598 class IDDiagnoser : public VerifyICEDiagnoser {
17599 unsigned DiagID;
17600
17601 public:
17602 IDDiagnoser(unsigned DiagID)
17603 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17604
17605 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17606 return S.Diag(Loc, DiagID);
17607 }
17608 } Diagnoser(DiagID);
17609
17610 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17611}
17612
17613Sema::SemaDiagnosticBuilder
17614Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17615 QualType T) {
17616 return diagnoseNotICE(S, Loc);
17617}
17618
17619Sema::SemaDiagnosticBuilder
17620Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17621 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17622}
17623
17624ExprResult
17625Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17626 VerifyICEDiagnoser &Diagnoser,
17627 AllowFoldKind CanFold) {
17628 SourceLocation DiagLoc = E->getBeginLoc();
17629
17630 if (getLangOpts().CPlusPlus11) {
17631 // C++11 [expr.const]p5:
17632 // If an expression of literal class type is used in a context where an
17633 // integral constant expression is required, then that class type shall
17634 // have a single non-explicit conversion function to an integral or
17635 // unscoped enumeration type
17636 ExprResult Converted;
17637 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17638 VerifyICEDiagnoser &BaseDiagnoser;
17639 public:
17640 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17641 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17642 BaseDiagnoser.Suppress, true),
17643 BaseDiagnoser(BaseDiagnoser) {}
17644
17645 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17646 QualType T) override {
17647 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17648 }
17649
17650 SemaDiagnosticBuilder diagnoseIncomplete(
17651 Sema &S, SourceLocation Loc, QualType T) override {
17652 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17653 }
17654
17655 SemaDiagnosticBuilder diagnoseExplicitConv(
17656 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17657 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17658 }
17659
17660 SemaDiagnosticBuilder noteExplicitConv(
17661 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17662 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17663 << ConvTy->isEnumeralType() << ConvTy;
17664 }
17665
17666 SemaDiagnosticBuilder diagnoseAmbiguous(
17667 Sema &S, SourceLocation Loc, QualType T) override {
17668 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17669 }
17670
17671 SemaDiagnosticBuilder noteAmbiguous(
17672 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17673 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17674 << ConvTy->isEnumeralType() << ConvTy;
17675 }
17676
17677 SemaDiagnosticBuilder diagnoseConversion(
17678 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17679 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "clang/lib/Sema/SemaExpr.cpp", 17679)
;
17680 }
17681 } ConvertDiagnoser(Diagnoser);
17682
17683 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17684 ConvertDiagnoser);
17685 if (Converted.isInvalid())
17686 return Converted;
17687 E = Converted.get();
17688 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17689 return ExprError();
17690 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17691 // An ICE must be of integral or unscoped enumeration type.
17692 if (!Diagnoser.Suppress)
17693 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17694 << E->getSourceRange();
17695 return ExprError();
17696 }
17697
17698 ExprResult RValueExpr = DefaultLvalueConversion(E);
17699 if (RValueExpr.isInvalid())
17700 return ExprError();
17701
17702 E = RValueExpr.get();
17703
17704 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17705 // in the non-ICE case.
17706 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17707 if (Result)
17708 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
17709 if (!isa<ConstantExpr>(E))
17710 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17711 : ConstantExpr::Create(Context, E);
17712 return E;
17713 }
17714
17715 Expr::EvalResult EvalResult;
17716 SmallVector<PartialDiagnosticAt, 8> Notes;
17717 EvalResult.Diag = &Notes;
17718
17719 // Try to evaluate the expression, and produce diagnostics explaining why it's
17720 // not a constant expression as a side-effect.
17721 bool Folded =
17722 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17723 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17724
17725 if (!isa<ConstantExpr>(E))
17726 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17727
17728 // In C++11, we can rely on diagnostics being produced for any expression
17729 // which is not a constant expression. If no diagnostics were produced, then
17730 // this is a constant expression.
17731 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17732 if (Result)
17733 *Result = EvalResult.Val.getInt();
17734 return E;
17735 }
17736
17737 // If our only note is the usual "invalid subexpression" note, just point
17738 // the caret at its location rather than producing an essentially
17739 // redundant note.
17740 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17741 diag::note_invalid_subexpr_in_const_expr) {
17742 DiagLoc = Notes[0].first;
17743 Notes.clear();
17744 }
17745
17746 if (!Folded || !CanFold) {
17747 if (!Diagnoser.Suppress) {
17748 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17749 for (const PartialDiagnosticAt &Note : Notes)
17750 Diag(Note.first, Note.second);
17751 }
17752
17753 return ExprError();
17754 }
17755
17756 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17757 for (const PartialDiagnosticAt &Note : Notes)
17758 Diag(Note.first, Note.second);
17759
17760 if (Result)
17761 *Result = EvalResult.Val.getInt();
17762 return E;
17763}
17764
17765namespace {
17766 // Handle the case where we conclude a expression which we speculatively
17767 // considered to be unevaluated is actually evaluated.
17768 class TransformToPE : public TreeTransform<TransformToPE> {
17769 typedef TreeTransform<TransformToPE> BaseTransform;
17770
17771 public:
17772 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17773
17774 // Make sure we redo semantic analysis
17775 bool AlwaysRebuild() { return true; }
17776 bool ReplacingOriginal() { return true; }
17777
17778 // We need to special-case DeclRefExprs referring to FieldDecls which
17779 // are not part of a member pointer formation; normal TreeTransforming
17780 // doesn't catch this case because of the way we represent them in the AST.
17781 // FIXME: This is a bit ugly; is it really the best way to handle this
17782 // case?
17783 //
17784 // Error on DeclRefExprs referring to FieldDecls.
17785 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17786 if (isa<FieldDecl>(E->getDecl()) &&
17787 !SemaRef.isUnevaluatedContext())
17788 return SemaRef.Diag(E->getLocation(),
17789 diag::err_invalid_non_static_member_use)
17790 << E->getDecl() << E->getSourceRange();
17791
17792 return BaseTransform::TransformDeclRefExpr(E);
17793 }
17794
17795 // Exception: filter out member pointer formation
17796 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17797 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17798 return E;
17799
17800 return BaseTransform::TransformUnaryOperator(E);
17801 }
17802
17803 // The body of a lambda-expression is in a separate expression evaluation
17804 // context so never needs to be transformed.
17805 // FIXME: Ideally we wouldn't transform the closure type either, and would
17806 // just recreate the capture expressions and lambda expression.
17807 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17808 return SkipLambdaBody(E, Body);
17809 }
17810 };
17811}
17812
17813ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17814 assert(isUnevaluatedContext() &&(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "clang/lib/Sema/SemaExpr.cpp", 17815, __extension__ __PRETTY_FUNCTION__
))
17815 "Should only transform unevaluated expressions")(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "clang/lib/Sema/SemaExpr.cpp", 17815, __extension__ __PRETTY_FUNCTION__
))
;
17816 ExprEvalContexts.back().Context =
17817 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17818 if (isUnevaluatedContext())
17819 return E;
17820 return TransformToPE(*this).TransformExpr(E);
17821}
17822
17823TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17824 assert(isUnevaluatedContext() &&(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "clang/lib/Sema/SemaExpr.cpp", 17825, __extension__ __PRETTY_FUNCTION__
))
17825 "Should only transform unevaluated expressions")(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "clang/lib/Sema/SemaExpr.cpp", 17825, __extension__ __PRETTY_FUNCTION__
))
;
17826 ExprEvalContexts.back().Context =
17827 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17828 if (isUnevaluatedContext())
17829 return TInfo;
17830 return TransformToPE(*this).TransformType(TInfo);
17831}
17832
17833void
17834Sema::PushExpressionEvaluationContext(
17835 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17836 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17837 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17838 LambdaContextDecl, ExprContext);
17839
17840 // Discarded statements and immediate contexts nested in other
17841 // discarded statements or immediate context are themselves
17842 // a discarded statement or an immediate context, respectively.
17843 ExprEvalContexts.back().InDiscardedStatement =
17844 ExprEvalContexts[ExprEvalContexts.size() - 2]
17845 .isDiscardedStatementContext();
17846 ExprEvalContexts.back().InImmediateFunctionContext =
17847 ExprEvalContexts[ExprEvalContexts.size() - 2]
17848 .isImmediateFunctionContext();
17849
17850 Cleanup.reset();
17851 if (!MaybeODRUseExprs.empty())
17852 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17853}
17854
17855void
17856Sema::PushExpressionEvaluationContext(
17857 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17858 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17859 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17860 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17861}
17862
17863namespace {
17864
17865const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17866 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17867 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17868 if (E->getOpcode() == UO_Deref)
17869 return CheckPossibleDeref(S, E->getSubExpr());
17870 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17871 return CheckPossibleDeref(S, E->getBase());
17872 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17873 return CheckPossibleDeref(S, E->getBase());
17874 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17875 QualType Inner;
17876 QualType Ty = E->getType();
17877 if (const auto *Ptr = Ty->getAs<PointerType>())
17878 Inner = Ptr->getPointeeType();
17879 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17880 Inner = Arr->getElementType();
17881 else
17882 return nullptr;
17883
17884 if (Inner->hasAttr(attr::NoDeref))
17885 return E;
17886 }
17887 return nullptr;
17888}
17889
17890} // namespace
17891
17892void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17893 for (const Expr *E : Rec.PossibleDerefs) {
17894 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17895 if (DeclRef) {
17896 const ValueDecl *Decl = DeclRef->getDecl();
17897 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17898 << Decl->getName() << E->getSourceRange();
17899 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17900 } else {
17901 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17902 << E->getSourceRange();
17903 }
17904 }
17905 Rec.PossibleDerefs.clear();
17906}
17907
17908/// Check whether E, which is either a discarded-value expression or an
17909/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17910/// and if so, remove it from the list of volatile-qualified assignments that
17911/// we are going to warn are deprecated.
17912void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17913 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17914 return;
17915
17916 // Note: ignoring parens here is not justified by the standard rules, but
17917 // ignoring parentheses seems like a more reasonable approach, and this only
17918 // drives a deprecation warning so doesn't affect conformance.
17919 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17920 if (BO->getOpcode() == BO_Assign) {
17921 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17922 llvm::erase_value(LHSs, BO->getLHS());
17923 }
17924 }
17925}
17926
17927ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17928 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17929 !Decl->isConsteval() || isConstantEvaluated() ||
17930 isCheckingDefaultArgumentOrInitializer() ||
17931 RebuildingImmediateInvocation || isImmediateFunctionContext())
17932 return E;
17933
17934 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17935 /// It's OK if this fails; we'll also remove this in
17936 /// HandleImmediateInvocations, but catching it here allows us to avoid
17937 /// walking the AST looking for it in simple cases.
17938 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17939 if (auto *DeclRef =
17940 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17941 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17942
17943 E = MaybeCreateExprWithCleanups(E);
17944
17945 ConstantExpr *Res = ConstantExpr::Create(
17946 getASTContext(), E.get(),
17947 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17948 getASTContext()),
17949 /*IsImmediateInvocation*/ true);
17950 /// Value-dependent constant expressions should not be immediately
17951 /// evaluated until they are instantiated.
17952 if (!Res->isValueDependent())
17953 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17954 return Res;
17955}
17956
17957static void EvaluateAndDiagnoseImmediateInvocation(
17958 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17959 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17960 Expr::EvalResult Eval;
17961 Eval.Diag = &Notes;
17962 ConstantExpr *CE = Candidate.getPointer();
17963 bool Result = CE->EvaluateAsConstantExpr(
17964 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17965 if (!Result || !Notes.empty()) {
17966 SemaRef.FailedImmediateInvocations.insert(CE);
17967 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17968 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17969 InnerExpr = FunctionalCast->getSubExpr();
17970 FunctionDecl *FD = nullptr;
17971 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17972 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17973 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17974 FD = Call->getConstructor();
17975 else
17976 llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "clang/lib/Sema/SemaExpr.cpp"
, 17976)
;
17977 assert(FD && FD->isConsteval())(static_cast <bool> (FD && FD->isConsteval()
) ? void (0) : __assert_fail ("FD && FD->isConsteval()"
, "clang/lib/Sema/SemaExpr.cpp", 17977, __extension__ __PRETTY_FUNCTION__
))
;
17978 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17979 if (auto Context =
17980 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
17981 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17982 << Context->Decl;
17983 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17984 }
17985 for (auto &Note : Notes)
17986 SemaRef.Diag(Note.first, Note.second);
17987 return;
17988 }
17989 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17990}
17991
17992static void RemoveNestedImmediateInvocation(
17993 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17994 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17995 struct ComplexRemove : TreeTransform<ComplexRemove> {
17996 using Base = TreeTransform<ComplexRemove>;
17997 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17998 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17999 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18000 CurrentII;
18001 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18002 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18003 SmallVector<Sema::ImmediateInvocationCandidate,
18004 4>::reverse_iterator Current)
18005 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18006 void RemoveImmediateInvocation(ConstantExpr* E) {
18007 auto It = std::find_if(CurrentII, IISet.rend(),
18008 [E](Sema::ImmediateInvocationCandidate Elem) {
18009 return Elem.getPointer() == E;
18010 });
18011 // It is possible that some subexpression of the current immediate
18012 // invocation was handled from another expression evaluation context. Do
18013 // not handle the current immediate invocation if some of its
18014 // subexpressions failed before.
18015 if (It == IISet.rend()) {
18016 if (SemaRef.FailedImmediateInvocations.contains(E))
18017 CurrentII->setInt(1);
18018 } else {
18019 It->setInt(1); // Mark as deleted
18020 }
18021 }
18022 ExprResult TransformConstantExpr(ConstantExpr *E) {
18023 if (!E->isImmediateInvocation())
18024 return Base::TransformConstantExpr(E);
18025 RemoveImmediateInvocation(E);
18026 return Base::TransformExpr(E->getSubExpr());
18027 }
18028 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18029 /// we need to remove its DeclRefExpr from the DRSet.
18030 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18031 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
1
The object is a 'CastReturnType'
18032 return Base::TransformCXXOperatorCallExpr(E);
2
Calling 'TreeTransform::TransformCXXOperatorCallExpr'
18033 }
18034 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
18035 /// here.
18036 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18037 if (!Init)
18038 return Init;
18039 /// ConstantExpr are the first layer of implicit node to be removed so if
18040 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18041 if (auto *CE = dyn_cast<ConstantExpr>(Init))
18042 if (CE->isImmediateInvocation())
18043 RemoveImmediateInvocation(CE);
18044 return Base::TransformInitializer(Init, NotCopyInit);
18045 }
18046 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18047 DRSet.erase(E);
18048 return E;
18049 }
18050 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18051 // Do not rebuild lambdas to avoid creating a new type.
18052 // Lambdas have already been processed inside their eval context.
18053 return E;
18054 }
18055 bool AlwaysRebuild() { return false; }
18056 bool ReplacingOriginal() { return true; }
18057 bool AllowSkippingCXXConstructExpr() {
18058 bool Res = AllowSkippingFirstCXXConstructExpr;
18059 AllowSkippingFirstCXXConstructExpr = true;
18060 return Res;
18061 }
18062 bool AllowSkippingFirstCXXConstructExpr = true;
18063 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18064 Rec.ImmediateInvocationCandidates, It);
18065
18066 /// CXXConstructExpr with a single argument are getting skipped by
18067 /// TreeTransform in some situtation because they could be implicit. This
18068 /// can only occur for the top-level CXXConstructExpr because it is used
18069 /// nowhere in the expression being transformed therefore will not be rebuilt.
18070 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18071 /// skipping the first CXXConstructExpr.
18072 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18073 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18074
18075 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18076 // The result may not be usable in case of previous compilation errors.
18077 // In this case evaluation of the expression may result in crash so just
18078 // don't do anything further with the result.
18079 if (Res.isUsable()) {
18080 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
18081 It->getPointer()->setSubExpr(Res.get());
18082 }
18083}
18084
18085static void
18086HandleImmediateInvocations(Sema &SemaRef,
18087 Sema::ExpressionEvaluationContextRecord &Rec) {
18088 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18089 Rec.ReferenceToConsteval.size() == 0) ||
18090 SemaRef.RebuildingImmediateInvocation)
18091 return;
18092
18093 /// When we have more than 1 ImmediateInvocationCandidates or previously
18094 /// failed immediate invocations, we need to check for nested
18095 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18096 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18097 /// invocation.
18098 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18099 !SemaRef.FailedImmediateInvocations.empty()) {
18100
18101 /// Prevent sema calls during the tree transform from adding pointers that
18102 /// are already in the sets.
18103 llvm::SaveAndRestore DisableIITracking(
18104 SemaRef.RebuildingImmediateInvocation, true);
18105
18106 /// Prevent diagnostic during tree transfrom as they are duplicates
18107 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18108
18109 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18110 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18111 if (!It->getInt())
18112 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18113 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18114 Rec.ReferenceToConsteval.size()) {
18115 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
18116 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18117 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18118 bool VisitDeclRefExpr(DeclRefExpr *E) {
18119 DRSet.erase(E);
18120 return DRSet.size();
18121 }
18122 } Visitor(Rec.ReferenceToConsteval);
18123 Visitor.TraverseStmt(
18124 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18125 }
18126 for (auto CE : Rec.ImmediateInvocationCandidates)
18127 if (!CE.getInt())
18128 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
18129 for (auto *DR : Rec.ReferenceToConsteval) {
18130 NamedDecl *ND = cast<FunctionDecl>(DR->getDecl());
18131 if (auto *MD = llvm::dyn_cast<CXXMethodDecl>(ND);
18132 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18133 ND = MD->getParent();
18134 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18135 << ND << isa<CXXRecordDecl>(ND);
18136 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18137 }
18138}
18139
18140void Sema::PopExpressionEvaluationContext() {
18141 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18142 unsigned NumTypos = Rec.NumTypos;
18143
18144 if (!Rec.Lambdas.empty()) {
18145 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18146 if (!getLangOpts().CPlusPlus20 &&
18147 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18148 Rec.isUnevaluated() ||
18149 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18150 unsigned D;
18151 if (Rec.isUnevaluated()) {
18152 // C++11 [expr.prim.lambda]p2:
18153 // A lambda-expression shall not appear in an unevaluated operand
18154 // (Clause 5).
18155 D = diag::err_lambda_unevaluated_operand;
18156 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18157 // C++1y [expr.const]p2:
18158 // A conditional-expression e is a core constant expression unless the
18159 // evaluation of e, following the rules of the abstract machine, would
18160 // evaluate [...] a lambda-expression.
18161 D = diag::err_lambda_in_constant_expression;
18162 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18163 // C++17 [expr.prim.lamda]p2:
18164 // A lambda-expression shall not appear [...] in a template-argument.
18165 D = diag::err_lambda_in_invalid_context;
18166 } else
18167 llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message."
, "clang/lib/Sema/SemaExpr.cpp", 18167)
;
18168
18169 for (const auto *L : Rec.Lambdas)
18170 Diag(L->getBeginLoc(), D);
18171 }
18172 }
18173
18174 WarnOnPendingNoDerefs(Rec);
18175 HandleImmediateInvocations(*this, Rec);
18176
18177 // Warn on any volatile-qualified simple-assignments that are not discarded-
18178 // value expressions nor unevaluated operands (those cases get removed from
18179 // this list by CheckUnusedVolatileAssignment).
18180 for (auto *BO : Rec.VolatileAssignmentLHSs)
18181 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18182 << BO->getType();
18183
18184 // When are coming out of an unevaluated context, clear out any
18185 // temporaries that we may have created as part of the evaluation of
18186 // the expression in that context: they aren't relevant because they
18187 // will never be constructed.
18188 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18189 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18190 ExprCleanupObjects.end());
18191 Cleanup = Rec.ParentCleanup;
18192 CleanupVarDeclMarking();
18193 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
18194 // Otherwise, merge the contexts together.
18195 } else {
18196 Cleanup.mergeFrom(Rec.ParentCleanup);
18197 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
18198 Rec.SavedMaybeODRUseExprs.end());
18199 }
18200
18201 // Pop the current expression evaluation context off the stack.
18202 ExprEvalContexts.pop_back();
18203
18204 // The global expression evaluation context record is never popped.
18205 ExprEvalContexts.back().NumTypos += NumTypos;
18206}
18207
18208void Sema::DiscardCleanupsInEvaluationContext() {
18209 ExprCleanupObjects.erase(
18210 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18211 ExprCleanupObjects.end());
18212 Cleanup.reset();
18213 MaybeODRUseExprs.clear();
18214}
18215
18216ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18217 ExprResult Result = CheckPlaceholderExpr(E);
18218 if (Result.isInvalid())
18219 return ExprError();
18220 E = Result.get();
18221 if (!E->getType()->isVariablyModifiedType())
18222 return E;
18223 return TransformToPotentiallyEvaluated(E);
18224}
18225
18226/// Are we in a context that is potentially constant evaluated per C++20
18227/// [expr.const]p12?
18228static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18229 /// C++2a [expr.const]p12:
18230 // An expression or conversion is potentially constant evaluated if it is
18231 switch (SemaRef.ExprEvalContexts.back().Context) {
18232 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18233 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18234
18235 // -- a manifestly constant-evaluated expression,
18236 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18237 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18238 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18239 // -- a potentially-evaluated expression,
18240 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18241 // -- an immediate subexpression of a braced-init-list,
18242
18243 // -- [FIXME] an expression of the form & cast-expression that occurs
18244 // within a templated entity
18245 // -- a subexpression of one of the above that is not a subexpression of
18246 // a nested unevaluated operand.
18247 return true;
18248
18249 case Sema::ExpressionEvaluationContext::Unevaluated:
18250 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18251 // Expressions in this context are never evaluated.
18252 return false;
18253 }
18254 llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "clang/lib/Sema/SemaExpr.cpp"
, 18254)
;
18255}
18256
18257/// Return true if this function has a calling convention that requires mangling
18258/// in the size of the parameter pack.
18259static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18260 // These manglings don't do anything on non-Windows or non-x86 platforms, so
18261 // we don't need parameter type sizes.
18262 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
18263 if (!TT.isOSWindows() || !TT.isX86())
18264 return false;
18265
18266 // If this is C++ and this isn't an extern "C" function, parameters do not
18267 // need to be complete. In this case, C++ mangling will apply, which doesn't
18268 // use the size of the parameters.
18269 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18270 return false;
18271
18272 // Stdcall, fastcall, and vectorcall need this special treatment.
18273 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18274 switch (CC) {
18275 case CC_X86StdCall:
18276 case CC_X86FastCall:
18277 case CC_X86VectorCall:
18278 return true;
18279 default:
18280 break;
18281 }
18282 return false;
18283}
18284
18285/// Require that all of the parameter types of function be complete. Normally,
18286/// parameter types are only required to be complete when a function is called
18287/// or defined, but to mangle functions with certain calling conventions, the
18288/// mangler needs to know the size of the parameter list. In this situation,
18289/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18290/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18291/// result in a linker error. Clang doesn't implement this behavior, and instead
18292/// attempts to error at compile time.
18293static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18294 SourceLocation Loc) {
18295 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18296 FunctionDecl *FD;
18297 ParmVarDecl *Param;
18298
18299 public:
18300 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18301 : FD(FD), Param(Param) {}
18302
18303 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18304 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18305 StringRef CCName;
18306 switch (CC) {
18307 case CC_X86StdCall:
18308 CCName = "stdcall";
18309 break;
18310 case CC_X86FastCall:
18311 CCName = "fastcall";
18312 break;
18313 case CC_X86VectorCall:
18314 CCName = "vectorcall";
18315 break;
18316 default:
18317 llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling"
, "clang/lib/Sema/SemaExpr.cpp", 18317)
;
18318 }
18319
18320 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18321 << Param->getDeclName() << FD->getDeclName() << CCName;
18322 }
18323 };
18324
18325 for (ParmVarDecl *Param : FD->parameters()) {
18326 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18327 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18328 }
18329}
18330
18331namespace {
18332enum class OdrUseContext {
18333 /// Declarations in this context are not odr-used.
18334 None,
18335 /// Declarations in this context are formally odr-used, but this is a
18336 /// dependent context.
18337 Dependent,
18338 /// Declarations in this context are odr-used but not actually used (yet).
18339 FormallyOdrUsed,
18340 /// Declarations in this context are used.
18341 Used
18342};
18343}
18344
18345/// Are we within a context in which references to resolved functions or to
18346/// variables result in odr-use?
18347static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18348 OdrUseContext Result;
18349
18350 switch (SemaRef.ExprEvalContexts.back().Context) {
18351 case Sema::ExpressionEvaluationContext::Unevaluated:
18352 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18353 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18354 return OdrUseContext::None;
18355
18356 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18357 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18358 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18359 Result = OdrUseContext::Used;
18360 break;
18361
18362 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18363 Result = OdrUseContext::FormallyOdrUsed;
18364 break;
18365
18366 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18367 // A default argument formally results in odr-use, but doesn't actually
18368 // result in a use in any real sense until it itself is used.
18369 Result = OdrUseContext::FormallyOdrUsed;
18370 break;
18371 }
18372
18373 if (SemaRef.CurContext->isDependentContext())
18374 return OdrUseContext::Dependent;
18375
18376 return Result;
18377}
18378
18379static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18380 if (!Func->isConstexpr())
18381 return false;
18382
18383 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18384 return true;
18385 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18386 return CCD && CCD->getInheritedConstructor();
18387}
18388
18389/// Mark a function referenced, and check whether it is odr-used
18390/// (C++ [basic.def.odr]p2, C99 6.9p3)
18391void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18392 bool MightBeOdrUse) {
18393 assert(Func && "No function?")(static_cast <bool> (Func && "No function?") ? void
(0) : __assert_fail ("Func && \"No function?\"", "clang/lib/Sema/SemaExpr.cpp"
, 18393, __extension__ __PRETTY_FUNCTION__))
;
18394
18395 Func->setReferenced();
18396
18397 // Recursive functions aren't really used until they're used from some other
18398 // context.
18399 bool IsRecursiveCall = CurContext == Func;
18400
18401 // C++11 [basic.def.odr]p3:
18402 // A function whose name appears as a potentially-evaluated expression is
18403 // odr-used if it is the unique lookup result or the selected member of a
18404 // set of overloaded functions [...].
18405 //
18406 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18407 // can just check that here.
18408 OdrUseContext OdrUse =
18409 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18410 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18411 OdrUse = OdrUseContext::FormallyOdrUsed;
18412
18413 // Trivial default constructors and destructors are never actually used.
18414 // FIXME: What about other special members?
18415 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18416 OdrUse == OdrUseContext::Used) {
18417 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18418 if (Constructor->isDefaultConstructor())
18419 OdrUse = OdrUseContext::FormallyOdrUsed;
18420 if (isa<CXXDestructorDecl>(Func))
18421 OdrUse = OdrUseContext::FormallyOdrUsed;
18422 }
18423
18424 // C++20 [expr.const]p12:
18425 // A function [...] is needed for constant evaluation if it is [...] a
18426 // constexpr function that is named by an expression that is potentially
18427 // constant evaluated
18428 bool NeededForConstantEvaluation =
18429 isPotentiallyConstantEvaluatedContext(*this) &&
18430 isImplicitlyDefinableConstexprFunction(Func);
18431
18432 // Determine whether we require a function definition to exist, per
18433 // C++11 [temp.inst]p3:
18434 // Unless a function template specialization has been explicitly
18435 // instantiated or explicitly specialized, the function template
18436 // specialization is implicitly instantiated when the specialization is
18437 // referenced in a context that requires a function definition to exist.
18438 // C++20 [temp.inst]p7:
18439 // The existence of a definition of a [...] function is considered to
18440 // affect the semantics of the program if the [...] function is needed for
18441 // constant evaluation by an expression
18442 // C++20 [basic.def.odr]p10:
18443 // Every program shall contain exactly one definition of every non-inline
18444 // function or variable that is odr-used in that program outside of a
18445 // discarded statement
18446 // C++20 [special]p1:
18447 // The implementation will implicitly define [defaulted special members]
18448 // if they are odr-used or needed for constant evaluation.
18449 //
18450 // Note that we skip the implicit instantiation of templates that are only
18451 // used in unused default arguments or by recursive calls to themselves.
18452 // This is formally non-conforming, but seems reasonable in practice.
18453 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
18454 NeededForConstantEvaluation);
18455
18456 // C++14 [temp.expl.spec]p6:
18457 // If a template [...] is explicitly specialized then that specialization
18458 // shall be declared before the first use of that specialization that would
18459 // cause an implicit instantiation to take place, in every translation unit
18460 // in which such a use occurs
18461 if (NeedDefinition &&
18462 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18463 Func->getMemberSpecializationInfo()))
18464 checkSpecializationReachability(Loc, Func);
18465
18466 if (getLangOpts().CUDA)
18467 CheckCUDACall(Loc, Func);
18468
18469 // If we need a definition, try to create one.
18470 if (NeedDefinition && !Func->getBody()) {
18471 runWithSufficientStackSpace(Loc, [&] {
18472 if (CXXConstructorDecl *Constructor =
18473 dyn_cast<CXXConstructorDecl>(Func)) {
18474 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18475 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18476 if (Constructor->isDefaultConstructor()) {
18477 if (Constructor->isTrivial() &&
18478 !Constructor->hasAttr<DLLExportAttr>())
18479 return;
18480 DefineImplicitDefaultConstructor(Loc, Constructor);
18481 } else if (Constructor->isCopyConstructor()) {
18482 DefineImplicitCopyConstructor(Loc, Constructor);
18483 } else if (Constructor->isMoveConstructor()) {
18484 DefineImplicitMoveConstructor(Loc, Constructor);
18485 }
18486 } else if (Constructor->getInheritedConstructor()) {
18487 DefineInheritingConstructor(Loc, Constructor);
18488 }
18489 } else if (CXXDestructorDecl *Destructor =
18490 dyn_cast<CXXDestructorDecl>(Func)) {
18491 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18492 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18493 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18494 return;
18495 DefineImplicitDestructor(Loc, Destructor);
18496 }
18497 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18498 MarkVTableUsed(Loc, Destructor->getParent());
18499 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18500 if (MethodDecl->isOverloadedOperator() &&
18501 MethodDecl->getOverloadedOperator() == OO_Equal) {
18502 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18503 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18504 if (MethodDecl->isCopyAssignmentOperator())
18505 DefineImplicitCopyAssignment(Loc, MethodDecl);
18506 else if (MethodDecl->isMoveAssignmentOperator())
18507 DefineImplicitMoveAssignment(Loc, MethodDecl);
18508 }
18509 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18510 MethodDecl->getParent()->isLambda()) {
18511 CXXConversionDecl *Conversion =
18512 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18513 if (Conversion->isLambdaToBlockPointerConversion())
18514 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
18515 else
18516 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
18517 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18518 MarkVTableUsed(Loc, MethodDecl->getParent());
18519 }
18520
18521 if (Func->isDefaulted() && !Func->isDeleted()) {
18522 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
18523 if (DCK != DefaultedComparisonKind::None)
18524 DefineDefaultedComparison(Loc, Func, DCK);
18525 }
18526
18527 // Implicit instantiation of function templates and member functions of
18528 // class templates.
18529 if (Func->isImplicitlyInstantiable()) {
18530 TemplateSpecializationKind TSK =
18531 Func->getTemplateSpecializationKindForInstantiation();
18532 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18533 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18534 if (FirstInstantiation) {
18535 PointOfInstantiation = Loc;
18536 if (auto *MSI = Func->getMemberSpecializationInfo())
18537 MSI->setPointOfInstantiation(Loc);
18538 // FIXME: Notify listener.
18539 else
18540 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18541 } else if (TSK != TSK_ImplicitInstantiation) {
18542 // Use the point of use as the point of instantiation, instead of the
18543 // point of explicit instantiation (which we track as the actual point
18544 // of instantiation). This gives better backtraces in diagnostics.
18545 PointOfInstantiation = Loc;
18546 }
18547
18548 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18549 Func->isConstexpr()) {
18550 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18551 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18552 CodeSynthesisContexts.size())
18553 PendingLocalImplicitInstantiations.push_back(
18554 std::make_pair(Func, PointOfInstantiation));
18555 else if (Func->isConstexpr())
18556 // Do not defer instantiations of constexpr functions, to avoid the
18557 // expression evaluator needing to call back into Sema if it sees a
18558 // call to such a function.
18559 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18560 else {
18561 Func->setInstantiationIsPending(true);
18562 PendingInstantiations.push_back(
18563 std::make_pair(Func, PointOfInstantiation));
18564 // Notify the consumer that a function was implicitly instantiated.
18565 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18566 }
18567 }
18568 } else {
18569 // Walk redefinitions, as some of them may be instantiable.
18570 for (auto *i : Func->redecls()) {
18571 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18572 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18573 }
18574 }
18575 });
18576 }
18577
18578 // If a constructor was defined in the context of a default parameter
18579 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18580 // context), its initializers may not be referenced yet.
18581 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18582 for (CXXCtorInitializer *Init : Constructor->inits()) {
18583 if (Init->isInClassMemberInitializer())
18584 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18585 MarkDeclarationsReferencedInExpr(Init->getInit());
18586 });
18587 }
18588 }
18589
18590 // C++14 [except.spec]p17:
18591 // An exception-specification is considered to be needed when:
18592 // - the function is odr-used or, if it appears in an unevaluated operand,
18593 // would be odr-used if the expression were potentially-evaluated;
18594 //
18595 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18596 // function is a pure virtual function we're calling, and in that case the
18597 // function was selected by overload resolution and we need to resolve its
18598 // exception specification for a different reason.
18599 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18600 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
18601 ResolveExceptionSpec(Loc, FPT);
18602
18603 // If this is the first "real" use, act on that.
18604 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18605 // Keep track of used but undefined functions.
18606 if (!Func->isDefined()) {
18607 if (mightHaveNonExternalLinkage(Func))
18608 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18609 else if (Func->getMostRecentDecl()->isInlined() &&
18610 !LangOpts.GNUInline &&
18611 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18612 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18613 else if (isExternalWithNoLinkageType(Func))
18614 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18615 }
18616
18617 // Some x86 Windows calling conventions mangle the size of the parameter
18618 // pack into the name. Computing the size of the parameters requires the
18619 // parameter types to be complete. Check that now.
18620 if (funcHasParameterSizeMangling(*this, Func))
18621 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18622
18623 // In the MS C++ ABI, the compiler emits destructor variants where they are
18624 // used. If the destructor is used here but defined elsewhere, mark the
18625 // virtual base destructors referenced. If those virtual base destructors
18626 // are inline, this will ensure they are defined when emitting the complete
18627 // destructor variant. This checking may be redundant if the destructor is
18628 // provided later in this TU.
18629 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18630 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18631 CXXRecordDecl *Parent = Dtor->getParent();
18632 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18633 CheckCompleteDestructorVariant(Loc, Dtor);
18634 }
18635 }
18636
18637 Func->markUsed(Context);
18638 }
18639}
18640
18641/// Directly mark a variable odr-used. Given a choice, prefer to use
18642/// MarkVariableReferenced since it does additional checks and then
18643/// calls MarkVarDeclODRUsed.
18644/// If the variable must be captured:
18645/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18646/// - else capture it in the DeclContext that maps to the
18647/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18648static void
18649MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
18650 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18651 // Keep track of used but undefined variables.
18652 // FIXME: We shouldn't suppress this warning for static data members.
18653 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18654 assert(Var && "expected a capturable variable")(static_cast <bool> (Var && "expected a capturable variable"
) ? void (0) : __assert_fail ("Var && \"expected a capturable variable\""
, "clang/lib/Sema/SemaExpr.cpp", 18654, __extension__ __PRETTY_FUNCTION__
))
;
18655
18656 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18657 (!Var->isExternallyVisible() || Var->isInline() ||
18658 SemaRef.isExternalWithNoLinkageType(Var)) &&
18659 !(Var->isStaticDataMember() && Var->hasInit())) {
18660 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18661 if (old.isInvalid())
18662 old = Loc;
18663 }
18664 QualType CaptureType, DeclRefType;
18665 if (SemaRef.LangOpts.OpenMP)
18666 SemaRef.tryCaptureOpenMPLambdas(V);
18667 SemaRef.tryCaptureVariable(V, Loc, Sema::TryCapture_Implicit,
18668 /*EllipsisLoc*/ SourceLocation(),
18669 /*BuildAndDiagnose*/ true, CaptureType,
18670 DeclRefType, FunctionScopeIndexToStopAt);
18671
18672 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18673 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18674 auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
18675 auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
18676 if (VarTarget == Sema::CVT_Host &&
18677 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
18678 UserTarget == Sema::CFT_Global)) {
18679 // Diagnose ODR-use of host global variables in device functions.
18680 // Reference of device global variables in host functions is allowed
18681 // through shadow variables therefore it is not diagnosed.
18682 if (SemaRef.LangOpts.CUDAIsDevice) {
18683 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18684 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18685 SemaRef.targetDiag(Var->getLocation(),
18686 Var->getType().isConstQualified()
18687 ? diag::note_cuda_const_var_unpromoted
18688 : diag::note_cuda_host_var);
18689 }
18690 } else if (VarTarget == Sema::CVT_Device &&
18691 (UserTarget == Sema::CFT_Host ||
18692 UserTarget == Sema::CFT_HostDevice)) {
18693 // Record a CUDA/HIP device side variable if it is ODR-used
18694 // by host code. This is done conservatively, when the variable is
18695 // referenced in any of the following contexts:
18696 // - a non-function context
18697 // - a host function
18698 // - a host device function
18699 // This makes the ODR-use of the device side variable by host code to
18700 // be visible in the device compilation for the compiler to be able to
18701 // emit template variables instantiated by host code only and to
18702 // externalize the static device side variable ODR-used by host code.
18703 if (!Var->hasExternalStorage())
18704 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18705 else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
18706 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18707 }
18708 }
18709
18710 V->markUsed(SemaRef.Context);
18711}
18712
18713void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
18714 SourceLocation Loc,
18715 unsigned CapturingScopeIndex) {
18716 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18717}
18718
18719void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc,
18720 ValueDecl *var) {
18721 DeclContext *VarDC = var->getDeclContext();
18722
18723 // If the parameter still belongs to the translation unit, then
18724 // we're actually just using one parameter in the declaration of
18725 // the next.
18726 if (isa<ParmVarDecl>(var) &&
18727 isa<TranslationUnitDecl>(VarDC))
18728 return;
18729
18730 // For C code, don't diagnose about capture if we're not actually in code
18731 // right now; it's impossible to write a non-constant expression outside of
18732 // function context, so we'll get other (more useful) diagnostics later.
18733 //
18734 // For C++, things get a bit more nasty... it would be nice to suppress this
18735 // diagnostic for certain cases like using a local variable in an array bound
18736 // for a member of a local class, but the correct predicate is not obvious.
18737 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18738 return;
18739
18740 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18741 unsigned ContextKind = 3; // unknown
18742 if (isa<CXXMethodDecl>(VarDC) &&
18743 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18744 ContextKind = 2;
18745 } else if (isa<FunctionDecl>(VarDC)) {
18746 ContextKind = 0;
18747 } else if (isa<BlockDecl>(VarDC)) {
18748 ContextKind = 1;
18749 }
18750
18751 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18752 << var << ValueKind << ContextKind << VarDC;
18753 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18754 << var;
18755
18756 // FIXME: Add additional diagnostic info about class etc. which prevents
18757 // capture.
18758}
18759
18760static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
18761 ValueDecl *Var,
18762 bool &SubCapturesAreNested,
18763 QualType &CaptureType,
18764 QualType &DeclRefType) {
18765 // Check whether we've already captured it.
18766 if (CSI->CaptureMap.count(Var)) {
18767 // If we found a capture, any subcaptures are nested.
18768 SubCapturesAreNested = true;
18769
18770 // Retrieve the capture type for this variable.
18771 CaptureType = CSI->getCapture(Var).getCaptureType();
18772
18773 // Compute the type of an expression that refers to this variable.
18774 DeclRefType = CaptureType.getNonReferenceType();
18775
18776 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18777 // are mutable in the sense that user can change their value - they are
18778 // private instances of the captured declarations.
18779 const Capture &Cap = CSI->getCapture(Var);
18780 if (Cap.isCopyCapture() &&
18781 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
18782 !(isa<CapturedRegionScopeInfo>(CSI) &&
18783 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18784 DeclRefType.addConst();
18785 return true;
18786 }
18787 return false;
18788}
18789
18790// Only block literals, captured statements, and lambda expressions can
18791// capture; other scopes don't work.
18792static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
18793 ValueDecl *Var,
18794 SourceLocation Loc,
18795 const bool Diagnose,
18796 Sema &S) {
18797 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18798 return getLambdaAwareParentOfDeclContext(DC);
18799
18800 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18801 if (Underlying) {
18802 if (Underlying->hasLocalStorage() && Diagnose)
18803 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
18804 }
18805 return nullptr;
18806}
18807
18808// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18809// certain types of variables (unnamed, variably modified types etc.)
18810// so check for eligibility.
18811static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
18812 SourceLocation Loc, const bool Diagnose,
18813 Sema &S) {
18814
18815 assert((isa<VarDecl, BindingDecl>(Var)) &&(static_cast <bool> ((isa<VarDecl, BindingDecl>(Var
)) && "Only variables and structured bindings can be captured"
) ? void (0) : __assert_fail ("(isa<VarDecl, BindingDecl>(Var)) && \"Only variables and structured bindings can be captured\""
, "clang/lib/Sema/SemaExpr.cpp", 18816, __extension__ __PRETTY_FUNCTION__
))
18816 "Only variables and structured bindings can be captured")(static_cast <bool> ((isa<VarDecl, BindingDecl>(Var
)) && "Only variables and structured bindings can be captured"
) ? void (0) : __assert_fail ("(isa<VarDecl, BindingDecl>(Var)) && \"Only variables and structured bindings can be captured\""
, "clang/lib/Sema/SemaExpr.cpp", 18816, __extension__ __PRETTY_FUNCTION__
))
;
18817
18818 bool IsBlock = isa<BlockScopeInfo>(CSI);
18819 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18820
18821 // Lambdas are not allowed to capture unnamed variables
18822 // (e.g. anonymous unions).
18823 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18824 // assuming that's the intent.
18825 if (IsLambda && !Var->getDeclName()) {
18826 if (Diagnose) {
18827 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18828 S.Diag(Var->getLocation(), diag::note_declared_at);
18829 }
18830 return false;
18831 }
18832
18833 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18834 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18835 if (Diagnose) {
18836 S.Diag(Loc, diag::err_ref_vm_type);
18837 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18838 }
18839 return false;
18840 }
18841 // Prohibit structs with flexible array members too.
18842 // We cannot capture what is in the tail end of the struct.
18843 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18844 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18845 if (Diagnose) {
18846 if (IsBlock)
18847 S.Diag(Loc, diag::err_ref_flexarray_type);
18848 else
18849 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18850 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18851 }
18852 return false;
18853 }
18854 }
18855 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18856 // Lambdas and captured statements are not allowed to capture __block
18857 // variables; they don't support the expected semantics.
18858 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18859 if (Diagnose) {
18860 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18861 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18862 }
18863 return false;
18864 }
18865 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18866 if (S.getLangOpts().OpenCL && IsBlock &&
18867 Var->getType()->isBlockPointerType()) {
18868 if (Diagnose)
18869 S.Diag(Loc, diag::err_opencl_block_ref_block);
18870 return false;
18871 }
18872
18873 if (isa<BindingDecl>(Var)) {
18874 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18875 if (Diagnose)
18876 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
18877 return false;
18878 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18879 S.Diag(Loc, S.LangOpts.CPlusPlus20
18880 ? diag::warn_cxx17_compat_capture_binding
18881 : diag::ext_capture_binding)
18882 << Var;
18883 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18884 }
18885 }
18886
18887 return true;
18888}
18889
18890// Returns true if the capture by block was successful.
18891static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
18892 SourceLocation Loc, const bool BuildAndDiagnose,
18893 QualType &CaptureType, QualType &DeclRefType,
18894 const bool Nested, Sema &S, bool Invalid) {
18895 bool ByRef = false;
18896
18897 // Blocks are not allowed to capture arrays, excepting OpenCL.
18898 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18899 // (decayed to pointers).
18900 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18901 if (BuildAndDiagnose) {
18902 S.Diag(Loc, diag::err_ref_array_type);
18903 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18904 Invalid = true;
18905 } else {
18906 return false;
18907 }
18908 }
18909
18910 // Forbid the block-capture of autoreleasing variables.
18911 if (!Invalid &&
18912 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18913 if (BuildAndDiagnose) {
18914 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18915 << /*block*/ 0;
18916 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18917 Invalid = true;
18918 } else {
18919 return false;
18920 }
18921 }
18922
18923 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18924 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18925 QualType PointeeTy = PT->getPointeeType();
18926
18927 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18928 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
18929 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18930 if (BuildAndDiagnose) {
18931 SourceLocation VarLoc = Var->getLocation();
18932 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18933 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18934 }
18935 }
18936 }
18937
18938 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18939 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18940 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
18941 // Block capture by reference does not change the capture or
18942 // declaration reference types.
18943 ByRef = true;
18944 } else {
18945 // Block capture by copy introduces 'const'.
18946 CaptureType = CaptureType.getNonReferenceType().withConst();
18947 DeclRefType = CaptureType;
18948 }
18949
18950 // Actually capture the variable.
18951 if (BuildAndDiagnose)
18952 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18953 CaptureType, Invalid);
18954
18955 return !Invalid;
18956}
18957
18958/// Capture the given variable in the captured region.
18959static bool captureInCapturedRegion(
18960 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
18961 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18962 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18963 bool IsTopScope, Sema &S, bool Invalid) {
18964 // By default, capture variables by reference.
18965 bool ByRef = true;
18966 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18967 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18968 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18969 // Using an LValue reference type is consistent with Lambdas (see below).
18970 if (S.isOpenMPCapturedDecl(Var)) {
18971 bool HasConst = DeclRefType.isConstQualified();
18972 DeclRefType = DeclRefType.getUnqualifiedType();
18973 // Don't lose diagnostics about assignments to const.
18974 if (HasConst)
18975 DeclRefType.addConst();
18976 }
18977 // Do not capture firstprivates in tasks.
18978 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
18979 OMPC_unknown)
18980 return true;
18981 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18982 RSI->OpenMPCaptureLevel);
18983 }
18984
18985 if (ByRef)
18986 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18987 else
18988 CaptureType = DeclRefType;
18989
18990 // Actually capture the variable.
18991 if (BuildAndDiagnose)
18992 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18993 Loc, SourceLocation(), CaptureType, Invalid);
18994
18995 return !Invalid;
18996}
18997
18998/// Capture the given variable in the lambda.
18999static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19000 SourceLocation Loc, const bool BuildAndDiagnose,
19001 QualType &CaptureType, QualType &DeclRefType,
19002 const bool RefersToCapturedVariable,
19003 const Sema::TryCaptureKind Kind,
19004 SourceLocation EllipsisLoc, const bool IsTopScope,
19005 Sema &S, bool Invalid) {
19006 // Determine whether we are capturing by reference or by value.
19007 bool ByRef = false;
19008 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
19009 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
19010 } else {
19011 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19012 }
19013
19014 BindingDecl *BD = dyn_cast<BindingDecl>(Var);
19015 // FIXME: We should support capturing structured bindings in OpenMP.
19016 if (!Invalid && BD && S.LangOpts.OpenMP) {
19017 if (BuildAndDiagnose) {
19018 S.Diag(Loc, diag::err_capture_binding_openmp) << Var;
19019 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19020 }
19021 Invalid = true;
19022 }
19023
19024 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19025 CaptureType.getNonReferenceType()->isWebAssemblyReferenceType()) {
19026 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19027 Invalid = true;
19028 }
19029
19030 // Compute the type of the field that will capture this variable.
19031 if (ByRef) {
19032 // C++11 [expr.prim.lambda]p15:
19033 // An entity is captured by reference if it is implicitly or
19034 // explicitly captured but not captured by copy. It is
19035 // unspecified whether additional unnamed non-static data
19036 // members are declared in the closure type for entities
19037 // captured by reference.
19038 //
19039 // FIXME: It is not clear whether we want to build an lvalue reference
19040 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19041 // to do the former, while EDG does the latter. Core issue 1249 will
19042 // clarify, but for now we follow GCC because it's a more permissive and
19043 // easily defensible position.
19044 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19045 } else {
19046 // C++11 [expr.prim.lambda]p14:
19047 // For each entity captured by copy, an unnamed non-static
19048 // data member is declared in the closure type. The
19049 // declaration order of these members is unspecified. The type
19050 // of such a data member is the type of the corresponding
19051 // captured entity if the entity is not a reference to an
19052 // object, or the referenced type otherwise. [Note: If the
19053 // captured entity is a reference to a function, the
19054 // corresponding data member is also a reference to a
19055 // function. - end note ]
19056 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19057 if (!RefType->getPointeeType()->isFunctionType())
19058 CaptureType = RefType->getPointeeType();
19059 }
19060
19061 // Forbid the lambda copy-capture of autoreleasing variables.
19062 if (!Invalid &&
19063 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19064 if (BuildAndDiagnose) {
19065 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19066 S.Diag(Var->getLocation(), diag::note_previous_decl)
19067 << Var->getDeclName();
19068 Invalid = true;
19069 } else {
19070 return false;
19071 }
19072 }
19073
19074 // Make sure that by-copy captures are of a complete and non-abstract type.
19075 if (!Invalid && BuildAndDiagnose) {
19076 if (!CaptureType->isDependentType() &&
19077 S.RequireCompleteSizedType(
19078 Loc, CaptureType,
19079 diag::err_capture_of_incomplete_or_sizeless_type,
19080 Var->getDeclName()))
19081 Invalid = true;
19082 else if (S.RequireNonAbstractType(Loc, CaptureType,
19083 diag::err_capture_of_abstract_type))
19084 Invalid = true;
19085 }
19086 }
19087
19088 // Compute the type of a reference to this captured variable.
19089 if (ByRef)
19090 DeclRefType = CaptureType.getNonReferenceType();
19091 else {
19092 // C++ [expr.prim.lambda]p5:
19093 // The closure type for a lambda-expression has a public inline
19094 // function call operator [...]. This function call operator is
19095 // declared const (9.3.1) if and only if the lambda-expression's
19096 // parameter-declaration-clause is not followed by mutable.
19097 DeclRefType = CaptureType.getNonReferenceType();
19098 if (!LSI->Mutable && !CaptureType->isReferenceType())
19099 DeclRefType.addConst();
19100 }
19101
19102 // Add the capture.
19103 if (BuildAndDiagnose)
19104 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19105 Loc, EllipsisLoc, CaptureType, Invalid);
19106
19107 return !Invalid;
19108}
19109
19110static bool canCaptureVariableByCopy(ValueDecl *Var,
19111 const ASTContext &Context) {
19112 // Offer a Copy fix even if the type is dependent.
19113 if (Var->getType()->isDependentType())
19114 return true;
19115 QualType T = Var->getType().getNonReferenceType();
19116 if (T.isTriviallyCopyableType(Context))
19117 return true;
19118 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19119
19120 if (!(RD = RD->getDefinition()))
19121 return false;
19122 if (RD->hasSimpleCopyConstructor())
19123 return true;
19124 if (RD->hasUserDeclaredCopyConstructor())
19125 for (CXXConstructorDecl *Ctor : RD->ctors())
19126 if (Ctor->isCopyConstructor())
19127 return !Ctor->isDeleted();
19128 }
19129 return false;
19130}
19131
19132/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19133/// default capture. Fixes may be omitted if they aren't allowed by the
19134/// standard, for example we can't emit a default copy capture fix-it if we
19135/// already explicitly copy capture capture another variable.
19136static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19137 ValueDecl *Var) {
19138 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None)(static_cast <bool> (LSI->ImpCaptureStyle == CapturingScopeInfo
::ImpCap_None) ? void (0) : __assert_fail ("LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None"
, "clang/lib/Sema/SemaExpr.cpp", 19138, __extension__ __PRETTY_FUNCTION__
))
;
19139 // Don't offer Capture by copy of default capture by copy fixes if Var is
19140 // known not to be copy constructible.
19141 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19142
19143 SmallString<32> FixBuffer;
19144 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19145 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19146 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19147 if (ShouldOfferCopyFix) {
19148 // Offer fixes to insert an explicit capture for the variable.
19149 // [] -> [VarName]
19150 // [OtherCapture] -> [OtherCapture, VarName]
19151 FixBuffer.assign({Separator, Var->getName()});
19152 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19153 << Var << /*value*/ 0
19154 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19155 }
19156 // As above but capture by reference.
19157 FixBuffer.assign({Separator, "&", Var->getName()});
19158 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19159 << Var << /*reference*/ 1
19160 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19161 }
19162
19163 // Only try to offer default capture if there are no captures excluding this
19164 // and init captures.
19165 // [this]: OK.
19166 // [X = Y]: OK.
19167 // [&A, &B]: Don't offer.
19168 // [A, B]: Don't offer.
19169 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19170 return !C.isThisCapture() && !C.isInitCapture();
19171 }))
19172 return;
19173
19174 // The default capture specifiers, '=' or '&', must appear first in the
19175 // capture body.
19176 SourceLocation DefaultInsertLoc =
19177 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
19178
19179 if (ShouldOfferCopyFix) {
19180 bool CanDefaultCopyCapture = true;
19181 // [=, *this] OK since c++17
19182 // [=, this] OK since c++20
19183 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19184 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19185 ? LSI->getCXXThisCapture().isCopyCapture()
19186 : false;
19187 // We can't use default capture by copy if any captures already specified
19188 // capture by copy.
19189 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19190 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19191 })) {
19192 FixBuffer.assign({"=", Separator});
19193 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19194 << /*value*/ 0
19195 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19196 }
19197 }
19198
19199 // We can't use default capture by reference if any captures already specified
19200 // capture by reference.
19201 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19202 return !C.isInitCapture() && C.isReferenceCapture() &&
19203 !C.isThisCapture();
19204 })) {
19205 FixBuffer.assign({"&", Separator});
19206 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19207 << /*reference*/ 1
19208 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19209 }
19210}
19211
19212bool Sema::tryCaptureVariable(
19213 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19214 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19215 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19216 // An init-capture is notionally from the context surrounding its
19217 // declaration, but its parent DC is the lambda class.
19218 DeclContext *VarDC = Var->getDeclContext();
19219 DeclContext *DC = CurContext;
19220
19221 // tryCaptureVariable is called every time a DeclRef is formed,
19222 // it can therefore have non-negigible impact on performances.
19223 // For local variables and when there is no capturing scope,
19224 // we can bailout early.
19225 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19226 return true;
19227
19228 const auto *VD = dyn_cast<VarDecl>(Var);
19229 if (VD) {
19230 if (VD->isInitCapture())
19231 VarDC = VarDC->getParent();
19232 } else {
19233 VD = Var->getPotentiallyDecomposedVarDecl();
19234 }
19235 assert(VD && "Cannot capture a null variable")(static_cast <bool> (VD && "Cannot capture a null variable"
) ? void (0) : __assert_fail ("VD && \"Cannot capture a null variable\""
, "clang/lib/Sema/SemaExpr.cpp", 19235, __extension__ __PRETTY_FUNCTION__
))
;
19236
19237 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19238 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19239 // We need to sync up the Declaration Context with the
19240 // FunctionScopeIndexToStopAt
19241 if (FunctionScopeIndexToStopAt) {
19242 unsigned FSIndex = FunctionScopes.size() - 1;
19243 while (FSIndex != MaxFunctionScopesIndex) {
19244 DC = getLambdaAwareParentOfDeclContext(DC);
19245 --FSIndex;
19246 }
19247 }
19248
19249 // Capture global variables if it is required to use private copy of this
19250 // variable.
19251 bool IsGlobal = !VD->hasLocalStorage();
19252 if (IsGlobal &&
19253 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19254 MaxFunctionScopesIndex)))
19255 return true;
19256
19257 if (isa<VarDecl>(Var))
19258 Var = cast<VarDecl>(Var->getCanonicalDecl());
19259
19260 // Walk up the stack to determine whether we can capture the variable,
19261 // performing the "simple" checks that don't depend on type. We stop when
19262 // we've either hit the declared scope of the variable or find an existing
19263 // capture of that variable. We start from the innermost capturing-entity
19264 // (the DC) and ensure that all intervening capturing-entities
19265 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19266 // declcontext can either capture the variable or have already captured
19267 // the variable.
19268 CaptureType = Var->getType();
19269 DeclRefType = CaptureType.getNonReferenceType();
19270 bool Nested = false;
19271 bool Explicit = (Kind != TryCapture_Implicit);
19272 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19273 do {
19274
19275 LambdaScopeInfo *LSI = nullptr;
19276 if (!FunctionScopes.empty())
19277 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19278 FunctionScopes[FunctionScopesIndex]);
19279
19280 bool IsInScopeDeclarationContext =
19281 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19282
19283 if (LSI && !LSI->AfterParameterList) {
19284 // This allows capturing parameters from a default value which does not
19285 // seems correct
19286 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19287 return true;
19288 }
19289 // If the variable is declared in the current context, there is no need to
19290 // capture it.
19291 if (IsInScopeDeclarationContext &&
19292 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19293 return true;
19294
19295 // When evaluating some attributes (like enable_if) we might refer to a
19296 // function parameter appertaining to the same declaration as that
19297 // attribute.
19298 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19299 Parm && Parm->getDeclContext() == DC)
19300 return true;
19301
19302 // Only block literals, captured statements, and lambda expressions can
19303 // capture; other scopes don't work.
19304 DeclContext *ParentDC =
19305 !IsInScopeDeclarationContext
19306 ? DC->getParent()
19307 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19308 BuildAndDiagnose, *this);
19309 // We need to check for the parent *first* because, if we *have*
19310 // private-captured a global variable, we need to recursively capture it in
19311 // intermediate blocks, lambdas, etc.
19312 if (!ParentDC) {
19313 if (IsGlobal) {
19314 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19315 break;
19316 }
19317 return true;
19318 }
19319
19320 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19321 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19322
19323 // Check whether we've already captured it.
19324 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19325 DeclRefType)) {
19326 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19327 break;
19328 }
19329 // If we are instantiating a generic lambda call operator body,
19330 // we do not want to capture new variables. What was captured
19331 // during either a lambdas transformation or initial parsing
19332 // should be used.
19333 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19334 if (BuildAndDiagnose) {
19335 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19336 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19337 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19338 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19339 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19340 buildLambdaCaptureFixit(*this, LSI, Var);
19341 } else
19342 diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);
19343 }
19344 return true;
19345 }
19346
19347 // Try to capture variable-length arrays types.
19348 if (Var->getType()->isVariablyModifiedType()) {
19349 // We're going to walk down into the type and look for VLA
19350 // expressions.
19351 QualType QTy = Var->getType();
19352 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19353 QTy = PVD->getOriginalType();
19354 captureVariablyModifiedType(Context, QTy, CSI);
19355 }
19356
19357 if (getLangOpts().OpenMP) {
19358 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19359 // OpenMP private variables should not be captured in outer scope, so
19360 // just break here. Similarly, global variables that are captured in a
19361 // target region should not be captured outside the scope of the region.
19362 if (RSI->CapRegionKind == CR_OpenMP) {
19363 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
19364 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19365 // If the variable is private (i.e. not captured) and has variably
19366 // modified type, we still need to capture the type for correct
19367 // codegen in all regions, associated with the construct. Currently,
19368 // it is captured in the innermost captured region only.
19369 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19370 Var->getType()->isVariablyModifiedType()) {
19371 QualType QTy = Var->getType();
19372 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19373 QTy = PVD->getOriginalType();
19374 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
19375 I < E; ++I) {
19376 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19377 FunctionScopes[FunctionScopesIndex - I]);
19378 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&(static_cast <bool> (RSI->OpenMPLevel == OuterRSI->
OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "clang/lib/Sema/SemaExpr.cpp", 19380, __extension__ __PRETTY_FUNCTION__
))
19379 "Wrong number of captured regions associated with the "(static_cast <bool> (RSI->OpenMPLevel == OuterRSI->
OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "clang/lib/Sema/SemaExpr.cpp", 19380, __extension__ __PRETTY_FUNCTION__
))
19380 "OpenMP construct.")(static_cast <bool> (RSI->OpenMPLevel == OuterRSI->
OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "clang/lib/Sema/SemaExpr.cpp", 19380, __extension__ __PRETTY_FUNCTION__
))
;
19381 captureVariablyModifiedType(Context, QTy, OuterRSI);
19382 }
19383 }
19384 bool IsTargetCap =
19385 IsOpenMPPrivateDecl != OMPC_private &&
19386 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19387 RSI->OpenMPCaptureLevel);
19388 // Do not capture global if it is not privatized in outer regions.
19389 bool IsGlobalCap =
19390 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
19391 RSI->OpenMPCaptureLevel);
19392
19393 // When we detect target captures we are looking from inside the
19394 // target region, therefore we need to propagate the capture from the
19395 // enclosing region. Therefore, the capture is not initially nested.
19396 if (IsTargetCap)
19397 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
19398
19399 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19400 (IsGlobal && !IsGlobalCap)) {
19401 Nested = !IsTargetCap;
19402 bool HasConst = DeclRefType.isConstQualified();
19403 DeclRefType = DeclRefType.getUnqualifiedType();
19404 // Don't lose diagnostics about assignments to const.
19405 if (HasConst)
19406 DeclRefType.addConst();
19407 CaptureType = Context.getLValueReferenceType(DeclRefType);
19408 break;
19409 }
19410 }
19411 }
19412 }
19413 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19414 // No capture-default, and this is not an explicit capture
19415 // so cannot capture this variable.
19416 if (BuildAndDiagnose) {
19417 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19418 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19419 auto *LSI = cast<LambdaScopeInfo>(CSI);
19420 if (LSI->Lambda) {
19421 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19422 buildLambdaCaptureFixit(*this, LSI, Var);
19423 }
19424 // FIXME: If we error out because an outer lambda can not implicitly
19425 // capture a variable that an inner lambda explicitly captures, we
19426 // should have the inner lambda do the explicit capture - because
19427 // it makes for cleaner diagnostics later. This would purely be done
19428 // so that the diagnostic does not misleadingly claim that a variable
19429 // can not be captured by a lambda implicitly even though it is captured
19430 // explicitly. Suggestion:
19431 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19432 // at the function head
19433 // - cache the StartingDeclContext - this must be a lambda
19434 // - captureInLambda in the innermost lambda the variable.
19435 }
19436 return true;
19437 }
19438 Explicit = false;
19439 FunctionScopesIndex--;
19440 if (IsInScopeDeclarationContext)
19441 DC = ParentDC;
19442 } while (!VarDC->Equals(DC));
19443
19444 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19445 // computing the type of the capture at each step, checking type-specific
19446 // requirements, and adding captures if requested.
19447 // If the variable had already been captured previously, we start capturing
19448 // at the lambda nested within that one.
19449 bool Invalid = false;
19450 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19451 ++I) {
19452 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19453
19454 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19455 // certain types of variables (unnamed, variably modified types etc.)
19456 // so check for eligibility.
19457 if (!Invalid)
19458 Invalid =
19459 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19460
19461 // After encountering an error, if we're actually supposed to capture, keep
19462 // capturing in nested contexts to suppress any follow-on diagnostics.
19463 if (Invalid && !BuildAndDiagnose)
19464 return true;
19465
19466 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19467 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19468 DeclRefType, Nested, *this, Invalid);
19469 Nested = true;
19470 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19471 Invalid = !captureInCapturedRegion(
19472 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19473 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19474 Nested = true;
19475 } else {
19476 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19477 Invalid =
19478 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19479 DeclRefType, Nested, Kind, EllipsisLoc,
19480 /*IsTopScope*/ I == N - 1, *this, Invalid);
19481 Nested = true;
19482 }
19483
19484 if (Invalid && !BuildAndDiagnose)
19485 return true;
19486 }
19487 return Invalid;
19488}
19489
19490bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
19491 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19492 QualType CaptureType;
19493 QualType DeclRefType;
19494 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19495 /*BuildAndDiagnose=*/true, CaptureType,
19496 DeclRefType, nullptr);
19497}
19498
19499bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
19500 QualType CaptureType;
19501 QualType DeclRefType;
19502 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19503 /*BuildAndDiagnose=*/false, CaptureType,
19504 DeclRefType, nullptr);
19505}
19506
19507QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
19508 QualType CaptureType;
19509 QualType DeclRefType;
19510
19511 // Determine whether we can capture this variable.
19512 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19513 /*BuildAndDiagnose=*/false, CaptureType,
19514 DeclRefType, nullptr))
19515 return QualType();
19516
19517 return DeclRefType;
19518}
19519
19520namespace {
19521// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19522// The produced TemplateArgumentListInfo* points to data stored within this
19523// object, so should only be used in contexts where the pointer will not be
19524// used after the CopiedTemplateArgs object is destroyed.
19525class CopiedTemplateArgs {
19526 bool HasArgs;
19527 TemplateArgumentListInfo TemplateArgStorage;
19528public:
19529 template<typename RefExpr>
19530 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19531 if (HasArgs)
19532 E->copyTemplateArgumentsInto(TemplateArgStorage);
19533 }
19534 operator TemplateArgumentListInfo*()
19535#ifdef __has_cpp_attribute
19536#if0 __has_cpp_attribute(clang::lifetimebound)1
19537 [[clang::lifetimebound]]
19538#endif
19539#endif
19540 {
19541 return HasArgs ? &TemplateArgStorage : nullptr;
19542 }
19543};
19544}
19545
19546/// Walk the set of potential results of an expression and mark them all as
19547/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19548///
19549/// \return A new expression if we found any potential results, ExprEmpty() if
19550/// not, and ExprError() if we diagnosed an error.
19551static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
19552 NonOdrUseReason NOUR) {
19553 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19554 // an object that satisfies the requirements for appearing in a
19555 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19556 // is immediately applied." This function handles the lvalue-to-rvalue
19557 // conversion part.
19558 //
19559 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19560 // transform it into the relevant kind of non-odr-use node and rebuild the
19561 // tree of nodes leading to it.
19562 //
19563 // This is a mini-TreeTransform that only transforms a restricted subset of
19564 // nodes (and only certain operands of them).
19565
19566 // Rebuild a subexpression.
19567 auto Rebuild = [&](Expr *Sub) {
19568 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19569 };
19570
19571 // Check whether a potential result satisfies the requirements of NOUR.
19572 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19573 // Any entity other than a VarDecl is always odr-used whenever it's named
19574 // in a potentially-evaluated expression.
19575 auto *VD = dyn_cast<VarDecl>(D);
19576 if (!VD)
19577 return true;
19578
19579 // C++2a [basic.def.odr]p4:
19580 // A variable x whose name appears as a potentially-evalauted expression
19581 // e is odr-used by e unless
19582 // -- x is a reference that is usable in constant expressions, or
19583 // -- x is a variable of non-reference type that is usable in constant
19584 // expressions and has no mutable subobjects, and e is an element of
19585 // the set of potential results of an expression of
19586 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19587 // conversion is applied, or
19588 // -- x is a variable of non-reference type, and e is an element of the
19589 // set of potential results of a discarded-value expression to which
19590 // the lvalue-to-rvalue conversion is not applied
19591 //
19592 // We check the first bullet and the "potentially-evaluated" condition in
19593 // BuildDeclRefExpr. We check the type requirements in the second bullet
19594 // in CheckLValueToRValueConversionOperand below.
19595 switch (NOUR) {
19596 case NOUR_None:
19597 case NOUR_Unevaluated:
19598 llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason"
, "clang/lib/Sema/SemaExpr.cpp", 19598)
;
19599
19600 case NOUR_Constant:
19601 // Constant references were handled when they were built.
19602 if (VD->getType()->isReferenceType())
19603 return true;
19604 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19605 if (RD->hasMutableFields())
19606 return true;
19607 if (!VD->isUsableInConstantExpressions(S.Context))
19608 return true;
19609 break;
19610
19611 case NOUR_Discarded:
19612 if (VD->getType()->isReferenceType())
19613 return true;
19614 break;
19615 }
19616 return false;
19617 };
19618
19619 // Mark that this expression does not constitute an odr-use.
19620 auto MarkNotOdrUsed = [&] {
19621 S.MaybeODRUseExprs.remove(E);
19622 if (LambdaScopeInfo *LSI = S.getCurLambda())
19623 LSI->markVariableExprAsNonODRUsed(E);
19624 };
19625
19626 // C++2a [basic.def.odr]p2:
19627 // The set of potential results of an expression e is defined as follows:
19628 switch (E->getStmtClass()) {
19629 // -- If e is an id-expression, ...
19630 case Expr::DeclRefExprClass: {
19631 auto *DRE = cast<DeclRefExpr>(E);
19632 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19633 break;
19634
19635 // Rebuild as a non-odr-use DeclRefExpr.
19636 MarkNotOdrUsed();
19637 return DeclRefExpr::Create(
19638 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19639 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19640 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19641 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19642 }
19643
19644 case Expr::FunctionParmPackExprClass: {
19645 auto *FPPE = cast<FunctionParmPackExpr>(E);
19646 // If any of the declarations in the pack is odr-used, then the expression
19647 // as a whole constitutes an odr-use.
19648 for (VarDecl *D : *FPPE)
19649 if (IsPotentialResultOdrUsed(D))
19650 return ExprEmpty();
19651
19652 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19653 // nothing cares about whether we marked this as an odr-use, but it might
19654 // be useful for non-compiler tools.
19655 MarkNotOdrUsed();
19656 break;
19657 }
19658
19659 // -- If e is a subscripting operation with an array operand...
19660 case Expr::ArraySubscriptExprClass: {
19661 auto *ASE = cast<ArraySubscriptExpr>(E);
19662 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19663 if (!OldBase->getType()->isArrayType())
19664 break;
19665 ExprResult Base = Rebuild(OldBase);
19666 if (!Base.isUsable())
19667 return Base;
19668 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19669 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19670 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19671 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19672 ASE->getRBracketLoc());
19673 }
19674
19675 case Expr::MemberExprClass: {
19676 auto *ME = cast<MemberExpr>(E);
19677 // -- If e is a class member access expression [...] naming a non-static
19678 // data member...
19679 if (isa<FieldDecl>(ME->getMemberDecl())) {
19680 ExprResult Base = Rebuild(ME->getBase());
19681 if (!Base.isUsable())
19682 return Base;
19683 return MemberExpr::Create(
19684 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19685 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19686 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19687 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19688 ME->getObjectKind(), ME->isNonOdrUse());
19689 }
19690
19691 if (ME->getMemberDecl()->isCXXInstanceMember())
19692 break;
19693
19694 // -- If e is a class member access expression naming a static data member,
19695 // ...
19696 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19697 break;
19698
19699 // Rebuild as a non-odr-use MemberExpr.
19700 MarkNotOdrUsed();
19701 return MemberExpr::Create(
19702 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19703 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19704 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19705 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19706 }
19707
19708 case Expr::BinaryOperatorClass: {
19709 auto *BO = cast<BinaryOperator>(E);
19710 Expr *LHS = BO->getLHS();
19711 Expr *RHS = BO->getRHS();
19712 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19713 if (BO->getOpcode() == BO_PtrMemD) {
19714 ExprResult Sub = Rebuild(LHS);
19715 if (!Sub.isUsable())
19716 return Sub;
19717 LHS = Sub.get();
19718 // -- If e is a comma expression, ...
19719 } else if (BO->getOpcode() == BO_Comma) {
19720 ExprResult Sub = Rebuild(RHS);
19721 if (!Sub.isUsable())
19722 return Sub;
19723 RHS = Sub.get();
19724 } else {
19725 break;
19726 }
19727 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
19728 LHS, RHS);
19729 }
19730
19731 // -- If e has the form (e1)...
19732 case Expr::ParenExprClass: {
19733 auto *PE = cast<ParenExpr>(E);
19734 ExprResult Sub = Rebuild(PE->getSubExpr());
19735 if (!Sub.isUsable())
19736 return Sub;
19737 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19738 }
19739
19740 // -- If e is a glvalue conditional expression, ...
19741 // We don't apply this to a binary conditional operator. FIXME: Should we?
19742 case Expr::ConditionalOperatorClass: {
19743 auto *CO = cast<ConditionalOperator>(E);
19744 ExprResult LHS = Rebuild(CO->getLHS());
19745 if (LHS.isInvalid())
19746 return ExprError();
19747 ExprResult RHS = Rebuild(CO->getRHS());
19748 if (RHS.isInvalid())
19749 return ExprError();
19750 if (!LHS.isUsable() && !RHS.isUsable())
19751 return ExprEmpty();
19752 if (!LHS.isUsable())
19753 LHS = CO->getLHS();
19754 if (!RHS.isUsable())
19755 RHS = CO->getRHS();
19756 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19757 CO->getCond(), LHS.get(), RHS.get());
19758 }
19759
19760 // [Clang extension]
19761 // -- If e has the form __extension__ e1...
19762 case Expr::UnaryOperatorClass: {
19763 auto *UO = cast<UnaryOperator>(E);
19764 if (UO->getOpcode() != UO_Extension)
19765 break;
19766 ExprResult Sub = Rebuild(UO->getSubExpr());
19767 if (!Sub.isUsable())
19768 return Sub;
19769 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19770 Sub.get());
19771 }
19772
19773 // [Clang extension]
19774 // -- If e has the form _Generic(...), the set of potential results is the
19775 // union of the sets of potential results of the associated expressions.
19776 case Expr::GenericSelectionExprClass: {
19777 auto *GSE = cast<GenericSelectionExpr>(E);
19778
19779 SmallVector<Expr *, 4> AssocExprs;
19780 bool AnyChanged = false;
19781 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19782 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19783 if (AssocExpr.isInvalid())
19784 return ExprError();
19785 if (AssocExpr.isUsable()) {
19786 AssocExprs.push_back(AssocExpr.get());
19787 AnyChanged = true;
19788 } else {
19789 AssocExprs.push_back(OrigAssocExpr);
19790 }
19791 }
19792
19793 return AnyChanged ? S.CreateGenericSelectionExpr(
19794 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19795 GSE->getRParenLoc(), GSE->getControllingExpr(),
19796 GSE->getAssocTypeSourceInfos(), AssocExprs)
19797 : ExprEmpty();
19798 }
19799
19800 // [Clang extension]
19801 // -- If e has the form __builtin_choose_expr(...), the set of potential
19802 // results is the union of the sets of potential results of the
19803 // second and third subexpressions.
19804 case Expr::ChooseExprClass: {
19805 auto *CE = cast<ChooseExpr>(E);
19806
19807 ExprResult LHS = Rebuild(CE->getLHS());
19808 if (LHS.isInvalid())
19809 return ExprError();
19810
19811 ExprResult RHS = Rebuild(CE->getLHS());
19812 if (RHS.isInvalid())
19813 return ExprError();
19814
19815 if (!LHS.get() && !RHS.get())
19816 return ExprEmpty();
19817 if (!LHS.isUsable())
19818 LHS = CE->getLHS();
19819 if (!RHS.isUsable())
19820 RHS = CE->getRHS();
19821
19822 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19823 RHS.get(), CE->getRParenLoc());
19824 }
19825
19826 // Step through non-syntactic nodes.
19827 case Expr::ConstantExprClass: {
19828 auto *CE = cast<ConstantExpr>(E);
19829 ExprResult Sub = Rebuild(CE->getSubExpr());
19830 if (!Sub.isUsable())
19831 return Sub;
19832 return ConstantExpr::Create(S.Context, Sub.get());
19833 }
19834
19835 // We could mostly rely on the recursive rebuilding to rebuild implicit
19836 // casts, but not at the top level, so rebuild them here.
19837 case Expr::ImplicitCastExprClass: {
19838 auto *ICE = cast<ImplicitCastExpr>(E);
19839 // Only step through the narrow set of cast kinds we expect to encounter.
19840 // Anything else suggests we've left the region in which potential results
19841 // can be found.
19842 switch (ICE->getCastKind()) {
19843 case CK_NoOp:
19844 case CK_DerivedToBase:
19845 case CK_UncheckedDerivedToBase: {
19846 ExprResult Sub = Rebuild(ICE->getSubExpr());
19847 if (!Sub.isUsable())
19848 return Sub;
19849 CXXCastPath Path(ICE->path());
19850 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19851 ICE->getValueKind(), &Path);
19852 }
19853
19854 default:
19855 break;
19856 }
19857 break;
19858 }
19859
19860 default:
19861 break;
19862 }
19863
19864 // Can't traverse through this node. Nothing to do.
19865 return ExprEmpty();
19866}
19867
19868ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
19869 // Check whether the operand is or contains an object of non-trivial C union
19870 // type.
19871 if (E->getType().isVolatileQualified() &&
19872 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19873 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19874 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
19875 Sema::NTCUC_LValueToRValueVolatile,
19876 NTCUK_Destruct|NTCUK_Copy);
19877
19878 // C++2a [basic.def.odr]p4:
19879 // [...] an expression of non-volatile-qualified non-class type to which
19880 // the lvalue-to-rvalue conversion is applied [...]
19881 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19882 return E;
19883
19884 ExprResult Result =
19885 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
19886 if (Result.isInvalid())
19887 return ExprError();
19888 return Result.get() ? Result : E;
19889}
19890
19891ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
19892 Res = CorrectDelayedTyposInExpr(Res);
19893
19894 if (!Res.isUsable())
19895 return Res;
19896
19897 // If a constant-expression is a reference to a variable where we delay
19898 // deciding whether it is an odr-use, just assume we will apply the
19899 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19900 // (a non-type template argument), we have special handling anyway.
19901 return CheckLValueToRValueConversionOperand(Res.get());
19902}
19903
19904void Sema::CleanupVarDeclMarking() {
19905 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19906 // call.
19907 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19908 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19909
19910 for (Expr *E : LocalMaybeODRUseExprs) {
19911 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19912 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19913 DRE->getLocation(), *this);
19914 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19915 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19916 *this);
19917 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19918 for (VarDecl *VD : *FP)
19919 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19920 } else {
19921 llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "clang/lib/Sema/SemaExpr.cpp"
, 19921)
;
19922 }
19923 }
19924
19925 assert(MaybeODRUseExprs.empty() &&(static_cast <bool> (MaybeODRUseExprs.empty() &&
"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?") ? void
(0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\""
, "clang/lib/Sema/SemaExpr.cpp", 19926, __extension__ __PRETTY_FUNCTION__
))
19926 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")(static_cast <bool> (MaybeODRUseExprs.empty() &&
"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?") ? void
(0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\""
, "clang/lib/Sema/SemaExpr.cpp", 19926, __extension__ __PRETTY_FUNCTION__
))
;
19927}
19928
19929static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
19930 ValueDecl *Var, Expr *E) {
19931 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
19932 if (!VD)
19933 return;
19934
19935 const bool RefersToEnclosingScope =
19936 (SemaRef.CurContext != VD->getDeclContext() &&
19937 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
19938 if (RefersToEnclosingScope) {
19939 LambdaScopeInfo *const LSI =
19940 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19941 if (LSI && (!LSI->CallOperator ||
19942 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19943 // If a variable could potentially be odr-used, defer marking it so
19944 // until we finish analyzing the full expression for any
19945 // lvalue-to-rvalue
19946 // or discarded value conversions that would obviate odr-use.
19947 // Add it to the list of potential captures that will be analyzed
19948 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19949 // unless the variable is a reference that was initialized by a constant
19950 // expression (this will never need to be captured or odr-used).
19951 //
19952 // FIXME: We can simplify this a lot after implementing P0588R1.
19953 assert(E && "Capture variable should be used in an expression.")(static_cast <bool> (E && "Capture variable should be used in an expression."
) ? void (0) : __assert_fail ("E && \"Capture variable should be used in an expression.\""
, "clang/lib/Sema/SemaExpr.cpp", 19953, __extension__ __PRETTY_FUNCTION__
))
;
19954 if (!Var->getType()->isReferenceType() ||
19955 !VD->isUsableInConstantExpressions(SemaRef.Context))
19956 LSI->addPotentialCapture(E->IgnoreParens());
19957 }
19958 }
19959}
19960
19961static void DoMarkVarDeclReferenced(
19962 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19963 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19964 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(static_cast <bool> ((!E || isa<DeclRefExpr>(E) ||
isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(
E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "clang/lib/Sema/SemaExpr.cpp", 19966, __extension__ __PRETTY_FUNCTION__
))
19965 isa<FunctionParmPackExpr>(E)) &&(static_cast <bool> ((!E || isa<DeclRefExpr>(E) ||
isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(
E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "clang/lib/Sema/SemaExpr.cpp", 19966, __extension__ __PRETTY_FUNCTION__
))
19966 "Invalid Expr argument to DoMarkVarDeclReferenced")(static_cast <bool> ((!E || isa<DeclRefExpr>(E) ||
isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(
E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "clang/lib/Sema/SemaExpr.cpp", 19966, __extension__ __PRETTY_FUNCTION__
))
;
19967 Var->setReferenced();
19968
19969 if (Var->isInvalidDecl())
19970 return;
19971
19972 auto *MSI = Var->getMemberSpecializationInfo();
19973 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
19974 : Var->getTemplateSpecializationKind();
19975
19976 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19977 bool UsableInConstantExpr =
19978 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
19979
19980 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19981 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19982 }
19983
19984 // C++20 [expr.const]p12:
19985 // A variable [...] is needed for constant evaluation if it is [...] a
19986 // variable whose name appears as a potentially constant evaluated
19987 // expression that is either a contexpr variable or is of non-volatile
19988 // const-qualified integral type or of reference type
19989 bool NeededForConstantEvaluation =
19990 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19991
19992 bool NeedDefinition =
19993 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19994
19995 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&(static_cast <bool> (!isa<VarTemplatePartialSpecializationDecl
>(Var) && "Can't instantiate a partial template specialization."
) ? void (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\""
, "clang/lib/Sema/SemaExpr.cpp", 19996, __extension__ __PRETTY_FUNCTION__
))
19996 "Can't instantiate a partial template specialization.")(static_cast <bool> (!isa<VarTemplatePartialSpecializationDecl
>(Var) && "Can't instantiate a partial template specialization."
) ? void (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\""
, "clang/lib/Sema/SemaExpr.cpp", 19996, __extension__ __PRETTY_FUNCTION__
))
;
19997
19998 // If this might be a member specialization of a static data member, check
19999 // the specialization is visible. We already did the checks for variable
20000 // template specializations when we created them.
20001 if (NeedDefinition && TSK != TSK_Undeclared &&
20002 !isa<VarTemplateSpecializationDecl>(Var))
20003 SemaRef.checkSpecializationVisibility(Loc, Var);
20004
20005 // Perform implicit instantiation of static data members, static data member
20006 // templates of class templates, and variable template specializations. Delay
20007 // instantiations of variable templates, except for those that could be used
20008 // in a constant expression.
20009 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20010 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20011 // instantiation declaration if a variable is usable in a constant
20012 // expression (among other cases).
20013 bool TryInstantiating =
20014 TSK == TSK_ImplicitInstantiation ||
20015 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20016
20017 if (TryInstantiating) {
20018 SourceLocation PointOfInstantiation =
20019 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20020 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20021 if (FirstInstantiation) {
20022 PointOfInstantiation = Loc;
20023 if (MSI)
20024 MSI->setPointOfInstantiation(PointOfInstantiation);
20025 // FIXME: Notify listener.
20026 else
20027 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20028 }
20029
20030 if (UsableInConstantExpr) {
20031 // Do not defer instantiations of variables that could be used in a
20032 // constant expression.
20033 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20034 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20035 });
20036
20037 // Re-set the member to trigger a recomputation of the dependence bits
20038 // for the expression.
20039 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20040 DRE->setDecl(DRE->getDecl());
20041 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20042 ME->setMemberDecl(ME->getMemberDecl());
20043 } else if (FirstInstantiation) {
20044 SemaRef.PendingInstantiations
20045 .push_back(std::make_pair(Var, PointOfInstantiation));
20046 } else {
20047 bool Inserted = false;
20048 for (auto &I : SemaRef.SavedPendingInstantiations) {
20049 auto Iter = llvm::find_if(
20050 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20051 return P.first == Var;
20052 });
20053 if (Iter != I.end()) {
20054 SemaRef.PendingInstantiations.push_back(*Iter);
20055 I.erase(Iter);
20056 Inserted = true;
20057 break;
20058 }
20059 }
20060
20061 // FIXME: For a specialization of a variable template, we don't
20062 // distinguish between "declaration and type implicitly instantiated"
20063 // and "implicit instantiation of definition requested", so we have
20064 // no direct way to avoid enqueueing the pending instantiation
20065 // multiple times.
20066 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20067 SemaRef.PendingInstantiations
20068 .push_back(std::make_pair(Var, PointOfInstantiation));
20069 }
20070 }
20071 }
20072
20073 // C++2a [basic.def.odr]p4:
20074 // A variable x whose name appears as a potentially-evaluated expression e
20075 // is odr-used by e unless
20076 // -- x is a reference that is usable in constant expressions
20077 // -- x is a variable of non-reference type that is usable in constant
20078 // expressions and has no mutable subobjects [FIXME], and e is an
20079 // element of the set of potential results of an expression of
20080 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20081 // conversion is applied
20082 // -- x is a variable of non-reference type, and e is an element of the set
20083 // of potential results of a discarded-value expression to which the
20084 // lvalue-to-rvalue conversion is not applied [FIXME]
20085 //
20086 // We check the first part of the second bullet here, and
20087 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20088 // FIXME: To get the third bullet right, we need to delay this even for
20089 // variables that are not usable in constant expressions.
20090
20091 // If we already know this isn't an odr-use, there's nothing more to do.
20092 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20093 if (DRE->isNonOdrUse())
20094 return;
20095 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20096 if (ME->isNonOdrUse())
20097 return;
20098
20099 switch (OdrUse) {
20100 case OdrUseContext::None:
20101 // In some cases, a variable may not have been marked unevaluated, if it
20102 // appears in a defaukt initializer.
20103 assert((!E || isa<FunctionParmPackExpr>(E) ||(static_cast <bool> ((!E || isa<FunctionParmPackExpr
>(E) || SemaRef.isUnevaluatedContext()) && "missing non-odr-use marking for unevaluated decl ref"
) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E) || SemaRef.isUnevaluatedContext()) && \"missing non-odr-use marking for unevaluated decl ref\""
, "clang/lib/Sema/SemaExpr.cpp", 20105, __extension__ __PRETTY_FUNCTION__
))
20104 SemaRef.isUnevaluatedContext()) &&(static_cast <bool> ((!E || isa<FunctionParmPackExpr
>(E) || SemaRef.isUnevaluatedContext()) && "missing non-odr-use marking for unevaluated decl ref"
) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E) || SemaRef.isUnevaluatedContext()) && \"missing non-odr-use marking for unevaluated decl ref\""
, "clang/lib/Sema/SemaExpr.cpp", 20105, __extension__ __PRETTY_FUNCTION__
))
20105 "missing non-odr-use marking for unevaluated decl ref")(static_cast <bool> ((!E || isa<FunctionParmPackExpr
>(E) || SemaRef.isUnevaluatedContext()) && "missing non-odr-use marking for unevaluated decl ref"
) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E) || SemaRef.isUnevaluatedContext()) && \"missing non-odr-use marking for unevaluated decl ref\""
, "clang/lib/Sema/SemaExpr.cpp", 20105, __extension__ __PRETTY_FUNCTION__
))
;
20106 break;
20107
20108 case OdrUseContext::FormallyOdrUsed:
20109 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20110 // behavior.
20111 break;
20112
20113 case OdrUseContext::Used:
20114 // If we might later find that this expression isn't actually an odr-use,
20115 // delay the marking.
20116 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
20117 SemaRef.MaybeODRUseExprs.insert(E);
20118 else
20119 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20120 break;
20121
20122 case OdrUseContext::Dependent:
20123 // If this is a dependent context, we don't need to mark variables as
20124 // odr-used, but we may still need to track them for lambda capture.
20125 // FIXME: Do we also need to do this inside dependent typeid expressions
20126 // (which are modeled as unevaluated at this point)?
20127 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20128 break;
20129 }
20130}
20131
20132static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20133 BindingDecl *BD, Expr *E) {
20134 BD->setReferenced();
20135
20136 if (BD->isInvalidDecl())
20137 return;
20138
20139 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20140 if (OdrUse == OdrUseContext::Used) {
20141 QualType CaptureType, DeclRefType;
20142 SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit,
20143 /*EllipsisLoc*/ SourceLocation(),
20144 /*BuildAndDiagnose*/ true, CaptureType,
20145 DeclRefType,
20146 /*FunctionScopeIndexToStopAt*/ nullptr);
20147 } else if (OdrUse == OdrUseContext::Dependent) {
20148 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20149 }
20150}
20151
20152/// Mark a variable referenced, and check whether it is odr-used
20153/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
20154/// used directly for normal expressions referring to VarDecl.
20155void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20156 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20157}
20158
20159static void
20160MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20161 bool MightBeOdrUse,
20162 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20163 if (SemaRef.isInOpenMPDeclareTargetContext())
20164 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
20165
20166 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20167 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20168 return;
20169 }
20170
20171 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20172 DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);
20173 return;
20174 }
20175
20176 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20177
20178 // If this is a call to a method via a cast, also mark the method in the
20179 // derived class used in case codegen can devirtualize the call.
20180 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20181 if (!ME)
20182 return;
20183 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20184 if (!MD)
20185 return;
20186 // Only attempt to devirtualize if this is truly a virtual call.
20187 bool IsVirtualCall = MD->isVirtual() &&
20188 ME->performsVirtualDispatch(SemaRef.getLangOpts());
20189 if (!IsVirtualCall)
20190 return;
20191
20192 // If it's possible to devirtualize the call, mark the called function
20193 // referenced.
20194 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20195 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20196 if (DM)
20197 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20198}
20199
20200/// Perform reference-marking and odr-use handling for a DeclRefExpr.
20201///
20202/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
20203/// handled with care if the DeclRefExpr is not newly-created.
20204void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20205 // TODO: update this with DR# once a defect report is filed.
20206 // C++11 defect. The address of a pure member should not be an ODR use, even
20207 // if it's a qualified reference.
20208 bool OdrUse = true;
20209 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20210 if (Method->isVirtual() &&
20211 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20212 OdrUse = false;
20213
20214 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
20215 if (!isUnevaluatedContext() && !isConstantEvaluated() &&
20216 !isImmediateFunctionContext() &&
20217 !isCheckingDefaultArgumentOrInitializer() && FD->isConsteval() &&
20218 !RebuildingImmediateInvocation && !FD->isDependentContext())
20219 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20220 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20221 RefsMinusAssignments);
20222}
20223
20224/// Perform reference-marking and odr-use handling for a MemberExpr.
20225void Sema::MarkMemberReferenced(MemberExpr *E) {
20226 // C++11 [basic.def.odr]p2:
20227 // A non-overloaded function whose name appears as a potentially-evaluated
20228 // expression or a member of a set of candidate functions, if selected by
20229 // overload resolution when referred to from a potentially-evaluated
20230 // expression, is odr-used, unless it is a pure virtual function and its
20231 // name is not explicitly qualified.
20232 bool MightBeOdrUse = true;
20233 if (E->performsVirtualDispatch(getLangOpts())) {
20234 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20235 if (Method->isPure())
20236 MightBeOdrUse = false;
20237 }
20238 SourceLocation Loc =
20239 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20240 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20241 RefsMinusAssignments);
20242}
20243
20244/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20245void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20246 for (VarDecl *VD : *E)
20247 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20248 RefsMinusAssignments);
20249}
20250
20251/// Perform marking for a reference to an arbitrary declaration. It
20252/// marks the declaration referenced, and performs odr-use checking for
20253/// functions and variables. This method should not be used when building a
20254/// normal expression which refers to a variable.
20255void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20256 bool MightBeOdrUse) {
20257 if (MightBeOdrUse) {
20258 if (auto *VD = dyn_cast<VarDecl>(D)) {
20259 MarkVariableReferenced(Loc, VD);
20260 return;
20261 }
20262 }
20263 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20264 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20265 return;
20266 }
20267 D->setReferenced();
20268}
20269
20270namespace {
20271 // Mark all of the declarations used by a type as referenced.
20272 // FIXME: Not fully implemented yet! We need to have a better understanding
20273 // of when we're entering a context we should not recurse into.
20274 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20275 // TreeTransforms rebuilding the type in a new context. Rather than
20276 // duplicating the TreeTransform logic, we should consider reusing it here.
20277 // Currently that causes problems when rebuilding LambdaExprs.
20278 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
20279 Sema &S;
20280 SourceLocation Loc;
20281
20282 public:
20283 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
20284
20285 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
20286
20287 bool TraverseTemplateArgument(const TemplateArgument &Arg);
20288 };
20289}
20290
20291bool MarkReferencedDecls::TraverseTemplateArgument(
20292 const TemplateArgument &Arg) {
20293 {
20294 // A non-type template argument is a constant-evaluated context.
20295 EnterExpressionEvaluationContext Evaluated(
20296 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20297 if (Arg.getKind() == TemplateArgument::Declaration) {
20298 if (Decl *D = Arg.getAsDecl())
20299 S.MarkAnyDeclReferenced(Loc, D, true);
20300 } else if (Arg.getKind() == TemplateArgument::Expression) {
20301 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
20302 }
20303 }
20304
20305 return Inherited::TraverseTemplateArgument(Arg);
20306}
20307
20308void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20309 MarkReferencedDecls Marker(*this, Loc);
20310 Marker.TraverseType(T);
20311}
20312
20313namespace {
20314/// Helper class that marks all of the declarations referenced by
20315/// potentially-evaluated subexpressions as "referenced".
20316class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20317public:
20318 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20319 bool SkipLocalVariables;
20320 ArrayRef<const Expr *> StopAt;
20321
20322 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20323 ArrayRef<const Expr *> StopAt)
20324 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20325
20326 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20327 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20328 }
20329
20330 void Visit(Expr *E) {
20331 if (llvm::is_contained(StopAt, E))
20332 return;
20333 Inherited::Visit(E);
20334 }
20335
20336 void VisitConstantExpr(ConstantExpr *E) {
20337 // Don't mark declarations within a ConstantExpression, as this expression
20338 // will be evaluated and folded to a value.
20339 }
20340
20341 void VisitDeclRefExpr(DeclRefExpr *E) {
20342 // If we were asked not to visit local variables, don't.
20343 if (SkipLocalVariables) {
20344 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20345 if (VD->hasLocalStorage())
20346 return;
20347 }
20348
20349 // FIXME: This can trigger the instantiation of the initializer of a
20350 // variable, which can cause the expression to become value-dependent
20351 // or error-dependent. Do we need to propagate the new dependence bits?
20352 S.MarkDeclRefReferenced(E);
20353 }
20354
20355 void VisitMemberExpr(MemberExpr *E) {
20356 S.MarkMemberReferenced(E);
20357 Visit(E->getBase());
20358 }
20359};
20360} // namespace
20361
20362/// Mark any declarations that appear within this expression or any
20363/// potentially-evaluated subexpressions as "referenced".
20364///
20365/// \param SkipLocalVariables If true, don't mark local variables as
20366/// 'referenced'.
20367/// \param StopAt Subexpressions that we shouldn't recurse into.
20368void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
20369 bool SkipLocalVariables,
20370 ArrayRef<const Expr*> StopAt) {
20371 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20372}
20373
20374/// Emit a diagnostic when statements are reachable.
20375/// FIXME: check for reachability even in expressions for which we don't build a
20376/// CFG (eg, in the initializer of a global or in a constant expression).
20377/// For example,
20378/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20379bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20380 const PartialDiagnostic &PD) {
20381 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20382 if (!FunctionScopes.empty())
20383 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20384 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20385 return true;
20386 }
20387
20388 // The initializer of a constexpr variable or of the first declaration of a
20389 // static data member is not syntactically a constant evaluated constant,
20390 // but nonetheless is always required to be a constant expression, so we
20391 // can skip diagnosing.
20392 // FIXME: Using the mangling context here is a hack.
20393 if (auto *VD = dyn_cast_or_null<VarDecl>(
20394 ExprEvalContexts.back().ManglingContextDecl)) {
20395 if (VD->isConstexpr() ||
20396 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20397 return false;
20398 // FIXME: For any other kind of variable, we should build a CFG for its
20399 // initializer and check whether the context in question is reachable.
20400 }
20401
20402 Diag(Loc, PD);
20403 return true;
20404}
20405
20406/// Emit a diagnostic that describes an effect on the run-time behavior
20407/// of the program being compiled.
20408///
20409/// This routine emits the given diagnostic when the code currently being
20410/// type-checked is "potentially evaluated", meaning that there is a
20411/// possibility that the code will actually be executable. Code in sizeof()
20412/// expressions, code used only during overload resolution, etc., are not
20413/// potentially evaluated. This routine will suppress such diagnostics or,
20414/// in the absolutely nutty case of potentially potentially evaluated
20415/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20416/// later.
20417///
20418/// This routine should be used for all diagnostics that describe the run-time
20419/// behavior of a program, such as passing a non-POD value through an ellipsis.
20420/// Failure to do so will likely result in spurious diagnostics or failures
20421/// during overload resolution or within sizeof/alignof/typeof/typeid.
20422bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
20423 const PartialDiagnostic &PD) {
20424
20425 if (ExprEvalContexts.back().isDiscardedStatementContext())
20426 return false;
20427
20428 switch (ExprEvalContexts.back().Context) {
20429 case ExpressionEvaluationContext::Unevaluated:
20430 case ExpressionEvaluationContext::UnevaluatedList:
20431 case ExpressionEvaluationContext::UnevaluatedAbstract:
20432 case ExpressionEvaluationContext::DiscardedStatement:
20433 // The argument will never be evaluated, so don't complain.
20434 break;
20435
20436 case ExpressionEvaluationContext::ConstantEvaluated:
20437 case ExpressionEvaluationContext::ImmediateFunctionContext:
20438 // Relevant diagnostics should be produced by constant evaluation.
20439 break;
20440
20441 case ExpressionEvaluationContext::PotentiallyEvaluated:
20442 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
20443 return DiagIfReachable(Loc, Stmts, PD);
20444 }
20445
20446 return false;
20447}
20448
20449bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
20450 const PartialDiagnostic &PD) {
20451 return DiagRuntimeBehavior(
20452 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20453}
20454
20455bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
20456 CallExpr *CE, FunctionDecl *FD) {
20457 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20458 return false;
20459
20460 // If we're inside a decltype's expression, don't check for a valid return
20461 // type or construct temporaries until we know whether this is the last call.
20462 if (ExprEvalContexts.back().ExprContext ==
20463 ExpressionEvaluationContextRecord::EK_Decltype) {
20464 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20465 return false;
20466 }
20467
20468 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20469 FunctionDecl *FD;
20470 CallExpr *CE;
20471
20472 public:
20473 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20474 : FD(FD), CE(CE) { }
20475
20476 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20477 if (!FD) {
20478 S.Diag(Loc, diag::err_call_incomplete_return)
20479 << T << CE->getSourceRange();
20480 return;
20481 }
20482
20483 S.Diag(Loc, diag::err_call_function_incomplete_return)
20484 << CE->getSourceRange() << FD << T;
20485 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20486 << FD->getDeclName();
20487 }
20488 } Diagnoser(FD, CE);
20489
20490 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20491 return true;
20492
20493 return false;
20494}
20495
20496// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20497// will prevent this condition from triggering, which is what we want.
20498void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
20499 SourceLocation Loc;
20500
20501 unsigned diagnostic = diag::warn_condition_is_assignment;
20502 bool IsOrAssign = false;
20503
20504 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20505 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20506 return;
20507
20508 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20509
20510 // Greylist some idioms by putting them into a warning subcategory.
20511 if (ObjCMessageExpr *ME
20512 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20513 Selector Sel = ME->getSelector();
20514
20515 // self = [<foo> init...]
20516 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20517 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20518
20519 // <foo> = [<bar> nextObject]
20520 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20521 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20522 }
20523
20524 Loc = Op->getOperatorLoc();
20525 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20526 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20527 return;
20528
20529 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20530 Loc = Op->getOperatorLoc();
20531 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20532 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20533 else {
20534 // Not an assignment.
20535 return;
20536 }
20537
20538 Diag(Loc, diagnostic) << E->getSourceRange();
20539
20540 SourceLocation Open = E->getBeginLoc();
20541 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
20542 Diag(Loc, diag::note_condition_assign_silence)
20543 << FixItHint::CreateInsertion(Open, "(")
20544 << FixItHint::CreateInsertion(Close, ")");
20545
20546 if (IsOrAssign)
20547 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20548 << FixItHint::CreateReplacement(Loc, "!=");
20549 else
20550 Diag(Loc, diag::note_condition_assign_to_comparison)
20551 << FixItHint::CreateReplacement(Loc, "==");
20552}
20553
20554/// Redundant parentheses over an equality comparison can indicate
20555/// that the user intended an assignment used as condition.
20556void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
20557 // Don't warn if the parens came from a macro.
20558 SourceLocation parenLoc = ParenE->getBeginLoc();
20559 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20560 return;
20561 // Don't warn for dependent expressions.
20562 if (ParenE->isTypeDependent())
20563 return;
20564
20565 Expr *E = ParenE->IgnoreParens();
20566
20567 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20568 if (opE->getOpcode() == BO_EQ &&
20569 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20570 == Expr::MLV_Valid) {
20571 SourceLocation Loc = opE->getOperatorLoc();
20572
20573 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20574 SourceRange ParenERange = ParenE->getSourceRange();
20575 Diag(Loc, diag::note_equality_comparison_silence)
20576 << FixItHint::CreateRemoval(ParenERange.getBegin())
20577 << FixItHint::CreateRemoval(ParenERange.getEnd());
20578 Diag(Loc, diag::note_equality_comparison_to_assign)
20579 << FixItHint::CreateReplacement(Loc, "=");
20580 }
20581}
20582
20583ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
20584 bool IsConstexpr) {
20585 DiagnoseAssignmentAsCondition(E);
20586 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20587 DiagnoseEqualityWithExtraParens(parenE);
20588
20589 ExprResult result = CheckPlaceholderExpr(E);
20590 if (result.isInvalid()) return ExprError();
20591 E = result.get();
20592
20593 if (!E->isTypeDependent()) {
20594 if (getLangOpts().CPlusPlus)
20595 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20596
20597 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
20598 if (ERes.isInvalid())
20599 return ExprError();
20600 E = ERes.get();
20601
20602 QualType T = E->getType();
20603 if (!T->isScalarType()) { // C99 6.8.4.1p1
20604 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20605 << T << E->getSourceRange();
20606 return ExprError();
20607 }
20608 CheckBoolLikeConversion(E, Loc);
20609 }
20610
20611 return E;
20612}
20613
20614Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
20615 Expr *SubExpr, ConditionKind CK,
20616 bool MissingOK) {
20617 // MissingOK indicates whether having no condition expression is valid
20618 // (for loop) or invalid (e.g. while loop).
20619 if (!SubExpr)
20620 return MissingOK ? ConditionResult() : ConditionError();
20621
20622 ExprResult Cond;
20623 switch (CK) {
20624 case ConditionKind::Boolean:
20625 Cond = CheckBooleanCondition(Loc, SubExpr);
20626 break;
20627
20628 case ConditionKind::ConstexprIf:
20629 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20630 break;
20631
20632 case ConditionKind::Switch:
20633 Cond = CheckSwitchCondition(Loc, SubExpr);
20634 break;
20635 }
20636 if (Cond.isInvalid()) {
20637 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20638 {SubExpr}, PreferredConditionType(CK));
20639 if (!Cond.get())
20640 return ConditionError();
20641 }
20642 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20643 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
20644 if (!FullExpr.get())
20645 return ConditionError();
20646
20647 return ConditionResult(*this, nullptr, FullExpr,
20648 CK == ConditionKind::ConstexprIf);
20649}
20650
20651namespace {
20652 /// A visitor for rebuilding a call to an __unknown_any expression
20653 /// to have an appropriate type.
20654 struct RebuildUnknownAnyFunction
20655 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20656
20657 Sema &S;
20658
20659 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20660
20661 ExprResult VisitStmt(Stmt *S) {
20662 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp"
, 20662)
;
20663 }
20664
20665 ExprResult VisitExpr(Expr *E) {
20666 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20667 << E->getSourceRange();
20668 return ExprError();
20669 }
20670
20671 /// Rebuild an expression which simply semantically wraps another
20672 /// expression which it shares the type and value kind of.
20673 template <class T> ExprResult rebuildSugarExpr(T *E) {
20674 ExprResult SubResult = Visit(E->getSubExpr());
20675 if (SubResult.isInvalid()) return ExprError();
20676
20677 Expr *SubExpr = SubResult.get();
20678 E->setSubExpr(SubExpr);
20679 E->setType(SubExpr->getType());
20680 E->setValueKind(SubExpr->getValueKind());
20681 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20681, __extension__ __PRETTY_FUNCTION__
))
;
20682 return E;
20683 }
20684
20685 ExprResult VisitParenExpr(ParenExpr *E) {
20686 return rebuildSugarExpr(E);
20687 }
20688
20689 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20690 return rebuildSugarExpr(E);
20691 }
20692
20693 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20694 ExprResult SubResult = Visit(E->getSubExpr());
20695 if (SubResult.isInvalid()) return ExprError();
20696
20697 Expr *SubExpr = SubResult.get();
20698 E->setSubExpr(SubExpr);
20699 E->setType(S.Context.getPointerType(SubExpr->getType()));
20700 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20700, __extension__
__PRETTY_FUNCTION__))
;
20701 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20701, __extension__ __PRETTY_FUNCTION__
))
;
20702 return E;
20703 }
20704
20705 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20706 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20707
20708 E->setType(VD->getType());
20709
20710 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20710, __extension__
__PRETTY_FUNCTION__))
;
20711 if (S.getLangOpts().CPlusPlus &&
20712 !(isa<CXXMethodDecl>(VD) &&
20713 cast<CXXMethodDecl>(VD)->isInstance()))
20714 E->setValueKind(VK_LValue);
20715
20716 return E;
20717 }
20718
20719 ExprResult VisitMemberExpr(MemberExpr *E) {
20720 return resolveDecl(E, E->getMemberDecl());
20721 }
20722
20723 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20724 return resolveDecl(E, E->getDecl());
20725 }
20726 };
20727}
20728
20729/// Given a function expression of unknown-any type, try to rebuild it
20730/// to have a function type.
20731static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
20732 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20733 if (Result.isInvalid()) return ExprError();
20734 return S.DefaultFunctionArrayConversion(Result.get());
20735}
20736
20737namespace {
20738 /// A visitor for rebuilding an expression of type __unknown_anytype
20739 /// into one which resolves the type directly on the referring
20740 /// expression. Strict preservation of the original source
20741 /// structure is not a goal.
20742 struct RebuildUnknownAnyExpr
20743 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20744
20745 Sema &S;
20746
20747 /// The current destination type.
20748 QualType DestType;
20749
20750 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20751 : S(S), DestType(CastType) {}
20752
20753 ExprResult VisitStmt(Stmt *S) {
20754 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp"
, 20754)
;
20755 }
20756
20757 ExprResult VisitExpr(Expr *E) {
20758 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20759 << E->getSourceRange();
20760 return ExprError();
20761 }
20762
20763 ExprResult VisitCallExpr(CallExpr *E);
20764 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20765
20766 /// Rebuild an expression which simply semantically wraps another
20767 /// expression which it shares the type and value kind of.
20768 template <class T> ExprResult rebuildSugarExpr(T *E) {
20769 ExprResult SubResult = Visit(E->getSubExpr());
20770 if (SubResult.isInvalid()) return ExprError();
20771 Expr *SubExpr = SubResult.get();
20772 E->setSubExpr(SubExpr);
20773 E->setType(SubExpr->getType());
20774 E->setValueKind(SubExpr->getValueKind());
20775 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20775, __extension__ __PRETTY_FUNCTION__
))
;
20776 return E;
20777 }
20778
20779 ExprResult VisitParenExpr(ParenExpr *E) {
20780 return rebuildSugarExpr(E);
20781 }
20782
20783 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20784 return rebuildSugarExpr(E);
20785 }
20786
20787 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20788 const PointerType *Ptr = DestType->getAs<PointerType>();
20789 if (!Ptr) {
20790 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20791 << E->getSourceRange();
20792 return ExprError();
20793 }
20794
20795 if (isa<CallExpr>(E->getSubExpr())) {
20796 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20797 << E->getSourceRange();
20798 return ExprError();
20799 }
20800
20801 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20801, __extension__
__PRETTY_FUNCTION__))
;
20802 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20802, __extension__ __PRETTY_FUNCTION__
))
;
20803 E->setType(DestType);
20804
20805 // Build the sub-expression as if it were an object of the pointee type.
20806 DestType = Ptr->getPointeeType();
20807 ExprResult SubResult = Visit(E->getSubExpr());
20808 if (SubResult.isInvalid()) return ExprError();
20809 E->setSubExpr(SubResult.get());
20810 return E;
20811 }
20812
20813 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20814
20815 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20816
20817 ExprResult VisitMemberExpr(MemberExpr *E) {
20818 return resolveDecl(E, E->getMemberDecl());
20819 }
20820
20821 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20822 return resolveDecl(E, E->getDecl());
20823 }
20824 };
20825}
20826
20827/// Rebuilds a call expression which yielded __unknown_anytype.
20828ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20829 Expr *CalleeExpr = E->getCallee();
20830
20831 enum FnKind {
20832 FK_MemberFunction,
20833 FK_FunctionPointer,
20834 FK_BlockPointer
20835 };
20836
20837 FnKind Kind;
20838 QualType CalleeType = CalleeExpr->getType();
20839 if (CalleeType == S.Context.BoundMemberTy) {
20840 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))(static_cast <bool> (isa<CXXMemberCallExpr>(E) ||
isa<CXXOperatorCallExpr>(E)) ? void (0) : __assert_fail
("isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)"
, "clang/lib/Sema/SemaExpr.cpp", 20840, __extension__ __PRETTY_FUNCTION__
))
;
20841 Kind = FK_MemberFunction;
20842 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20843 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20844 CalleeType = Ptr->getPointeeType();
20845 Kind = FK_FunctionPointer;
20846 } else {
20847 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20848 Kind = FK_BlockPointer;
20849 }
20850 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20851
20852 // Verify that this is a legal result type of a function.
20853 if (DestType->isArrayType() || DestType->isFunctionType()) {
20854 unsigned diagID = diag::err_func_returning_array_function;
20855 if (Kind == FK_BlockPointer)
20856 diagID = diag::err_block_returning_array_function;
20857
20858 S.Diag(E->getExprLoc(), diagID)
20859 << DestType->isFunctionType() << DestType;
20860 return ExprError();
20861 }
20862
20863 // Otherwise, go ahead and set DestType as the call's result.
20864 E->setType(DestType.getNonLValueExprType(S.Context));
20865 E->setValueKind(Expr::getValueKindForType(DestType));
20866 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20866, __extension__ __PRETTY_FUNCTION__
))
;
20867
20868 // Rebuild the function type, replacing the result type with DestType.
20869 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20870 if (Proto) {
20871 // __unknown_anytype(...) is a special case used by the debugger when
20872 // it has no idea what a function's signature is.
20873 //
20874 // We want to build this call essentially under the K&R
20875 // unprototyped rules, but making a FunctionNoProtoType in C++
20876 // would foul up all sorts of assumptions. However, we cannot
20877 // simply pass all arguments as variadic arguments, nor can we
20878 // portably just call the function under a non-variadic type; see
20879 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20880 // However, it turns out that in practice it is generally safe to
20881 // call a function declared as "A foo(B,C,D);" under the prototype
20882 // "A foo(B,C,D,...);". The only known exception is with the
20883 // Windows ABI, where any variadic function is implicitly cdecl
20884 // regardless of its normal CC. Therefore we change the parameter
20885 // types to match the types of the arguments.
20886 //
20887 // This is a hack, but it is far superior to moving the
20888 // corresponding target-specific code from IR-gen to Sema/AST.
20889
20890 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20891 SmallVector<QualType, 8> ArgTypes;
20892 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20893 ArgTypes.reserve(E->getNumArgs());
20894 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20895 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20896 }
20897 ParamTypes = ArgTypes;
20898 }
20899 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20900 Proto->getExtProtoInfo());
20901 } else {
20902 DestType = S.Context.getFunctionNoProtoType(DestType,
20903 FnType->getExtInfo());
20904 }
20905
20906 // Rebuild the appropriate pointer-to-function type.
20907 switch (Kind) {
20908 case FK_MemberFunction:
20909 // Nothing to do.
20910 break;
20911
20912 case FK_FunctionPointer:
20913 DestType = S.Context.getPointerType(DestType);
20914 break;
20915
20916 case FK_BlockPointer:
20917 DestType = S.Context.getBlockPointerType(DestType);
20918 break;
20919 }
20920
20921 // Finally, we can recurse.
20922 ExprResult CalleeResult = Visit(CalleeExpr);
20923 if (!CalleeResult.isUsable()) return ExprError();
20924 E->setCallee(CalleeResult.get());
20925
20926 // Bind a temporary if necessary.
20927 return S.MaybeBindToTemporary(E);
20928}
20929
20930ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20931 // Verify that this is a legal result type of a call.
20932 if (DestType->isArrayType() || DestType->isFunctionType()) {
20933 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20934 << DestType->isFunctionType() << DestType;
20935 return ExprError();
20936 }
20937
20938 // Rewrite the method result type if available.
20939 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20940 assert(Method->getReturnType() == S.Context.UnknownAnyTy)(static_cast <bool> (Method->getReturnType() == S.Context
.UnknownAnyTy) ? void (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy"
, "clang/lib/Sema/SemaExpr.cpp", 20940, __extension__ __PRETTY_FUNCTION__
))
;
20941 Method->setReturnType(DestType);
20942 }
20943
20944 // Change the type of the message.
20945 E->setType(DestType.getNonReferenceType());
20946 E->setValueKind(Expr::getValueKindForType(DestType));
20947
20948 return S.MaybeBindToTemporary(E);
20949}
20950
20951ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20952 // The only case we should ever see here is a function-to-pointer decay.
20953 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20954 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20954, __extension__
__PRETTY_FUNCTION__))
;
20955 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20955, __extension__ __PRETTY_FUNCTION__
))
;
20956
20957 E->setType(DestType);
20958
20959 // Rebuild the sub-expression as the pointee (function) type.
20960 DestType = DestType->castAs<PointerType>()->getPointeeType();
20961
20962 ExprResult Result = Visit(E->getSubExpr());
20963 if (!Result.isUsable()) return ExprError();
20964
20965 E->setSubExpr(Result.get());
20966 return E;
20967 } else if (E->getCastKind() == CK_LValueToRValue) {
20968 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20968, __extension__
__PRETTY_FUNCTION__))
;
20969 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20969, __extension__ __PRETTY_FUNCTION__
))
;
20970
20971 assert(isa<BlockPointerType>(E->getType()))(static_cast <bool> (isa<BlockPointerType>(E->
getType())) ? void (0) : __assert_fail ("isa<BlockPointerType>(E->getType())"
, "clang/lib/Sema/SemaExpr.cpp", 20971, __extension__ __PRETTY_FUNCTION__
))
;
20972
20973 E->setType(DestType);
20974
20975 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20976 DestType = S.Context.getLValueReferenceType(DestType);
20977
20978 ExprResult Result = Visit(E->getSubExpr());
20979 if (!Result.isUsable()) return ExprError();
20980
20981 E->setSubExpr(Result.get());
20982 return E;
20983 } else {
20984 llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "clang/lib/Sema/SemaExpr.cpp"
, 20984)
;
20985 }
20986}
20987
20988ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20989 ExprValueKind ValueKind = VK_LValue;
20990 QualType Type = DestType;
20991
20992 // We know how to make this work for certain kinds of decls:
20993
20994 // - functions
20995 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20996 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20997 DestType = Ptr->getPointeeType();
20998 ExprResult Result = resolveDecl(E, VD);
20999 if (Result.isInvalid()) return ExprError();
21000 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21001 VK_PRValue);
21002 }
21003
21004 if (!Type->isFunctionType()) {
21005 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21006 << VD << E->getSourceRange();
21007 return ExprError();
21008 }
21009 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21010 // We must match the FunctionDecl's type to the hack introduced in
21011 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21012 // type. See the lengthy commentary in that routine.
21013 QualType FDT = FD->getType();
21014 const FunctionType *FnType = FDT->castAs<FunctionType>();
21015 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21016 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21017 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21018 SourceLocation Loc = FD->getLocation();
21019 FunctionDecl *NewFD = FunctionDecl::Create(
21020 S.Context, FD->getDeclContext(), Loc, Loc,
21021 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21022 SC_None, S.getCurFPFeatures().isFPConstrained(),
21023 false /*isInlineSpecified*/, FD->hasPrototype(),
21024 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21025
21026 if (FD->getQualifier())
21027 NewFD->setQualifierInfo(FD->getQualifierLoc());
21028
21029 SmallVector<ParmVarDecl*, 16> Params;
21030 for (const auto &AI : FT->param_types()) {
21031 ParmVarDecl *Param =
21032 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21033 Param->setScopeInfo(0, Params.size());
21034 Params.push_back(Param);
21035 }
21036 NewFD->setParams(Params);
21037 DRE->setDecl(NewFD);
21038 VD = DRE->getDecl();
21039 }
21040 }
21041
21042 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21043 if (MD->isInstance()) {
21044 ValueKind = VK_PRValue;
21045 Type = S.Context.BoundMemberTy;
21046 }
21047
21048 // Function references aren't l-values in C.
21049 if (!S.getLangOpts().CPlusPlus)
21050 ValueKind = VK_PRValue;
21051
21052 // - variables
21053 } else if (isa<VarDecl>(VD)) {
21054 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21055 Type = RefTy->getPointeeType();
21056 } else if (Type->isFunctionType()) {
21057 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21058 << VD << E->getSourceRange();
21059 return ExprError();
21060 }
21061
21062 // - nothing else
21063 } else {
21064 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21065 << VD << E->getSourceRange();
21066 return ExprError();
21067 }
21068
21069 // Modifying the declaration like this is friendly to IR-gen but
21070 // also really dangerous.
21071 VD->setType(DestType);
21072 E->setType(Type);
21073 E->setValueKind(ValueKind);
21074 return E;
21075}
21076
21077/// Check a cast of an unknown-any type. We intentionally only
21078/// trigger this for C-style casts.
21079ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21080 Expr *CastExpr, CastKind &CastKind,
21081 ExprValueKind &VK, CXXCastPath &Path) {
21082 // The type we're casting to must be either void or complete.
21083 if (!CastType->isVoidType() &&
21084 RequireCompleteType(TypeRange.getBegin(), CastType,
21085 diag::err_typecheck_cast_to_incomplete))
21086 return ExprError();
21087
21088 // Rewrite the casted expression from scratch.
21089 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21090 if (!result.isUsable()) return ExprError();
21091
21092 CastExpr = result.get();
21093 VK = CastExpr->getValueKind();
21094 CastKind = CK_NoOp;
21095
21096 return CastExpr;
21097}
21098
21099ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21100 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21101}
21102
21103ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21104 Expr *arg, QualType &paramType) {
21105 // If the syntactic form of the argument is not an explicit cast of
21106 // any sort, just do default argument promotion.
21107 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21108 if (!castArg) {
21109 ExprResult result = DefaultArgumentPromotion(arg);
21110 if (result.isInvalid()) return ExprError();
21111 paramType = result.get()->getType();
21112 return result;
21113 }
21114
21115 // Otherwise, use the type that was written in the explicit cast.
21116 assert(!arg->hasPlaceholderType())(static_cast <bool> (!arg->hasPlaceholderType()) ? void
(0) : __assert_fail ("!arg->hasPlaceholderType()", "clang/lib/Sema/SemaExpr.cpp"
, 21116, __extension__ __PRETTY_FUNCTION__))
;
21117 paramType = castArg->getTypeAsWritten();
21118
21119 // Copy-initialize a parameter of that type.
21120 InitializedEntity entity =
21121 InitializedEntity::InitializeParameter(Context, paramType,
21122 /*consumed*/ false);
21123 return PerformCopyInitialization(entity, callLoc, arg);
21124}
21125
21126static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21127 Expr *orig = E;
21128 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21129 while (true) {
21130 E = E->IgnoreParenImpCasts();
21131 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21132 E = call->getCallee();
21133 diagID = diag::err_uncasted_call_of_unknown_any;
21134 } else {
21135 break;
21136 }
21137 }
21138
21139 SourceLocation loc;
21140 NamedDecl *d;
21141 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21142 loc = ref->getLocation();
21143 d = ref->getDecl();
21144 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21145 loc = mem->getMemberLoc();
21146 d = mem->getMemberDecl();
21147 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21148 diagID = diag::err_uncasted_call_of_unknown_any;
21149 loc = msg->getSelectorStartLoc();
21150 d = msg->getMethodDecl();
21151 if (!d) {
21152 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21153 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21154 << orig->getSourceRange();
21155 return ExprError();
21156 }
21157 } else {
21158 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21159 << E->getSourceRange();
21160 return ExprError();
21161 }
21162
21163 S.Diag(loc, diagID) << d << orig->getSourceRange();
21164
21165 // Never recoverable.
21166 return ExprError();
21167}
21168
21169/// Check for operands with placeholder types and complain if found.
21170/// Returns ExprError() if there was an error and no recovery was possible.
21171ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21172 if (!Context.isDependenceAllowed()) {
21173 // C cannot handle TypoExpr nodes on either side of a binop because it
21174 // doesn't handle dependent types properly, so make sure any TypoExprs have
21175 // been dealt with before checking the operands.
21176 ExprResult Result = CorrectDelayedTyposInExpr(E);
21177 if (!Result.isUsable()) return ExprError();
21178 E = Result.get();
21179 }
21180
21181 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21182 if (!placeholderType) return E;
21183
21184 switch (placeholderType->getKind()) {
21185
21186 // Overloaded expressions.
21187 case BuiltinType::Overload: {
21188 // Try to resolve a single function template specialization.
21189 // This is obligatory.
21190 ExprResult Result = E;
21191 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
21192 return Result;
21193
21194 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21195 // leaves Result unchanged on failure.
21196 Result = E;
21197 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
21198 return Result;
21199
21200 // If that failed, try to recover with a call.
21201 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21202 /*complain*/ true);
21203 return Result;
21204 }
21205
21206 // Bound member functions.
21207 case BuiltinType::BoundMember: {
21208 ExprResult result = E;
21209 const Expr *BME = E->IgnoreParens();
21210 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21211 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21212 if (isa<CXXPseudoDestructorExpr>(BME)) {
21213 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21214 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21215 if (ME->getMemberNameInfo().getName().getNameKind() ==
21216 DeclarationName::CXXDestructorName)
21217 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21218 }
21219 tryToRecoverWithCall(result, PD,
21220 /*complain*/ true);
21221 return result;
21222 }
21223
21224 // ARC unbridged casts.
21225 case BuiltinType::ARCUnbridgedCast: {
21226 Expr *realCast = stripARCUnbridgedCast(E);
21227 diagnoseARCUnbridgedCast(realCast);
21228 return realCast;
21229 }
21230
21231 // Expressions of unknown type.
21232 case BuiltinType::UnknownAny:
21233 return diagnoseUnknownAnyExpr(*this, E);
21234
21235 // Pseudo-objects.
21236 case BuiltinType::PseudoObject:
21237 return checkPseudoObjectRValue(E);
21238
21239 case BuiltinType::BuiltinFn: {
21240 // Accept __noop without parens by implicitly converting it to a call expr.
21241 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21242 if (DRE) {
21243 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21244 unsigned BuiltinID = FD->getBuiltinID();
21245 if (BuiltinID == Builtin::BI__noop) {
21246 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21247 CK_BuiltinFnToFnPtr)
21248 .get();
21249 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21250 VK_PRValue, SourceLocation(),
21251 FPOptionsOverride());
21252 }
21253
21254 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21255 // Any use of these other than a direct call is ill-formed as of C++20,
21256 // because they are not addressable functions. In earlier language
21257 // modes, warn and force an instantiation of the real body.
21258 Diag(E->getBeginLoc(),
21259 getLangOpts().CPlusPlus20
21260 ? diag::err_use_of_unaddressable_function
21261 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21262 if (FD->isImplicitlyInstantiable()) {
21263 // Require a definition here because a normal attempt at
21264 // instantiation for a builtin will be ignored, and we won't try
21265 // again later. We assume that the definition of the template
21266 // precedes this use.
21267 InstantiateFunctionDefinition(E->getBeginLoc(), FD,
21268 /*Recursive=*/false,
21269 /*DefinitionRequired=*/true,
21270 /*AtEndOfTU=*/false);
21271 }
21272 // Produce a properly-typed reference to the function.
21273 CXXScopeSpec SS;
21274 SS.Adopt(DRE->getQualifierLoc());
21275 TemplateArgumentListInfo TemplateArgs;
21276 DRE->copyTemplateArgumentsInto(TemplateArgs);
21277 return BuildDeclRefExpr(
21278 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21279 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21280 DRE->getTemplateKeywordLoc(),
21281 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21282 }
21283 }
21284
21285 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21286 return ExprError();
21287 }
21288
21289 case BuiltinType::IncompleteMatrixIdx:
21290 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21291 ->getRowIdx()
21292 ->getBeginLoc(),
21293 diag::err_matrix_incomplete_index);
21294 return ExprError();
21295
21296 // Expressions of unknown type.
21297 case BuiltinType::OMPArraySection:
21298 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
21299 return ExprError();
21300
21301 // Expressions of unknown type.
21302 case BuiltinType::OMPArrayShaping:
21303 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21304
21305 case BuiltinType::OMPIterator:
21306 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21307
21308 // Everything else should be impossible.
21309#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21310 case BuiltinType::Id:
21311#include "clang/Basic/OpenCLImageTypes.def"
21312#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21313 case BuiltinType::Id:
21314#include "clang/Basic/OpenCLExtensionTypes.def"
21315#define SVE_TYPE(Name, Id, SingletonId) \
21316 case BuiltinType::Id:
21317#include "clang/Basic/AArch64SVEACLETypes.def"
21318#define PPC_VECTOR_TYPE(Name, Id, Size) \
21319 case BuiltinType::Id:
21320#include "clang/Basic/PPCTypes.def"
21321#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21322#include "clang/Basic/RISCVVTypes.def"
21323#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21324#include "clang/Basic/WebAssemblyReferenceTypes.def"
21325#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21326#define PLACEHOLDER_TYPE(Id, SingletonId)
21327#include "clang/AST/BuiltinTypes.def"
21328 break;
21329 }
21330
21331 llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!"
, "clang/lib/Sema/SemaExpr.cpp", 21331)
;
21332}
21333
21334bool Sema::CheckCaseExpression(Expr *E) {
21335 if (E->isTypeDependent())
21336 return true;
21337 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
21338 return E->getType()->isIntegralOrEnumerationType();
21339 return false;
21340}
21341
21342/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21343ExprResult
21344Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
21345 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(static_cast <bool> ((Kind == tok::kw___objc_yes || Kind
== tok::kw___objc_no) && "Unknown Objective-C Boolean value!"
) ? void (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\""
, "clang/lib/Sema/SemaExpr.cpp", 21346, __extension__ __PRETTY_FUNCTION__
))
21346 "Unknown Objective-C Boolean value!")(static_cast <bool> ((Kind == tok::kw___objc_yes || Kind
== tok::kw___objc_no) && "Unknown Objective-C Boolean value!"
) ? void (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\""
, "clang/lib/Sema/SemaExpr.cpp", 21346, __extension__ __PRETTY_FUNCTION__
))
;
21347 QualType BoolT = Context.ObjCBuiltinBoolTy;
21348 if (!Context.getBOOLDecl()) {
21349 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
21350 Sema::LookupOrdinaryName);
21351 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
21352 NamedDecl *ND = Result.getFoundDecl();
21353 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
21354 Context.setBOOLDecl(TD);
21355 }
21356 }
21357 if (Context.getBOOLDecl())
21358 BoolT = Context.getBOOLType();
21359 return new (Context)
21360 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
21361}
21362
21363ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
21364 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
21365 SourceLocation RParen) {
21366 auto FindSpecVersion =
21367 [&](StringRef Platform) -> std::optional<VersionTuple> {
21368 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21369 return Spec.getPlatform() == Platform;
21370 });
21371 // Transcribe the "ios" availability check to "maccatalyst" when compiling
21372 // for "maccatalyst" if "maccatalyst" is not specified.
21373 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
21374 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21375 return Spec.getPlatform() == "ios";
21376 });
21377 }
21378 if (Spec == AvailSpecs.end())
21379 return std::nullopt;
21380 return Spec->getVersion();
21381 };
21382
21383 VersionTuple Version;
21384 if (auto MaybeVersion =
21385 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
21386 Version = *MaybeVersion;
21387
21388 // The use of `@available` in the enclosing context should be analyzed to
21389 // warn when it's used inappropriately (i.e. not if(@available)).
21390 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
21391 Context->HasPotentialAvailabilityViolations = true;
21392
21393 return new (Context)
21394 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
21395}
21396
21397ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
21398 ArrayRef<Expr *> SubExprs, QualType T) {
21399 if (!Context.getLangOpts().RecoveryAST)
21400 return ExprError();
21401
21402 if (isSFINAEContext())
21403 return ExprError();
21404
21405 if (T.isNull() || T->isUndeducedType() ||
21406 !Context.getLangOpts().RecoveryASTType)
21407 // We don't know the concrete type, fallback to dependent type.
21408 T = Context.DependentTy;
21409
21410 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21411}

/build/source/clang/lib/Sema/TreeTransform.h

1//===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
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// This file implements a semantic tree transformation that takes a given
9// AST and rebuilds it, possibly transforming some nodes in the process.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
14#define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15
16#include "CoroutineStmtBuilder.h"
17#include "TypeLocBuilder.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprConcepts.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExprOpenMP.h"
26#include "clang/AST/OpenMPClause.h"
27#include "clang/AST/Stmt.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/AST/StmtObjC.h"
30#include "clang/AST/StmtOpenMP.h"
31#include "clang/Basic/DiagnosticParse.h"
32#include "clang/Basic/OpenMPKinds.h"
33#include "clang/Sema/Designator.h"
34#include "clang/Sema/EnterExpressionEvaluationContext.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/Ownership.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaDiagnostic.h"
40#include "clang/Sema/SemaInternal.h"
41#include "llvm/ADT/ArrayRef.h"
42#include "llvm/Support/ErrorHandling.h"
43#include <algorithm>
44#include <optional>
45
46using namespace llvm::omp;
47
48namespace clang {
49using namespace sema;
50
51/// A semantic tree transformation that allows one to transform one
52/// abstract syntax tree into another.
53///
54/// A new tree transformation is defined by creating a new subclass \c X of
55/// \c TreeTransform<X> and then overriding certain operations to provide
56/// behavior specific to that transformation. For example, template
57/// instantiation is implemented as a tree transformation where the
58/// transformation of TemplateTypeParmType nodes involves substituting the
59/// template arguments for their corresponding template parameters; a similar
60/// transformation is performed for non-type template parameters and
61/// template template parameters.
62///
63/// This tree-transformation template uses static polymorphism to allow
64/// subclasses to customize any of its operations. Thus, a subclass can
65/// override any of the transformation or rebuild operators by providing an
66/// operation with the same signature as the default implementation. The
67/// overriding function should not be virtual.
68///
69/// Semantic tree transformations are split into two stages, either of which
70/// can be replaced by a subclass. The "transform" step transforms an AST node
71/// or the parts of an AST node using the various transformation functions,
72/// then passes the pieces on to the "rebuild" step, which constructs a new AST
73/// node of the appropriate kind from the pieces. The default transformation
74/// routines recursively transform the operands to composite AST nodes (e.g.,
75/// the pointee type of a PointerType node) and, if any of those operand nodes
76/// were changed by the transformation, invokes the rebuild operation to create
77/// a new AST node.
78///
79/// Subclasses can customize the transformation at various levels. The
80/// most coarse-grained transformations involve replacing TransformType(),
81/// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
82/// TransformTemplateName(), or TransformTemplateArgument() with entirely
83/// new implementations.
84///
85/// For more fine-grained transformations, subclasses can replace any of the
86/// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
87/// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
88/// replacing TransformTemplateTypeParmType() allows template instantiation
89/// to substitute template arguments for their corresponding template
90/// parameters. Additionally, subclasses can override the \c RebuildXXX
91/// functions to control how AST nodes are rebuilt when their operands change.
92/// By default, \c TreeTransform will invoke semantic analysis to rebuild
93/// AST nodes. However, certain other tree transformations (e.g, cloning) may
94/// be able to use more efficient rebuild steps.
95///
96/// There are a handful of other functions that can be overridden, allowing one
97/// to avoid traversing nodes that don't need any transformation
98/// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
99/// operands have not changed (\c AlwaysRebuild()), and customize the
100/// default locations and entity names used for type-checking
101/// (\c getBaseLocation(), \c getBaseEntity()).
102template<typename Derived>
103class TreeTransform {
104 /// Private RAII object that helps us forget and then re-remember
105 /// the template argument corresponding to a partially-substituted parameter
106 /// pack.
107 class ForgetPartiallySubstitutedPackRAII {
108 Derived &Self;
109 TemplateArgument Old;
110
111 public:
112 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
113 Old = Self.ForgetPartiallySubstitutedPack();
114 }
115
116 ~ForgetPartiallySubstitutedPackRAII() {
117 Self.RememberPartiallySubstitutedPack(Old);
118 }
119 };
120
121protected:
122 Sema &SemaRef;
123
124 /// The set of local declarations that have been transformed, for
125 /// cases where we are forced to build new declarations within the transformer
126 /// rather than in the subclass (e.g., lambda closure types).
127 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
128
129public:
130 /// Initializes a new tree transformer.
131 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
132
133 /// Retrieves a reference to the derived class.
134 Derived &getDerived() { return static_cast<Derived&>(*this); }
135
136 /// Retrieves a reference to the derived class.
137 const Derived &getDerived() const {
138 return static_cast<const Derived&>(*this);
139 }
140
141 static inline ExprResult Owned(Expr *E) { return E; }
142 static inline StmtResult Owned(Stmt *S) { return S; }
143
144 /// Retrieves a reference to the semantic analysis object used for
145 /// this tree transform.
146 Sema &getSema() const { return SemaRef; }
147
148 /// Whether the transformation should always rebuild AST nodes, even
149 /// if none of the children have changed.
150 ///
151 /// Subclasses may override this function to specify when the transformation
152 /// should rebuild all AST nodes.
153 ///
154 /// We must always rebuild all AST nodes when performing variadic template
155 /// pack expansion, in order to avoid violating the AST invariant that each
156 /// statement node appears at most once in its containing declaration.
157 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
158
159 /// Whether the transformation is forming an expression or statement that
160 /// replaces the original. In this case, we'll reuse mangling numbers from
161 /// existing lambdas.
162 bool ReplacingOriginal() { return false; }
163
164 /// Wether CXXConstructExpr can be skipped when they are implicit.
165 /// They will be reconstructed when used if needed.
166 /// This is useful when the user that cause rebuilding of the
167 /// CXXConstructExpr is outside of the expression at which the TreeTransform
168 /// started.
169 bool AllowSkippingCXXConstructExpr() { return true; }
170
171 /// Returns the location of the entity being transformed, if that
172 /// information was not available elsewhere in the AST.
173 ///
174 /// By default, returns no source-location information. Subclasses can
175 /// provide an alternative implementation that provides better location
176 /// information.
177 SourceLocation getBaseLocation() { return SourceLocation(); }
178
179 /// Returns the name of the entity being transformed, if that
180 /// information was not available elsewhere in the AST.
181 ///
182 /// By default, returns an empty name. Subclasses can provide an alternative
183 /// implementation with a more precise name.
184 DeclarationName getBaseEntity() { return DeclarationName(); }
185
186 /// Sets the "base" location and entity when that
187 /// information is known based on another transformation.
188 ///
189 /// By default, the source location and entity are ignored. Subclasses can
190 /// override this function to provide a customized implementation.
191 void setBase(SourceLocation Loc, DeclarationName Entity) { }
192
193 /// RAII object that temporarily sets the base location and entity
194 /// used for reporting diagnostics in types.
195 class TemporaryBase {
196 TreeTransform &Self;
197 SourceLocation OldLocation;
198 DeclarationName OldEntity;
199
200 public:
201 TemporaryBase(TreeTransform &Self, SourceLocation Location,
202 DeclarationName Entity) : Self(Self) {
203 OldLocation = Self.getDerived().getBaseLocation();
204 OldEntity = Self.getDerived().getBaseEntity();
205
206 if (Location.isValid())
207 Self.getDerived().setBase(Location, Entity);
208 }
209
210 ~TemporaryBase() {
211 Self.getDerived().setBase(OldLocation, OldEntity);
212 }
213 };
214
215 /// Determine whether the given type \p T has already been
216 /// transformed.
217 ///
218 /// Subclasses can provide an alternative implementation of this routine
219 /// to short-circuit evaluation when it is known that a given type will
220 /// not change. For example, template instantiation need not traverse
221 /// non-dependent types.
222 bool AlreadyTransformed(QualType T) {
223 return T.isNull();
224 }
225
226 /// Transform a template parameter depth level.
227 ///
228 /// During a transformation that transforms template parameters, this maps
229 /// an old template parameter depth to a new depth.
230 unsigned TransformTemplateDepth(unsigned Depth) {
231 return Depth;
232 }
233
234 /// Determine whether the given call argument should be dropped, e.g.,
235 /// because it is a default argument.
236 ///
237 /// Subclasses can provide an alternative implementation of this routine to
238 /// determine which kinds of call arguments get dropped. By default,
239 /// CXXDefaultArgument nodes are dropped (prior to transformation).
240 bool DropCallArgument(Expr *E) {
241 return E->isDefaultArgument();
242 }
243
244 /// Determine whether we should expand a pack expansion with the
245 /// given set of parameter packs into separate arguments by repeatedly
246 /// transforming the pattern.
247 ///
248 /// By default, the transformer never tries to expand pack expansions.
249 /// Subclasses can override this routine to provide different behavior.
250 ///
251 /// \param EllipsisLoc The location of the ellipsis that identifies the
252 /// pack expansion.
253 ///
254 /// \param PatternRange The source range that covers the entire pattern of
255 /// the pack expansion.
256 ///
257 /// \param Unexpanded The set of unexpanded parameter packs within the
258 /// pattern.
259 ///
260 /// \param ShouldExpand Will be set to \c true if the transformer should
261 /// expand the corresponding pack expansions into separate arguments. When
262 /// set, \c NumExpansions must also be set.
263 ///
264 /// \param RetainExpansion Whether the caller should add an unexpanded
265 /// pack expansion after all of the expanded arguments. This is used
266 /// when extending explicitly-specified template argument packs per
267 /// C++0x [temp.arg.explicit]p9.
268 ///
269 /// \param NumExpansions The number of separate arguments that will be in
270 /// the expanded form of the corresponding pack expansion. This is both an
271 /// input and an output parameter, which can be set by the caller if the
272 /// number of expansions is known a priori (e.g., due to a prior substitution)
273 /// and will be set by the callee when the number of expansions is known.
274 /// The callee must set this value when \c ShouldExpand is \c true; it may
275 /// set this value in other cases.
276 ///
277 /// \returns true if an error occurred (e.g., because the parameter packs
278 /// are to be instantiated with arguments of different lengths), false
279 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
280 /// must be set.
281 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
282 SourceRange PatternRange,
283 ArrayRef<UnexpandedParameterPack> Unexpanded,
284 bool &ShouldExpand, bool &RetainExpansion,
285 std::optional<unsigned> &NumExpansions) {
286 ShouldExpand = false;
287 return false;
288 }
289
290 /// "Forget" about the partially-substituted pack template argument,
291 /// when performing an instantiation that must preserve the parameter pack
292 /// use.
293 ///
294 /// This routine is meant to be overridden by the template instantiator.
295 TemplateArgument ForgetPartiallySubstitutedPack() {
296 return TemplateArgument();
297 }
298
299 /// "Remember" the partially-substituted pack template argument
300 /// after performing an instantiation that must preserve the parameter pack
301 /// use.
302 ///
303 /// This routine is meant to be overridden by the template instantiator.
304 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
305
306 /// Note to the derived class when a function parameter pack is
307 /// being expanded.
308 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
309
310 /// Transforms the given type into another type.
311 ///
312 /// By default, this routine transforms a type by creating a
313 /// TypeSourceInfo for it and delegating to the appropriate
314 /// function. This is expensive, but we don't mind, because
315 /// this method is deprecated anyway; all users should be
316 /// switched to storing TypeSourceInfos.
317 ///
318 /// \returns the transformed type.
319 QualType TransformType(QualType T);
320
321 /// Transforms the given type-with-location into a new
322 /// type-with-location.
323 ///
324 /// By default, this routine transforms a type by delegating to the
325 /// appropriate TransformXXXType to build a new type. Subclasses
326 /// may override this function (to take over all type
327 /// transformations) or some set of the TransformXXXType functions
328 /// to alter the transformation.
329 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
330
331 /// Transform the given type-with-location into a new
332 /// type, collecting location information in the given builder
333 /// as necessary.
334 ///
335 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
336
337 /// Transform a type that is permitted to produce a
338 /// DeducedTemplateSpecializationType.
339 ///
340 /// This is used in the (relatively rare) contexts where it is acceptable
341 /// for transformation to produce a class template type with deduced
342 /// template arguments.
343 /// @{
344 QualType TransformTypeWithDeducedTST(QualType T);
345 TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
346 /// @}
347
348 /// The reason why the value of a statement is not discarded, if any.
349 enum StmtDiscardKind {
350 SDK_Discarded,
351 SDK_NotDiscarded,
352 SDK_StmtExprResult,
353 };
354
355 /// Transform the given statement.
356 ///
357 /// By default, this routine transforms a statement by delegating to the
358 /// appropriate TransformXXXStmt function to transform a specific kind of
359 /// statement or the TransformExpr() function to transform an expression.
360 /// Subclasses may override this function to transform statements using some
361 /// other mechanism.
362 ///
363 /// \returns the transformed statement.
364 StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
365
366 /// Transform the given statement.
367 ///
368 /// By default, this routine transforms a statement by delegating to the
369 /// appropriate TransformOMPXXXClause function to transform a specific kind
370 /// of clause. Subclasses may override this function to transform statements
371 /// using some other mechanism.
372 ///
373 /// \returns the transformed OpenMP clause.
374 OMPClause *TransformOMPClause(OMPClause *S);
375
376 /// Transform the given attribute.
377 ///
378 /// By default, this routine transforms a statement by delegating to the
379 /// appropriate TransformXXXAttr function to transform a specific kind
380 /// of attribute. Subclasses may override this function to transform
381 /// attributed statements/types using some other mechanism.
382 ///
383 /// \returns the transformed attribute
384 const Attr *TransformAttr(const Attr *S);
385
386 // Transform the given statement attribute.
387 //
388 // Delegates to the appropriate TransformXXXAttr function to transform a
389 // specific kind of statement attribute. Unlike the non-statement taking
390 // version of this, this implements all attributes, not just pragmas.
391 const Attr *TransformStmtAttr(const Stmt *OrigS, const Stmt *InstS,
392 const Attr *A);
393
394 // Transform the specified attribute.
395 //
396 // Subclasses should override the transformation of attributes with a pragma
397 // spelling to transform expressions stored within the attribute.
398 //
399 // \returns the transformed attribute.
400#define ATTR(X) \
401 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
402#include "clang/Basic/AttrList.inc"
403
404 // Transform the specified attribute.
405 //
406 // Subclasses should override the transformation of attributes to do
407 // transformation and checking of statement attributes. By default, this
408 // delegates to the non-statement taking version.
409 //
410 // \returns the transformed attribute.
411#define ATTR(X) \
412 const X##Attr *TransformStmt##X##Attr(const Stmt *, const Stmt *, \
413 const X##Attr *A) { \
414 return getDerived().Transform##X##Attr(A); \
415 }
416#include "clang/Basic/AttrList.inc"
417
418 /// Transform the given expression.
419 ///
420 /// By default, this routine transforms an expression by delegating to the
421 /// appropriate TransformXXXExpr function to build a new expression.
422 /// Subclasses may override this function to transform expressions using some
423 /// other mechanism.
424 ///
425 /// \returns the transformed expression.
426 ExprResult TransformExpr(Expr *E);
427
428 /// Transform the given initializer.
429 ///
430 /// By default, this routine transforms an initializer by stripping off the
431 /// semantic nodes added by initialization, then passing the result to
432 /// TransformExpr or TransformExprs.
433 ///
434 /// \returns the transformed initializer.
435 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
436
437 /// Transform the given list of expressions.
438 ///
439 /// This routine transforms a list of expressions by invoking
440 /// \c TransformExpr() for each subexpression. However, it also provides
441 /// support for variadic templates by expanding any pack expansions (if the
442 /// derived class permits such expansion) along the way. When pack expansions
443 /// are present, the number of outputs may not equal the number of inputs.
444 ///
445 /// \param Inputs The set of expressions to be transformed.
446 ///
447 /// \param NumInputs The number of expressions in \c Inputs.
448 ///
449 /// \param IsCall If \c true, then this transform is being performed on
450 /// function-call arguments, and any arguments that should be dropped, will
451 /// be.
452 ///
453 /// \param Outputs The transformed input expressions will be added to this
454 /// vector.
455 ///
456 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
457 /// due to transformation.
458 ///
459 /// \returns true if an error occurred, false otherwise.
460 bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
461 SmallVectorImpl<Expr *> &Outputs,
462 bool *ArgChanged = nullptr);
463
464 /// Transform the given declaration, which is referenced from a type
465 /// or expression.
466 ///
467 /// By default, acts as the identity function on declarations, unless the
468 /// transformer has had to transform the declaration itself. Subclasses
469 /// may override this function to provide alternate behavior.
470 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
471 llvm::DenseMap<Decl *, Decl *>::iterator Known
472 = TransformedLocalDecls.find(D);
473 if (Known != TransformedLocalDecls.end())
474 return Known->second;
475
476 return D;
477 }
478
479 /// Transform the specified condition.
480 ///
481 /// By default, this transforms the variable and expression and rebuilds
482 /// the condition.
483 Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
484 Expr *Expr,
485 Sema::ConditionKind Kind);
486
487 /// Transform the attributes associated with the given declaration and
488 /// place them on the new declaration.
489 ///
490 /// By default, this operation does nothing. Subclasses may override this
491 /// behavior to transform attributes.
492 void transformAttrs(Decl *Old, Decl *New) { }
493
494 /// Note that a local declaration has been transformed by this
495 /// transformer.
496 ///
497 /// Local declarations are typically transformed via a call to
498 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
499 /// the transformer itself has to transform the declarations. This routine
500 /// can be overridden by a subclass that keeps track of such mappings.
501 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
502 assert(New.size() == 1 &&(static_cast <bool> (New.size() == 1 && "must override transformedLocalDecl if performing pack expansion"
) ? void (0) : __assert_fail ("New.size() == 1 && \"must override transformedLocalDecl if performing pack expansion\""
, "clang/lib/Sema/TreeTransform.h", 503, __extension__ __PRETTY_FUNCTION__
))
503 "must override transformedLocalDecl if performing pack expansion")(static_cast <bool> (New.size() == 1 && "must override transformedLocalDecl if performing pack expansion"
) ? void (0) : __assert_fail ("New.size() == 1 && \"must override transformedLocalDecl if performing pack expansion\""
, "clang/lib/Sema/TreeTransform.h", 503, __extension__ __PRETTY_FUNCTION__
))
;
504 TransformedLocalDecls[Old] = New.front();
505 }
506
507 /// Transform the definition of the given declaration.
508 ///
509 /// By default, invokes TransformDecl() to transform the declaration.
510 /// Subclasses may override this function to provide alternate behavior.
511 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
512 return getDerived().TransformDecl(Loc, D);
513 }
514
515 /// Transform the given declaration, which was the first part of a
516 /// nested-name-specifier in a member access expression.
517 ///
518 /// This specific declaration transformation only applies to the first
519 /// identifier in a nested-name-specifier of a member access expression, e.g.,
520 /// the \c T in \c x->T::member
521 ///
522 /// By default, invokes TransformDecl() to transform the declaration.
523 /// Subclasses may override this function to provide alternate behavior.
524 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
525 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
526 }
527
528 /// Transform the set of declarations in an OverloadExpr.
529 bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
530 LookupResult &R);
531
532 /// Transform the given nested-name-specifier with source-location
533 /// information.
534 ///
535 /// By default, transforms all of the types and declarations within the
536 /// nested-name-specifier. Subclasses may override this function to provide
537 /// alternate behavior.
538 NestedNameSpecifierLoc
539 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
540 QualType ObjectType = QualType(),
541 NamedDecl *FirstQualifierInScope = nullptr);
542
543 /// Transform the given declaration name.
544 ///
545 /// By default, transforms the types of conversion function, constructor,
546 /// and destructor names and then (if needed) rebuilds the declaration name.
547 /// Identifiers and selectors are returned unmodified. Subclasses may
548 /// override this function to provide alternate behavior.
549 DeclarationNameInfo
550 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
551
552 bool TransformRequiresExprRequirements(ArrayRef<concepts::Requirement *> Reqs,
553 llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
554 concepts::TypeRequirement *
555 TransformTypeRequirement(concepts::TypeRequirement *Req);
556 concepts::ExprRequirement *
557 TransformExprRequirement(concepts::ExprRequirement *Req);
558 concepts::NestedRequirement *
559 TransformNestedRequirement(concepts::NestedRequirement *Req);
560
561 /// Transform the given template name.
562 ///
563 /// \param SS The nested-name-specifier that qualifies the template
564 /// name. This nested-name-specifier must already have been transformed.
565 ///
566 /// \param Name The template name to transform.
567 ///
568 /// \param NameLoc The source location of the template name.
569 ///
570 /// \param ObjectType If we're translating a template name within a member
571 /// access expression, this is the type of the object whose member template
572 /// is being referenced.
573 ///
574 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
575 /// also refers to a name within the current (lexical) scope, this is the
576 /// declaration it refers to.
577 ///
578 /// By default, transforms the template name by transforming the declarations
579 /// and nested-name-specifiers that occur within the template name.
580 /// Subclasses may override this function to provide alternate behavior.
581 TemplateName
582 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
583 SourceLocation NameLoc,
584 QualType ObjectType = QualType(),
585 NamedDecl *FirstQualifierInScope = nullptr,
586 bool AllowInjectedClassName = false);
587
588 /// Transform the given template argument.
589 ///
590 /// By default, this operation transforms the type, expression, or
591 /// declaration stored within the template argument and constructs a
592 /// new template argument from the transformed result. Subclasses may
593 /// override this function to provide alternate behavior.
594 ///
595 /// Returns true if there was an error.
596 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
597 TemplateArgumentLoc &Output,
598 bool Uneval = false);
599
600 /// Transform the given set of template arguments.
601 ///
602 /// By default, this operation transforms all of the template arguments
603 /// in the input set using \c TransformTemplateArgument(), and appends
604 /// the transformed arguments to the output list.
605 ///
606 /// Note that this overload of \c TransformTemplateArguments() is merely
607 /// a convenience function. Subclasses that wish to override this behavior
608 /// should override the iterator-based member template version.
609 ///
610 /// \param Inputs The set of template arguments to be transformed.
611 ///
612 /// \param NumInputs The number of template arguments in \p Inputs.
613 ///
614 /// \param Outputs The set of transformed template arguments output by this
615 /// routine.
616 ///
617 /// Returns true if an error occurred.
618 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
619 unsigned NumInputs,
620 TemplateArgumentListInfo &Outputs,
621 bool Uneval = false) {
622 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
623 Uneval);
624 }
625
626 /// Transform the given set of template arguments.
627 ///
628 /// By default, this operation transforms all of the template arguments
629 /// in the input set using \c TransformTemplateArgument(), and appends
630 /// the transformed arguments to the output list.
631 ///
632 /// \param First An iterator to the first template argument.
633 ///
634 /// \param Last An iterator one step past the last template argument.
635 ///
636 /// \param Outputs The set of transformed template arguments output by this
637 /// routine.
638 ///
639 /// Returns true if an error occurred.
640 template<typename InputIterator>
641 bool TransformTemplateArguments(InputIterator First,
642 InputIterator Last,
643 TemplateArgumentListInfo &Outputs,
644 bool Uneval = false);
645
646 /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
647 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
648 TemplateArgumentLoc &ArgLoc);
649
650 /// Fakes up a TypeSourceInfo for a type.
651 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
652 return SemaRef.Context.getTrivialTypeSourceInfo(T,
653 getDerived().getBaseLocation());
654 }
655
656#define ABSTRACT_TYPELOC(CLASS, PARENT)
657#define TYPELOC(CLASS, PARENT) \
658 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
659#include "clang/AST/TypeLocNodes.def"
660
661 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
662 TemplateTypeParmTypeLoc TL,
663 bool SuppressObjCLifetime);
664 QualType
665 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
666 SubstTemplateTypeParmPackTypeLoc TL,
667 bool SuppressObjCLifetime);
668
669 template<typename Fn>
670 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
671 FunctionProtoTypeLoc TL,
672 CXXRecordDecl *ThisContext,
673 Qualifiers ThisTypeQuals,
674 Fn TransformExceptionSpec);
675
676 bool TransformExceptionSpec(SourceLocation Loc,
677 FunctionProtoType::ExceptionSpecInfo &ESI,
678 SmallVectorImpl<QualType> &Exceptions,
679 bool &Changed);
680
681 StmtResult TransformSEHHandler(Stmt *Handler);
682
683 QualType
684 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
685 TemplateSpecializationTypeLoc TL,
686 TemplateName Template);
687
688 QualType
689 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
690 DependentTemplateSpecializationTypeLoc TL,
691 TemplateName Template,
692 CXXScopeSpec &SS);
693
694 QualType TransformDependentTemplateSpecializationType(
695 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
696 NestedNameSpecifierLoc QualifierLoc);
697
698 /// Transforms the parameters of a function type into the
699 /// given vectors.
700 ///
701 /// The result vectors should be kept in sync; null entries in the
702 /// variables vector are acceptable.
703 ///
704 /// LastParamTransformed, if non-null, will be set to the index of the last
705 /// parameter on which transfromation was started. In the event of an error,
706 /// this will contain the parameter which failed to instantiate.
707 ///
708 /// Return true on error.
709 bool TransformFunctionTypeParams(
710 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
711 const QualType *ParamTypes,
712 const FunctionProtoType::ExtParameterInfo *ParamInfos,
713 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
714 Sema::ExtParameterInfoBuilder &PInfos, unsigned *LastParamTransformed);
715
716 bool TransformFunctionTypeParams(
717 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
718 const QualType *ParamTypes,
719 const FunctionProtoType::ExtParameterInfo *ParamInfos,
720 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
721 Sema::ExtParameterInfoBuilder &PInfos) {
722 return getDerived().TransformFunctionTypeParams(
723 Loc, Params, ParamTypes, ParamInfos, PTypes, PVars, PInfos, nullptr);
724 }
725
726 /// Transforms the parameters of a requires expresison into the given vectors.
727 ///
728 /// The result vectors should be kept in sync; null entries in the
729 /// variables vector are acceptable.
730 ///
731 /// Returns an unset ExprResult on success. Returns an ExprResult the 'not
732 /// satisfied' RequiresExpr if subsitution failed, OR an ExprError, both of
733 /// which are cases where transformation shouldn't continue.
734 ExprResult TransformRequiresTypeParams(
735 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
736 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
737 SmallVectorImpl<QualType> &PTypes,
738 SmallVectorImpl<ParmVarDecl *> &TransParams,
739 Sema::ExtParameterInfoBuilder &PInfos) {
740 if (getDerived().TransformFunctionTypeParams(
741 KWLoc, Params, /*ParamTypes=*/nullptr,
742 /*ParamInfos=*/nullptr, PTypes, &TransParams, PInfos))
743 return ExprError();
744
745 return ExprResult{};
746 }
747
748 /// Transforms a single function-type parameter. Return null
749 /// on error.
750 ///
751 /// \param indexAdjustment - A number to add to the parameter's
752 /// scope index; can be negative
753 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
754 int indexAdjustment,
755 std::optional<unsigned> NumExpansions,
756 bool ExpectParameterPack);
757
758 /// Transform the body of a lambda-expression.
759 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
760 /// Alternative implementation of TransformLambdaBody that skips transforming
761 /// the body.
762 StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
763
764 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
765
766 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
767 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
768
769 TemplateParameterList *TransformTemplateParameterList(
770 TemplateParameterList *TPL) {
771 return TPL;
772 }
773
774 ExprResult TransformAddressOfOperand(Expr *E);
775
776 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
777 bool IsAddressOfOperand,
778 TypeSourceInfo **RecoveryTSI);
779
780 ExprResult TransformParenDependentScopeDeclRefExpr(
781 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
782 TypeSourceInfo **RecoveryTSI);
783
784 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
785
786// FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
787// amount of stack usage with clang.
788#define STMT(Node, Parent) \
789 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
790 StmtResult Transform##Node(Node *S);
791#define VALUESTMT(Node, Parent) \
792 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
793 StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
794#define EXPR(Node, Parent) \
795 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
796 ExprResult Transform##Node(Node *E);
797#define ABSTRACT_STMT(Stmt)
798#include "clang/AST/StmtNodes.inc"
799
800#define GEN_CLANG_CLAUSE_CLASS
801#define CLAUSE_CLASS(Enum, Str, Class) \
802 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
803 OMPClause *Transform##Class(Class *S);
804#include "llvm/Frontend/OpenMP/OMP.inc"
805
806 /// Build a new qualified type given its unqualified type and type location.
807 ///
808 /// By default, this routine adds type qualifiers only to types that can
809 /// have qualifiers, and silently suppresses those qualifiers that are not
810 /// permitted. Subclasses may override this routine to provide different
811 /// behavior.
812 QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
813
814 /// Build a new pointer type given its pointee type.
815 ///
816 /// By default, performs semantic analysis when building the pointer type.
817 /// Subclasses may override this routine to provide different behavior.
818 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
819
820 /// Build a new block pointer type given its pointee type.
821 ///
822 /// By default, performs semantic analysis when building the block pointer
823 /// type. Subclasses may override this routine to provide different behavior.
824 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
825
826 /// Build a new reference type given the type it references.
827 ///
828 /// By default, performs semantic analysis when building the
829 /// reference type. Subclasses may override this routine to provide
830 /// different behavior.
831 ///
832 /// \param LValue whether the type was written with an lvalue sigil
833 /// or an rvalue sigil.
834 QualType RebuildReferenceType(QualType ReferentType,
835 bool LValue,
836 SourceLocation Sigil);
837
838 /// Build a new member pointer type given the pointee type and the
839 /// class type it refers into.
840 ///
841 /// By default, performs semantic analysis when building the member pointer
842 /// type. Subclasses may override this routine to provide different behavior.
843 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
844 SourceLocation Sigil);
845
846 QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
847 SourceLocation ProtocolLAngleLoc,
848 ArrayRef<ObjCProtocolDecl *> Protocols,
849 ArrayRef<SourceLocation> ProtocolLocs,
850 SourceLocation ProtocolRAngleLoc);
851
852 /// Build an Objective-C object type.
853 ///
854 /// By default, performs semantic analysis when building the object type.
855 /// Subclasses may override this routine to provide different behavior.
856 QualType RebuildObjCObjectType(QualType BaseType,
857 SourceLocation Loc,
858 SourceLocation TypeArgsLAngleLoc,
859 ArrayRef<TypeSourceInfo *> TypeArgs,
860 SourceLocation TypeArgsRAngleLoc,
861 SourceLocation ProtocolLAngleLoc,
862 ArrayRef<ObjCProtocolDecl *> Protocols,
863 ArrayRef<SourceLocation> ProtocolLocs,
864 SourceLocation ProtocolRAngleLoc);
865
866 /// Build a new Objective-C object pointer type given the pointee type.
867 ///
868 /// By default, directly builds the pointer type, with no additional semantic
869 /// analysis.
870 QualType RebuildObjCObjectPointerType(QualType PointeeType,
871 SourceLocation Star);
872
873 /// Build a new array type given the element type, size
874 /// modifier, size of the array (if known), size expression, and index type
875 /// qualifiers.
876 ///
877 /// By default, performs semantic analysis when building the array type.
878 /// Subclasses may override this routine to provide different behavior.
879 /// Also by default, all of the other Rebuild*Array
880 QualType RebuildArrayType(QualType ElementType,
881 ArrayType::ArraySizeModifier SizeMod,
882 const llvm::APInt *Size,
883 Expr *SizeExpr,
884 unsigned IndexTypeQuals,
885 SourceRange BracketsRange);
886
887 /// Build a new constant array type given the element type, size
888 /// modifier, (known) size of the array, and index type qualifiers.
889 ///
890 /// By default, performs semantic analysis when building the array type.
891 /// Subclasses may override this routine to provide different behavior.
892 QualType RebuildConstantArrayType(QualType ElementType,
893 ArrayType::ArraySizeModifier SizeMod,
894 const llvm::APInt &Size,
895 Expr *SizeExpr,
896 unsigned IndexTypeQuals,
897 SourceRange BracketsRange);
898
899 /// Build a new incomplete array type given the element type, size
900 /// modifier, and index type qualifiers.
901 ///
902 /// By default, performs semantic analysis when building the array type.
903 /// Subclasses may override this routine to provide different behavior.
904 QualType RebuildIncompleteArrayType(QualType ElementType,
905 ArrayType::ArraySizeModifier SizeMod,
906 unsigned IndexTypeQuals,
907 SourceRange BracketsRange);
908
909 /// Build a new variable-length array type given the element type,
910 /// size modifier, size expression, and index type qualifiers.
911 ///
912 /// By default, performs semantic analysis when building the array type.
913 /// Subclasses may override this routine to provide different behavior.
914 QualType RebuildVariableArrayType(QualType ElementType,
915 ArrayType::ArraySizeModifier SizeMod,
916 Expr *SizeExpr,
917 unsigned IndexTypeQuals,
918 SourceRange BracketsRange);
919
920 /// Build a new dependent-sized array type given the element type,
921 /// size modifier, size expression, and index type qualifiers.
922 ///
923 /// By default, performs semantic analysis when building the array type.
924 /// Subclasses may override this routine to provide different behavior.
925 QualType RebuildDependentSizedArrayType(QualType ElementType,
926 ArrayType::ArraySizeModifier SizeMod,
927 Expr *SizeExpr,
928 unsigned IndexTypeQuals,
929 SourceRange BracketsRange);
930
931 /// Build a new vector type given the element type and
932 /// number of elements.
933 ///
934 /// By default, performs semantic analysis when building the vector type.
935 /// Subclasses may override this routine to provide different behavior.
936 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
937 VectorType::VectorKind VecKind);
938
939 /// Build a new potentially dependently-sized extended vector type
940 /// given the element type and number of elements.
941 ///
942 /// By default, performs semantic analysis when building the vector type.
943 /// Subclasses may override this routine to provide different behavior.
944 QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
945 SourceLocation AttributeLoc,
946 VectorType::VectorKind);
947
948 /// Build a new extended vector type given the element type and
949 /// number of elements.
950 ///
951 /// By default, performs semantic analysis when building the vector type.
952 /// Subclasses may override this routine to provide different behavior.
953 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
954 SourceLocation AttributeLoc);
955
956 /// Build a new potentially dependently-sized extended vector type
957 /// given the element type and number of elements.
958 ///
959 /// By default, performs semantic analysis when building the vector type.
960 /// Subclasses may override this routine to provide different behavior.
961 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
962 Expr *SizeExpr,
963 SourceLocation AttributeLoc);
964
965 /// Build a new matrix type given the element type and dimensions.
966 QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
967 unsigned NumColumns);
968
969 /// Build a new matrix type given the type and dependently-defined
970 /// dimensions.
971 QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
972 Expr *ColumnExpr,
973 SourceLocation AttributeLoc);
974
975 /// Build a new DependentAddressSpaceType or return the pointee
976 /// type variable with the correct address space (retrieved from
977 /// AddrSpaceExpr) applied to it. The former will be returned in cases
978 /// where the address space remains dependent.
979 ///
980 /// By default, performs semantic analysis when building the type with address
981 /// space applied. Subclasses may override this routine to provide different
982 /// behavior.
983 QualType RebuildDependentAddressSpaceType(QualType PointeeType,
984 Expr *AddrSpaceExpr,
985 SourceLocation AttributeLoc);
986
987 /// Build a new function type.
988 ///
989 /// By default, performs semantic analysis when building the function type.
990 /// Subclasses may override this routine to provide different behavior.
991 QualType RebuildFunctionProtoType(QualType T,
992 MutableArrayRef<QualType> ParamTypes,
993 const FunctionProtoType::ExtProtoInfo &EPI);
994
995 /// Build a new unprototyped function type.
996 QualType RebuildFunctionNoProtoType(QualType ResultType);
997
998 /// Rebuild an unresolved typename type, given the decl that
999 /// the UnresolvedUsingTypenameDecl was transformed to.
1000 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
1001
1002 /// Build a new type found via an alias.
1003 QualType RebuildUsingType(UsingShadowDecl *Found, QualType Underlying) {
1004 return SemaRef.Context.getUsingType(Found, Underlying);
1005 }
1006
1007 /// Build a new typedef type.
1008 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
1009 return SemaRef.Context.getTypeDeclType(Typedef);
1010 }
1011
1012 /// Build a new MacroDefined type.
1013 QualType RebuildMacroQualifiedType(QualType T,
1014 const IdentifierInfo *MacroII) {
1015 return SemaRef.Context.getMacroQualifiedType(T, MacroII);
1016 }
1017
1018 /// Build a new class/struct/union type.
1019 QualType RebuildRecordType(RecordDecl *Record) {
1020 return SemaRef.Context.getTypeDeclType(Record);
1021 }
1022
1023 /// Build a new Enum type.
1024 QualType RebuildEnumType(EnumDecl *Enum) {
1025 return SemaRef.Context.getTypeDeclType(Enum);
1026 }
1027
1028 /// Build a new typeof(expr) type.
1029 ///
1030 /// By default, performs semantic analysis when building the typeof type.
1031 /// Subclasses may override this routine to provide different behavior.
1032 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc,
1033 TypeOfKind Kind);
1034
1035 /// Build a new typeof(type) type.
1036 ///
1037 /// By default, builds a new TypeOfType with the given underlying type.
1038 QualType RebuildTypeOfType(QualType Underlying, TypeOfKind Kind);
1039
1040 /// Build a new unary transform type.
1041 QualType RebuildUnaryTransformType(QualType BaseType,
1042 UnaryTransformType::UTTKind UKind,
1043 SourceLocation Loc);
1044
1045 /// Build a new C++11 decltype type.
1046 ///
1047 /// By default, performs semantic analysis when building the decltype type.
1048 /// Subclasses may override this routine to provide different behavior.
1049 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
1050
1051 /// Build a new C++11 auto type.
1052 ///
1053 /// By default, builds a new AutoType with the given deduced type.
1054 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
1055 ConceptDecl *TypeConstraintConcept,
1056 ArrayRef<TemplateArgument> TypeConstraintArgs) {
1057 // Note, IsDependent is always false here: we implicitly convert an 'auto'
1058 // which has been deduced to a dependent type into an undeduced 'auto', so
1059 // that we'll retry deduction after the transformation.
1060 return SemaRef.Context.getAutoType(Deduced, Keyword,
1061 /*IsDependent*/ false, /*IsPack=*/false,
1062 TypeConstraintConcept,
1063 TypeConstraintArgs);
1064 }
1065
1066 /// By default, builds a new DeducedTemplateSpecializationType with the given
1067 /// deduced type.
1068 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
1069 QualType Deduced) {
1070 return SemaRef.Context.getDeducedTemplateSpecializationType(
1071 Template, Deduced, /*IsDependent*/ false);
1072 }
1073
1074 /// Build a new template specialization type.
1075 ///
1076 /// By default, performs semantic analysis when building the template
1077 /// specialization type. Subclasses may override this routine to provide
1078 /// different behavior.
1079 QualType RebuildTemplateSpecializationType(TemplateName Template,
1080 SourceLocation TemplateLoc,
1081 TemplateArgumentListInfo &Args);
1082
1083 /// Build a new parenthesized type.
1084 ///
1085 /// By default, builds a new ParenType type from the inner type.
1086 /// Subclasses may override this routine to provide different behavior.
1087 QualType RebuildParenType(QualType InnerType) {
1088 return SemaRef.BuildParenType(InnerType);
1089 }
1090
1091 /// Build a new qualified name type.
1092 ///
1093 /// By default, builds a new ElaboratedType type from the keyword,
1094 /// the nested-name-specifier and the named type.
1095 /// Subclasses may override this routine to provide different behavior.
1096 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1097 ElaboratedTypeKeyword Keyword,
1098 NestedNameSpecifierLoc QualifierLoc,
1099 QualType Named) {
1100 return SemaRef.Context.getElaboratedType(Keyword,
1101 QualifierLoc.getNestedNameSpecifier(),
1102 Named);
1103 }
1104
1105 /// Build a new typename type that refers to a template-id.
1106 ///
1107 /// By default, builds a new DependentNameType type from the
1108 /// nested-name-specifier and the given type. Subclasses may override
1109 /// this routine to provide different behavior.
1110 QualType RebuildDependentTemplateSpecializationType(
1111 ElaboratedTypeKeyword Keyword,
1112 NestedNameSpecifierLoc QualifierLoc,
1113 SourceLocation TemplateKWLoc,
1114 const IdentifierInfo *Name,
1115 SourceLocation NameLoc,
1116 TemplateArgumentListInfo &Args,
1117 bool AllowInjectedClassName) {
1118 // Rebuild the template name.
1119 // TODO: avoid TemplateName abstraction
1120 CXXScopeSpec SS;
1121 SS.Adopt(QualifierLoc);
1122 TemplateName InstName = getDerived().RebuildTemplateName(
1123 SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1124 AllowInjectedClassName);
1125
1126 if (InstName.isNull())
1127 return QualType();
1128
1129 // If it's still dependent, make a dependent specialization.
1130 if (InstName.getAsDependentTemplateName())
1131 return SemaRef.Context.getDependentTemplateSpecializationType(
1132 Keyword, QualifierLoc.getNestedNameSpecifier(), Name,
1133 Args.arguments());
1134
1135 // Otherwise, make an elaborated type wrapping a non-dependent
1136 // specialization.
1137 QualType T =
1138 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1139 if (T.isNull())
1140 return QualType();
1141 return SemaRef.Context.getElaboratedType(
1142 Keyword, QualifierLoc.getNestedNameSpecifier(), T);
1143 }
1144
1145 /// Build a new typename type that refers to an identifier.
1146 ///
1147 /// By default, performs semantic analysis when building the typename type
1148 /// (or elaborated type). Subclasses may override this routine to provide
1149 /// different behavior.
1150 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1151 SourceLocation KeywordLoc,
1152 NestedNameSpecifierLoc QualifierLoc,
1153 const IdentifierInfo *Id,
1154 SourceLocation IdLoc,
1155 bool DeducedTSTContext) {
1156 CXXScopeSpec SS;
1157 SS.Adopt(QualifierLoc);
1158
1159 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1160 // If the name is still dependent, just build a new dependent name type.
1161 if (!SemaRef.computeDeclContext(SS))
1162 return SemaRef.Context.getDependentNameType(Keyword,
1163 QualifierLoc.getNestedNameSpecifier(),
1164 Id);
1165 }
1166
1167 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1168 return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1169 *Id, IdLoc, DeducedTSTContext);
1170 }
1171
1172 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1173
1174 // We had a dependent elaborated-type-specifier that has been transformed
1175 // into a non-dependent elaborated-type-specifier. Find the tag we're
1176 // referring to.
1177 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1178 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1179 if (!DC)
1180 return QualType();
1181
1182 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1183 return QualType();
1184
1185 TagDecl *Tag = nullptr;
1186 SemaRef.LookupQualifiedName(Result, DC);
1187 switch (Result.getResultKind()) {
1188 case LookupResult::NotFound:
1189 case LookupResult::NotFoundInCurrentInstantiation:
1190 break;
1191
1192 case LookupResult::Found:
1193 Tag = Result.getAsSingle<TagDecl>();
1194 break;
1195
1196 case LookupResult::FoundOverloaded:
1197 case LookupResult::FoundUnresolvedValue:
1198 llvm_unreachable("Tag lookup cannot find non-tags")::llvm::llvm_unreachable_internal("Tag lookup cannot find non-tags"
, "clang/lib/Sema/TreeTransform.h", 1198)
;
1199
1200 case LookupResult::Ambiguous:
1201 // Let the LookupResult structure handle ambiguities.
1202 return QualType();
1203 }
1204
1205 if (!Tag) {
1206 // Check where the name exists but isn't a tag type and use that to emit
1207 // better diagnostics.
1208 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1209 SemaRef.LookupQualifiedName(Result, DC);
1210 switch (Result.getResultKind()) {
1211 case LookupResult::Found:
1212 case LookupResult::FoundOverloaded:
1213 case LookupResult::FoundUnresolvedValue: {
1214 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1215 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1216 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1217 << NTK << Kind;
1218 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1219 break;
1220 }
1221 default:
1222 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1223 << Kind << Id << DC << QualifierLoc.getSourceRange();
1224 break;
1225 }
1226 return QualType();
1227 }
1228
1229 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1230 IdLoc, Id)) {
1231 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1232 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1233 return QualType();
1234 }
1235
1236 // Build the elaborated-type-specifier type.
1237 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1238 return SemaRef.Context.getElaboratedType(Keyword,
1239 QualifierLoc.getNestedNameSpecifier(),
1240 T);
1241 }
1242
1243 /// Build a new pack expansion type.
1244 ///
1245 /// By default, builds a new PackExpansionType type from the given pattern.
1246 /// Subclasses may override this routine to provide different behavior.
1247 QualType RebuildPackExpansionType(QualType Pattern, SourceRange PatternRange,
1248 SourceLocation EllipsisLoc,
1249 std::optional<unsigned> NumExpansions) {
1250 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1251 NumExpansions);
1252 }
1253
1254 /// Build a new atomic type given its value type.
1255 ///
1256 /// By default, performs semantic analysis when building the atomic type.
1257 /// Subclasses may override this routine to provide different behavior.
1258 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1259
1260 /// Build a new pipe type given its value type.
1261 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1262 bool isReadPipe);
1263
1264 /// Build a bit-precise int given its value type.
1265 QualType RebuildBitIntType(bool IsUnsigned, unsigned NumBits,
1266 SourceLocation Loc);
1267
1268 /// Build a dependent bit-precise int given its value type.
1269 QualType RebuildDependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr,
1270 SourceLocation Loc);
1271
1272 /// Build a new template name given a nested name specifier, a flag
1273 /// indicating whether the "template" keyword was provided, and the template
1274 /// that the template name refers to.
1275 ///
1276 /// By default, builds the new template name directly. Subclasses may override
1277 /// this routine to provide different behavior.
1278 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1279 bool TemplateKW,
1280 TemplateDecl *Template);
1281
1282 /// Build a new template name given a nested name specifier and the
1283 /// name that is referred to as a template.
1284 ///
1285 /// By default, performs semantic analysis to determine whether the name can
1286 /// be resolved to a specific template, then builds the appropriate kind of
1287 /// template name. Subclasses may override this routine to provide different
1288 /// behavior.
1289 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1290 SourceLocation TemplateKWLoc,
1291 const IdentifierInfo &Name,
1292 SourceLocation NameLoc, QualType ObjectType,
1293 NamedDecl *FirstQualifierInScope,
1294 bool AllowInjectedClassName);
1295
1296 /// Build a new template name given a nested name specifier and the
1297 /// overloaded operator name that is referred to as a template.
1298 ///
1299 /// By default, performs semantic analysis to determine whether the name can
1300 /// be resolved to a specific template, then builds the appropriate kind of
1301 /// template name. Subclasses may override this routine to provide different
1302 /// behavior.
1303 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1304 SourceLocation TemplateKWLoc,
1305 OverloadedOperatorKind Operator,
1306 SourceLocation NameLoc, QualType ObjectType,
1307 bool AllowInjectedClassName);
1308
1309 /// Build a new template name given a template template parameter pack
1310 /// and the
1311 ///
1312 /// By default, performs semantic analysis to determine whether the name can
1313 /// be resolved to a specific template, then builds the appropriate kind of
1314 /// template name. Subclasses may override this routine to provide different
1315 /// behavior.
1316 TemplateName RebuildTemplateName(const TemplateArgument &ArgPack,
1317 Decl *AssociatedDecl, unsigned Index,
1318 bool Final) {
1319 return getSema().Context.getSubstTemplateTemplateParmPack(
1320 ArgPack, AssociatedDecl, Index, Final);
1321 }
1322
1323 /// Build a new compound statement.
1324 ///
1325 /// By default, performs semantic analysis to build the new statement.
1326 /// Subclasses may override this routine to provide different behavior.
1327 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1328 MultiStmtArg Statements,
1329 SourceLocation RBraceLoc,
1330 bool IsStmtExpr) {
1331 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1332 IsStmtExpr);
1333 }
1334
1335 /// Build a new case statement.
1336 ///
1337 /// By default, performs semantic analysis to build the new statement.
1338 /// Subclasses may override this routine to provide different behavior.
1339 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1340 Expr *LHS,
1341 SourceLocation EllipsisLoc,
1342 Expr *RHS,
1343 SourceLocation ColonLoc) {
1344 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1345 ColonLoc);
1346 }
1347
1348 /// Attach the body to a new case statement.
1349 ///
1350 /// By default, performs semantic analysis to build the new statement.
1351 /// Subclasses may override this routine to provide different behavior.
1352 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1353 getSema().ActOnCaseStmtBody(S, Body);
1354 return S;
1355 }
1356
1357 /// Build a new default statement.
1358 ///
1359 /// By default, performs semantic analysis to build the new statement.
1360 /// Subclasses may override this routine to provide different behavior.
1361 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1362 SourceLocation ColonLoc,
1363 Stmt *SubStmt) {
1364 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1365 /*CurScope=*/nullptr);
1366 }
1367
1368 /// Build a new label statement.
1369 ///
1370 /// By default, performs semantic analysis to build the new statement.
1371 /// Subclasses may override this routine to provide different behavior.
1372 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1373 SourceLocation ColonLoc, Stmt *SubStmt) {
1374 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1375 }
1376
1377 /// Build a new attributed statement.
1378 ///
1379 /// By default, performs semantic analysis to build the new statement.
1380 /// Subclasses may override this routine to provide different behavior.
1381 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1382 ArrayRef<const Attr *> Attrs,
1383 Stmt *SubStmt) {
1384 return SemaRef.BuildAttributedStmt(AttrLoc, Attrs, SubStmt);
1385 }
1386
1387 /// Build a new "if" statement.
1388 ///
1389 /// By default, performs semantic analysis to build the new statement.
1390 /// Subclasses may override this routine to provide different behavior.
1391 StmtResult RebuildIfStmt(SourceLocation IfLoc, IfStatementKind Kind,
1392 SourceLocation LParenLoc, Sema::ConditionResult Cond,
1393 SourceLocation RParenLoc, Stmt *Init, Stmt *Then,
1394 SourceLocation ElseLoc, Stmt *Else) {
1395 return getSema().ActOnIfStmt(IfLoc, Kind, LParenLoc, Init, Cond, RParenLoc,
1396 Then, ElseLoc, Else);
1397 }
1398
1399 /// Start building a new switch statement.
1400 ///
1401 /// By default, performs semantic analysis to build the new statement.
1402 /// Subclasses may override this routine to provide different behavior.
1403 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1404 SourceLocation LParenLoc, Stmt *Init,
1405 Sema::ConditionResult Cond,
1406 SourceLocation RParenLoc) {
1407 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, LParenLoc, Init, Cond,
1408 RParenLoc);
1409 }
1410
1411 /// Attach the body to the switch statement.
1412 ///
1413 /// By default, performs semantic analysis to build the new statement.
1414 /// Subclasses may override this routine to provide different behavior.
1415 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1416 Stmt *Switch, Stmt *Body) {
1417 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1418 }
1419
1420 /// Build a new while statement.
1421 ///
1422 /// By default, performs semantic analysis to build the new statement.
1423 /// Subclasses may override this routine to provide different behavior.
1424 StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1425 Sema::ConditionResult Cond,
1426 SourceLocation RParenLoc, Stmt *Body) {
1427 return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1428 }
1429
1430 /// Build a new do-while statement.
1431 ///
1432 /// By default, performs semantic analysis to build the new statement.
1433 /// Subclasses may override this routine to provide different behavior.
1434 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1435 SourceLocation WhileLoc, SourceLocation LParenLoc,
1436 Expr *Cond, SourceLocation RParenLoc) {
1437 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1438 Cond, RParenLoc);
1439 }
1440
1441 /// Build a new for statement.
1442 ///
1443 /// By default, performs semantic analysis to build the new statement.
1444 /// Subclasses may override this routine to provide different behavior.
1445 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1446 Stmt *Init, Sema::ConditionResult Cond,
1447 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1448 Stmt *Body) {
1449 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1450 Inc, RParenLoc, Body);
1451 }
1452
1453 /// Build a new goto statement.
1454 ///
1455 /// By default, performs semantic analysis to build the new statement.
1456 /// Subclasses may override this routine to provide different behavior.
1457 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1458 LabelDecl *Label) {
1459 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1460 }
1461
1462 /// Build a new indirect goto statement.
1463 ///
1464 /// By default, performs semantic analysis to build the new statement.
1465 /// Subclasses may override this routine to provide different behavior.
1466 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1467 SourceLocation StarLoc,
1468 Expr *Target) {
1469 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1470 }
1471
1472 /// Build a new return statement.
1473 ///
1474 /// By default, performs semantic analysis to build the new statement.
1475 /// Subclasses may override this routine to provide different behavior.
1476 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1477 return getSema().BuildReturnStmt(ReturnLoc, Result);
1478 }
1479
1480 /// Build a new declaration statement.
1481 ///
1482 /// By default, performs semantic analysis to build the new statement.
1483 /// Subclasses may override this routine to provide different behavior.
1484 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1485 SourceLocation StartLoc, SourceLocation EndLoc) {
1486 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1487 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1488 }
1489
1490 /// Build a new inline asm statement.
1491 ///
1492 /// By default, performs semantic analysis to build the new statement.
1493 /// Subclasses may override this routine to provide different behavior.
1494 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1495 bool IsVolatile, unsigned NumOutputs,
1496 unsigned NumInputs, IdentifierInfo **Names,
1497 MultiExprArg Constraints, MultiExprArg Exprs,
1498 Expr *AsmString, MultiExprArg Clobbers,
1499 unsigned NumLabels,
1500 SourceLocation RParenLoc) {
1501 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1502 NumInputs, Names, Constraints, Exprs,
1503 AsmString, Clobbers, NumLabels, RParenLoc);
1504 }
1505
1506 /// Build a new MS style inline asm statement.
1507 ///
1508 /// By default, performs semantic analysis to build the new statement.
1509 /// Subclasses may override this routine to provide different behavior.
1510 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1511 ArrayRef<Token> AsmToks,
1512 StringRef AsmString,
1513 unsigned NumOutputs, unsigned NumInputs,
1514 ArrayRef<StringRef> Constraints,
1515 ArrayRef<StringRef> Clobbers,
1516 ArrayRef<Expr*> Exprs,
1517 SourceLocation EndLoc) {
1518 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1519 NumOutputs, NumInputs,
1520 Constraints, Clobbers, Exprs, EndLoc);
1521 }
1522
1523 /// Build a new co_return statement.
1524 ///
1525 /// By default, performs semantic analysis to build the new statement.
1526 /// Subclasses may override this routine to provide different behavior.
1527 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1528 bool IsImplicit) {
1529 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1530 }
1531
1532 /// Build a new co_await expression.
1533 ///
1534 /// By default, performs semantic analysis to build the new expression.
1535 /// Subclasses may override this routine to provide different behavior.
1536 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand,
1537 UnresolvedLookupExpr *OpCoawaitLookup,
1538 bool IsImplicit) {
1539 // This function rebuilds a coawait-expr given its operator.
1540 // For an explicit coawait-expr, the rebuild involves the full set
1541 // of transformations performed by BuildUnresolvedCoawaitExpr(),
1542 // including calling await_transform().
1543 // For an implicit coawait-expr, we need to rebuild the "operator
1544 // coawait" but not await_transform(), so use BuildResolvedCoawaitExpr().
1545 // This mirrors how the implicit CoawaitExpr is originally created
1546 // in Sema::ActOnCoroutineBodyStart().
1547 if (IsImplicit) {
1548 ExprResult Suspend = getSema().BuildOperatorCoawaitCall(
1549 CoawaitLoc, Operand, OpCoawaitLookup);
1550 if (Suspend.isInvalid())
1551 return ExprError();
1552 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Operand,
1553 Suspend.get(), true);
1554 }
1555
1556 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Operand,
1557 OpCoawaitLookup);
1558 }
1559
1560 /// Build a new co_await expression.
1561 ///
1562 /// By default, performs semantic analysis to build the new expression.
1563 /// Subclasses may override this routine to provide different behavior.
1564 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1565 Expr *Result,
1566 UnresolvedLookupExpr *Lookup) {
1567 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1568 }
1569
1570 /// Build a new co_yield expression.
1571 ///
1572 /// By default, performs semantic analysis to build the new expression.
1573 /// Subclasses may override this routine to provide different behavior.
1574 ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1575 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1576 }
1577
1578 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1579 return getSema().BuildCoroutineBodyStmt(Args);
1580 }
1581
1582 /// Build a new Objective-C \@try statement.
1583 ///
1584 /// By default, performs semantic analysis to build the new statement.
1585 /// Subclasses may override this routine to provide different behavior.
1586 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1587 Stmt *TryBody,
1588 MultiStmtArg CatchStmts,
1589 Stmt *Finally) {
1590 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1591 Finally);
1592 }
1593
1594 /// Rebuild an Objective-C exception declaration.
1595 ///
1596 /// By default, performs semantic analysis to build the new declaration.
1597 /// Subclasses may override this routine to provide different behavior.
1598 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1599 TypeSourceInfo *TInfo, QualType T) {
1600 return getSema().BuildObjCExceptionDecl(TInfo, T,
1601 ExceptionDecl->getInnerLocStart(),
1602 ExceptionDecl->getLocation(),
1603 ExceptionDecl->getIdentifier());
1604 }
1605
1606 /// Build a new Objective-C \@catch statement.
1607 ///
1608 /// By default, performs semantic analysis to build the new statement.
1609 /// Subclasses may override this routine to provide different behavior.
1610 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1611 SourceLocation RParenLoc,
1612 VarDecl *Var,
1613 Stmt *Body) {
1614 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1615 Var, Body);
1616 }
1617
1618 /// Build a new Objective-C \@finally statement.
1619 ///
1620 /// By default, performs semantic analysis to build the new statement.
1621 /// Subclasses may override this routine to provide different behavior.
1622 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1623 Stmt *Body) {
1624 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1625 }
1626
1627 /// Build a new Objective-C \@throw statement.
1628 ///
1629 /// By default, performs semantic analysis to build the new statement.
1630 /// Subclasses may override this routine to provide different behavior.
1631 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1632 Expr *Operand) {
1633 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1634 }
1635
1636 /// Build a new OpenMP Canonical loop.
1637 ///
1638 /// Ensures that the outermost loop in @p LoopStmt is wrapped by a
1639 /// OMPCanonicalLoop.
1640 StmtResult RebuildOMPCanonicalLoop(Stmt *LoopStmt) {
1641 return getSema().ActOnOpenMPCanonicalLoop(LoopStmt);
1642 }
1643
1644 /// Build a new OpenMP executable directive.
1645 ///
1646 /// By default, performs semantic analysis to build the new statement.
1647 /// Subclasses may override this routine to provide different behavior.
1648 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1649 DeclarationNameInfo DirName,
1650 OpenMPDirectiveKind CancelRegion,
1651 ArrayRef<OMPClause *> Clauses,
1652 Stmt *AStmt, SourceLocation StartLoc,
1653 SourceLocation EndLoc) {
1654 return getSema().ActOnOpenMPExecutableDirective(
1655 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1656 }
1657
1658 /// Build a new OpenMP 'if' clause.
1659 ///
1660 /// By default, performs semantic analysis to build the new OpenMP clause.
1661 /// Subclasses may override this routine to provide different behavior.
1662 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1663 Expr *Condition, SourceLocation StartLoc,
1664 SourceLocation LParenLoc,
1665 SourceLocation NameModifierLoc,
1666 SourceLocation ColonLoc,
1667 SourceLocation EndLoc) {
1668 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1669 LParenLoc, NameModifierLoc, ColonLoc,
1670 EndLoc);
1671 }
1672
1673 /// Build a new OpenMP 'final' clause.
1674 ///
1675 /// By default, performs semantic analysis to build the new OpenMP clause.
1676 /// Subclasses may override this routine to provide different behavior.
1677 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1678 SourceLocation LParenLoc,
1679 SourceLocation EndLoc) {
1680 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1681 EndLoc);
1682 }
1683
1684 /// Build a new OpenMP 'num_threads' clause.
1685 ///
1686 /// By default, performs semantic analysis to build the new OpenMP clause.
1687 /// Subclasses may override this routine to provide different behavior.
1688 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1689 SourceLocation StartLoc,
1690 SourceLocation LParenLoc,
1691 SourceLocation EndLoc) {
1692 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1693 LParenLoc, EndLoc);
1694 }
1695
1696 /// Build a new OpenMP 'safelen' clause.
1697 ///
1698 /// By default, performs semantic analysis to build the new OpenMP clause.
1699 /// Subclasses may override this routine to provide different behavior.
1700 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1701 SourceLocation LParenLoc,
1702 SourceLocation EndLoc) {
1703 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1704 }
1705
1706 /// Build a new OpenMP 'simdlen' clause.
1707 ///
1708 /// By default, performs semantic analysis to build the new OpenMP clause.
1709 /// Subclasses may override this routine to provide different behavior.
1710 OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1711 SourceLocation LParenLoc,
1712 SourceLocation EndLoc) {
1713 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1714 }
1715
1716 OMPClause *RebuildOMPSizesClause(ArrayRef<Expr *> Sizes,
1717 SourceLocation StartLoc,
1718 SourceLocation LParenLoc,
1719 SourceLocation EndLoc) {
1720 return getSema().ActOnOpenMPSizesClause(Sizes, StartLoc, LParenLoc, EndLoc);
1721 }
1722
1723 /// Build a new OpenMP 'full' clause.
1724 OMPClause *RebuildOMPFullClause(SourceLocation StartLoc,
1725 SourceLocation EndLoc) {
1726 return getSema().ActOnOpenMPFullClause(StartLoc, EndLoc);
1727 }
1728
1729 /// Build a new OpenMP 'partial' clause.
1730 OMPClause *RebuildOMPPartialClause(Expr *Factor, SourceLocation StartLoc,
1731 SourceLocation LParenLoc,
1732 SourceLocation EndLoc) {
1733 return getSema().ActOnOpenMPPartialClause(Factor, StartLoc, LParenLoc,
1734 EndLoc);
1735 }
1736
1737 /// Build a new OpenMP 'allocator' clause.
1738 ///
1739 /// By default, performs semantic analysis to build the new OpenMP clause.
1740 /// Subclasses may override this routine to provide different behavior.
1741 OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1742 SourceLocation LParenLoc,
1743 SourceLocation EndLoc) {
1744 return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1745 }
1746
1747 /// Build a new OpenMP 'collapse' clause.
1748 ///
1749 /// By default, performs semantic analysis to build the new OpenMP clause.
1750 /// Subclasses may override this routine to provide different behavior.
1751 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1752 SourceLocation LParenLoc,
1753 SourceLocation EndLoc) {
1754 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1755 EndLoc);
1756 }
1757
1758 /// Build a new OpenMP 'default' clause.
1759 ///
1760 /// By default, performs semantic analysis to build the new OpenMP clause.
1761 /// Subclasses may override this routine to provide different behavior.
1762 OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1763 SourceLocation StartLoc,
1764 SourceLocation LParenLoc,
1765 SourceLocation EndLoc) {
1766 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1767 StartLoc, LParenLoc, EndLoc);
1768 }
1769
1770 /// Build a new OpenMP 'proc_bind' clause.
1771 ///
1772 /// By default, performs semantic analysis to build the new OpenMP clause.
1773 /// Subclasses may override this routine to provide different behavior.
1774 OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1775 SourceLocation KindKwLoc,
1776 SourceLocation StartLoc,
1777 SourceLocation LParenLoc,
1778 SourceLocation EndLoc) {
1779 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1780 StartLoc, LParenLoc, EndLoc);
1781 }
1782
1783 /// Build a new OpenMP 'schedule' clause.
1784 ///
1785 /// By default, performs semantic analysis to build the new OpenMP clause.
1786 /// Subclasses may override this routine to provide different behavior.
1787 OMPClause *RebuildOMPScheduleClause(
1788 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1789 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1790 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1791 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1792 return getSema().ActOnOpenMPScheduleClause(
1793 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1794 CommaLoc, EndLoc);
1795 }
1796
1797 /// Build a new OpenMP 'ordered' clause.
1798 ///
1799 /// By default, performs semantic analysis to build the new OpenMP clause.
1800 /// Subclasses may override this routine to provide different behavior.
1801 OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1802 SourceLocation EndLoc,
1803 SourceLocation LParenLoc, Expr *Num) {
1804 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1805 }
1806
1807 /// Build a new OpenMP 'private' clause.
1808 ///
1809 /// By default, performs semantic analysis to build the new OpenMP clause.
1810 /// Subclasses may override this routine to provide different behavior.
1811 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1812 SourceLocation StartLoc,
1813 SourceLocation LParenLoc,
1814 SourceLocation EndLoc) {
1815 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1816 EndLoc);
1817 }
1818
1819 /// Build a new OpenMP 'firstprivate' clause.
1820 ///
1821 /// By default, performs semantic analysis to build the new OpenMP clause.
1822 /// Subclasses may override this routine to provide different behavior.
1823 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1824 SourceLocation StartLoc,
1825 SourceLocation LParenLoc,
1826 SourceLocation EndLoc) {
1827 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1828 EndLoc);
1829 }
1830
1831 /// Build a new OpenMP 'lastprivate' clause.
1832 ///
1833 /// By default, performs semantic analysis to build the new OpenMP clause.
1834 /// Subclasses may override this routine to provide different behavior.
1835 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1836 OpenMPLastprivateModifier LPKind,
1837 SourceLocation LPKindLoc,
1838 SourceLocation ColonLoc,
1839 SourceLocation StartLoc,
1840 SourceLocation LParenLoc,
1841 SourceLocation EndLoc) {
1842 return getSema().ActOnOpenMPLastprivateClause(
1843 VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1844 }
1845
1846 /// Build a new OpenMP 'shared' clause.
1847 ///
1848 /// By default, performs semantic analysis to build the new OpenMP clause.
1849 /// Subclasses may override this routine to provide different behavior.
1850 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1851 SourceLocation StartLoc,
1852 SourceLocation LParenLoc,
1853 SourceLocation EndLoc) {
1854 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1855 EndLoc);
1856 }
1857
1858 /// Build a new OpenMP 'reduction' clause.
1859 ///
1860 /// By default, performs semantic analysis to build the new statement.
1861 /// Subclasses may override this routine to provide different behavior.
1862 OMPClause *RebuildOMPReductionClause(
1863 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1864 SourceLocation StartLoc, SourceLocation LParenLoc,
1865 SourceLocation ModifierLoc, SourceLocation ColonLoc,
1866 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1867 const DeclarationNameInfo &ReductionId,
1868 ArrayRef<Expr *> UnresolvedReductions) {
1869 return getSema().ActOnOpenMPReductionClause(
1870 VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1871 ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1872 }
1873
1874 /// Build a new OpenMP 'task_reduction' clause.
1875 ///
1876 /// By default, performs semantic analysis to build the new statement.
1877 /// Subclasses may override this routine to provide different behavior.
1878 OMPClause *RebuildOMPTaskReductionClause(
1879 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1880 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1881 CXXScopeSpec &ReductionIdScopeSpec,
1882 const DeclarationNameInfo &ReductionId,
1883 ArrayRef<Expr *> UnresolvedReductions) {
1884 return getSema().ActOnOpenMPTaskReductionClause(
1885 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1886 ReductionId, UnresolvedReductions);
1887 }
1888
1889 /// Build a new OpenMP 'in_reduction' clause.
1890 ///
1891 /// By default, performs semantic analysis to build the new statement.
1892 /// Subclasses may override this routine to provide different behavior.
1893 OMPClause *
1894 RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1895 SourceLocation LParenLoc, SourceLocation ColonLoc,
1896 SourceLocation EndLoc,
1897 CXXScopeSpec &ReductionIdScopeSpec,
1898 const DeclarationNameInfo &ReductionId,
1899 ArrayRef<Expr *> UnresolvedReductions) {
1900 return getSema().ActOnOpenMPInReductionClause(
1901 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1902 ReductionId, UnresolvedReductions);
1903 }
1904
1905 /// Build a new OpenMP 'linear' clause.
1906 ///
1907 /// By default, performs semantic analysis to build the new OpenMP clause.
1908 /// Subclasses may override this routine to provide different behavior.
1909 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1910 SourceLocation StartLoc,
1911 SourceLocation LParenLoc,
1912 OpenMPLinearClauseKind Modifier,
1913 SourceLocation ModifierLoc,
1914 SourceLocation ColonLoc,
1915 SourceLocation EndLoc) {
1916 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1917 Modifier, ModifierLoc, ColonLoc,
1918 EndLoc);
1919 }
1920
1921 /// Build a new OpenMP 'aligned' clause.
1922 ///
1923 /// By default, performs semantic analysis to build the new OpenMP clause.
1924 /// Subclasses may override this routine to provide different behavior.
1925 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1926 SourceLocation StartLoc,
1927 SourceLocation LParenLoc,
1928 SourceLocation ColonLoc,
1929 SourceLocation EndLoc) {
1930 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1931 LParenLoc, ColonLoc, EndLoc);
1932 }
1933
1934 /// Build a new OpenMP 'copyin' clause.
1935 ///
1936 /// By default, performs semantic analysis to build the new OpenMP clause.
1937 /// Subclasses may override this routine to provide different behavior.
1938 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1939 SourceLocation StartLoc,
1940 SourceLocation LParenLoc,
1941 SourceLocation EndLoc) {
1942 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1943 EndLoc);
1944 }
1945
1946 /// Build a new OpenMP 'copyprivate' clause.
1947 ///
1948 /// By default, performs semantic analysis to build the new OpenMP clause.
1949 /// Subclasses may override this routine to provide different behavior.
1950 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1951 SourceLocation StartLoc,
1952 SourceLocation LParenLoc,
1953 SourceLocation EndLoc) {
1954 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1955 EndLoc);
1956 }
1957
1958 /// Build a new OpenMP 'flush' pseudo clause.
1959 ///
1960 /// By default, performs semantic analysis to build the new OpenMP clause.
1961 /// Subclasses may override this routine to provide different behavior.
1962 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1963 SourceLocation StartLoc,
1964 SourceLocation LParenLoc,
1965 SourceLocation EndLoc) {
1966 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1967 EndLoc);
1968 }
1969
1970 /// Build a new OpenMP 'depobj' pseudo clause.
1971 ///
1972 /// By default, performs semantic analysis to build the new OpenMP clause.
1973 /// Subclasses may override this routine to provide different behavior.
1974 OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1975 SourceLocation LParenLoc,
1976 SourceLocation EndLoc) {
1977 return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1978 EndLoc);
1979 }
1980
1981 /// Build a new OpenMP 'depend' pseudo clause.
1982 ///
1983 /// By default, performs semantic analysis to build the new OpenMP clause.
1984 /// Subclasses may override this routine to provide different behavior.
1985 OMPClause *RebuildOMPDependClause(OMPDependClause::DependDataTy Data,
1986 Expr *DepModifier, ArrayRef<Expr *> VarList,
1987 SourceLocation StartLoc,
1988 SourceLocation LParenLoc,
1989 SourceLocation EndLoc) {
1990 return getSema().ActOnOpenMPDependClause(Data, DepModifier, VarList,
1991 StartLoc, LParenLoc, EndLoc);
1992 }
1993
1994 /// Build a new OpenMP 'device' clause.
1995 ///
1996 /// By default, performs semantic analysis to build the new statement.
1997 /// Subclasses may override this routine to provide different behavior.
1998 OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
1999 Expr *Device, SourceLocation StartLoc,
2000 SourceLocation LParenLoc,
2001 SourceLocation ModifierLoc,
2002 SourceLocation EndLoc) {
2003 return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
2004 LParenLoc, ModifierLoc, EndLoc);
2005 }
2006
2007 /// Build a new OpenMP 'map' clause.
2008 ///
2009 /// By default, performs semantic analysis to build the new OpenMP clause.
2010 /// Subclasses may override this routine to provide different behavior.
2011 OMPClause *RebuildOMPMapClause(
2012 Expr *IteratorModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
2013 ArrayRef<SourceLocation> MapTypeModifiersLoc,
2014 CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
2015 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
2016 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
2017 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
2018 return getSema().ActOnOpenMPMapClause(
2019 IteratorModifier, MapTypeModifiers, MapTypeModifiersLoc,
2020 MapperIdScopeSpec, MapperId, MapType, IsMapTypeImplicit, MapLoc,
2021 ColonLoc, VarList, Locs,
2022 /*NoDiagnose=*/false, UnresolvedMappers);
2023 }
2024
2025 /// Build a new OpenMP 'allocate' clause.
2026 ///
2027 /// By default, performs semantic analysis to build the new OpenMP clause.
2028 /// Subclasses may override this routine to provide different behavior.
2029 OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
2030 SourceLocation StartLoc,
2031 SourceLocation LParenLoc,
2032 SourceLocation ColonLoc,
2033 SourceLocation EndLoc) {
2034 return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
2035 LParenLoc, ColonLoc, EndLoc);
2036 }
2037
2038 /// Build a new OpenMP 'num_teams' clause.
2039 ///
2040 /// By default, performs semantic analysis to build the new statement.
2041 /// Subclasses may override this routine to provide different behavior.
2042 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
2043 SourceLocation LParenLoc,
2044 SourceLocation EndLoc) {
2045 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
2046 EndLoc);
2047 }
2048
2049 /// Build a new OpenMP 'thread_limit' clause.
2050 ///
2051 /// By default, performs semantic analysis to build the new statement.
2052 /// Subclasses may override this routine to provide different behavior.
2053 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
2054 SourceLocation StartLoc,
2055 SourceLocation LParenLoc,
2056 SourceLocation EndLoc) {
2057 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
2058 LParenLoc, EndLoc);
2059 }
2060
2061 /// Build a new OpenMP 'priority' clause.
2062 ///
2063 /// By default, performs semantic analysis to build the new statement.
2064 /// Subclasses may override this routine to provide different behavior.
2065 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
2066 SourceLocation LParenLoc,
2067 SourceLocation EndLoc) {
2068 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
2069 EndLoc);
2070 }
2071
2072 /// Build a new OpenMP 'grainsize' clause.
2073 ///
2074 /// By default, performs semantic analysis to build the new statement.
2075 /// Subclasses may override this routine to provide different behavior.
2076 OMPClause *RebuildOMPGrainsizeClause(OpenMPGrainsizeClauseModifier Modifier,
2077 Expr *Device, SourceLocation StartLoc,
2078 SourceLocation LParenLoc,
2079 SourceLocation ModifierLoc,
2080 SourceLocation EndLoc) {
2081 return getSema().ActOnOpenMPGrainsizeClause(Modifier, Device, StartLoc,
2082 LParenLoc, ModifierLoc, EndLoc);
2083 }
2084
2085 /// Build a new OpenMP 'num_tasks' clause.
2086 ///
2087 /// By default, performs semantic analysis to build the new statement.
2088 /// Subclasses may override this routine to provide different behavior.
2089 OMPClause *RebuildOMPNumTasksClause(OpenMPNumTasksClauseModifier Modifier,
2090 Expr *NumTasks, SourceLocation StartLoc,
2091 SourceLocation LParenLoc,
2092 SourceLocation ModifierLoc,
2093 SourceLocation EndLoc) {
2094 return getSema().ActOnOpenMPNumTasksClause(Modifier, NumTasks, StartLoc,
2095 LParenLoc, ModifierLoc, EndLoc);
2096 }
2097
2098 /// Build a new OpenMP 'hint' clause.
2099 ///
2100 /// By default, performs semantic analysis to build the new statement.
2101 /// Subclasses may override this routine to provide different behavior.
2102 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
2103 SourceLocation LParenLoc,
2104 SourceLocation EndLoc) {
2105 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
2106 }
2107
2108 /// Build a new OpenMP 'detach' clause.
2109 ///
2110 /// By default, performs semantic analysis to build the new statement.
2111 /// Subclasses may override this routine to provide different behavior.
2112 OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
2113 SourceLocation LParenLoc,
2114 SourceLocation EndLoc) {
2115 return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
2116 }
2117
2118 /// Build a new OpenMP 'dist_schedule' clause.
2119 ///
2120 /// By default, performs semantic analysis to build the new OpenMP clause.
2121 /// Subclasses may override this routine to provide different behavior.
2122 OMPClause *
2123 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
2124 Expr *ChunkSize, SourceLocation StartLoc,
2125 SourceLocation LParenLoc, SourceLocation KindLoc,
2126 SourceLocation CommaLoc, SourceLocation EndLoc) {
2127 return getSema().ActOnOpenMPDistScheduleClause(
2128 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2129 }
2130
2131 /// Build a new OpenMP 'to' clause.
2132 ///
2133 /// By default, performs semantic analysis to build the new statement.
2134 /// Subclasses may override this routine to provide different behavior.
2135 OMPClause *
2136 RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2137 ArrayRef<SourceLocation> MotionModifiersLoc,
2138 CXXScopeSpec &MapperIdScopeSpec,
2139 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2140 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2141 ArrayRef<Expr *> UnresolvedMappers) {
2142 return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2143 MapperIdScopeSpec, MapperId, ColonLoc,
2144 VarList, Locs, UnresolvedMappers);
2145 }
2146
2147 /// Build a new OpenMP 'from' clause.
2148 ///
2149 /// By default, performs semantic analysis to build the new statement.
2150 /// Subclasses may override this routine to provide different behavior.
2151 OMPClause *
2152 RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2153 ArrayRef<SourceLocation> MotionModifiersLoc,
2154 CXXScopeSpec &MapperIdScopeSpec,
2155 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2156 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2157 ArrayRef<Expr *> UnresolvedMappers) {
2158 return getSema().ActOnOpenMPFromClause(
2159 MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2160 ColonLoc, VarList, Locs, UnresolvedMappers);
2161 }
2162
2163 /// Build a new OpenMP 'use_device_ptr' clause.
2164 ///
2165 /// By default, performs semantic analysis to build the new OpenMP clause.
2166 /// Subclasses may override this routine to provide different behavior.
2167 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2168 const OMPVarListLocTy &Locs) {
2169 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2170 }
2171
2172 /// Build a new OpenMP 'use_device_addr' clause.
2173 ///
2174 /// By default, performs semantic analysis to build the new OpenMP clause.
2175 /// Subclasses may override this routine to provide different behavior.
2176 OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2177 const OMPVarListLocTy &Locs) {
2178 return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2179 }
2180
2181 /// Build a new OpenMP 'is_device_ptr' clause.
2182 ///
2183 /// By default, performs semantic analysis to build the new OpenMP clause.
2184 /// Subclasses may override this routine to provide different behavior.
2185 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2186 const OMPVarListLocTy &Locs) {
2187 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2188 }
2189
2190 /// Build a new OpenMP 'has_device_addr' clause.
2191 ///
2192 /// By default, performs semantic analysis to build the new OpenMP clause.
2193 /// Subclasses may override this routine to provide different behavior.
2194 OMPClause *RebuildOMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
2195 const OMPVarListLocTy &Locs) {
2196 return getSema().ActOnOpenMPHasDeviceAddrClause(VarList, Locs);
2197 }
2198
2199 /// Build a new OpenMP 'defaultmap' clause.
2200 ///
2201 /// By default, performs semantic analysis to build the new OpenMP clause.
2202 /// Subclasses may override this routine to provide different behavior.
2203 OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2204 OpenMPDefaultmapClauseKind Kind,
2205 SourceLocation StartLoc,
2206 SourceLocation LParenLoc,
2207 SourceLocation MLoc,
2208 SourceLocation KindLoc,
2209 SourceLocation EndLoc) {
2210 return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2211 MLoc, KindLoc, EndLoc);
2212 }
2213
2214 /// Build a new OpenMP 'nontemporal' clause.
2215 ///
2216 /// By default, performs semantic analysis to build the new OpenMP clause.
2217 /// Subclasses may override this routine to provide different behavior.
2218 OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2219 SourceLocation StartLoc,
2220 SourceLocation LParenLoc,
2221 SourceLocation EndLoc) {
2222 return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2223 EndLoc);
2224 }
2225
2226 /// Build a new OpenMP 'inclusive' clause.
2227 ///
2228 /// By default, performs semantic analysis to build the new OpenMP clause.
2229 /// Subclasses may override this routine to provide different behavior.
2230 OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2231 SourceLocation StartLoc,
2232 SourceLocation LParenLoc,
2233 SourceLocation EndLoc) {
2234 return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2235 EndLoc);
2236 }
2237
2238 /// Build a new OpenMP 'exclusive' clause.
2239 ///
2240 /// By default, performs semantic analysis to build the new OpenMP clause.
2241 /// Subclasses may override this routine to provide different behavior.
2242 OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2243 SourceLocation StartLoc,
2244 SourceLocation LParenLoc,
2245 SourceLocation EndLoc) {
2246 return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2247 EndLoc);
2248 }
2249
2250 /// Build a new OpenMP 'uses_allocators' clause.
2251 ///
2252 /// By default, performs semantic analysis to build the new OpenMP clause.
2253 /// Subclasses may override this routine to provide different behavior.
2254 OMPClause *RebuildOMPUsesAllocatorsClause(
2255 ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2256 SourceLocation LParenLoc, SourceLocation EndLoc) {
2257 return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2258 Data);
2259 }
2260
2261 /// Build a new OpenMP 'affinity' clause.
2262 ///
2263 /// By default, performs semantic analysis to build the new OpenMP clause.
2264 /// Subclasses may override this routine to provide different behavior.
2265 OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2266 SourceLocation LParenLoc,
2267 SourceLocation ColonLoc,
2268 SourceLocation EndLoc, Expr *Modifier,
2269 ArrayRef<Expr *> Locators) {
2270 return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2271 EndLoc, Modifier, Locators);
2272 }
2273
2274 /// Build a new OpenMP 'order' clause.
2275 ///
2276 /// By default, performs semantic analysis to build the new OpenMP clause.
2277 /// Subclasses may override this routine to provide different behavior.
2278 OMPClause *RebuildOMPOrderClause(
2279 OpenMPOrderClauseKind Kind, SourceLocation KindKwLoc,
2280 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
2281 OpenMPOrderClauseModifier Modifier, SourceLocation ModifierKwLoc) {
2282 return getSema().ActOnOpenMPOrderClause(Modifier, Kind, StartLoc, LParenLoc,
2283 ModifierKwLoc, KindKwLoc, EndLoc);
2284 }
2285
2286 /// Build a new OpenMP 'init' clause.
2287 ///
2288 /// By default, performs semantic analysis to build the new OpenMP clause.
2289 /// Subclasses may override this routine to provide different behavior.
2290 OMPClause *RebuildOMPInitClause(Expr *InteropVar, OMPInteropInfo &InteropInfo,
2291 SourceLocation StartLoc,
2292 SourceLocation LParenLoc,
2293 SourceLocation VarLoc,
2294 SourceLocation EndLoc) {
2295 return getSema().ActOnOpenMPInitClause(InteropVar, InteropInfo, StartLoc,
2296 LParenLoc, VarLoc, EndLoc);
2297 }
2298
2299 /// Build a new OpenMP 'use' clause.
2300 ///
2301 /// By default, performs semantic analysis to build the new OpenMP clause.
2302 /// Subclasses may override this routine to provide different behavior.
2303 OMPClause *RebuildOMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
2304 SourceLocation LParenLoc,
2305 SourceLocation VarLoc, SourceLocation EndLoc) {
2306 return getSema().ActOnOpenMPUseClause(InteropVar, StartLoc, LParenLoc,
2307 VarLoc, EndLoc);
2308 }
2309
2310 /// Build a new OpenMP 'destroy' clause.
2311 ///
2312 /// By default, performs semantic analysis to build the new OpenMP clause.
2313 /// Subclasses may override this routine to provide different behavior.
2314 OMPClause *RebuildOMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
2315 SourceLocation LParenLoc,
2316 SourceLocation VarLoc,
2317 SourceLocation EndLoc) {
2318 return getSema().ActOnOpenMPDestroyClause(InteropVar, StartLoc, LParenLoc,
2319 VarLoc, EndLoc);
2320 }
2321
2322 /// Build a new OpenMP 'novariants' clause.
2323 ///
2324 /// By default, performs semantic analysis to build the new OpenMP clause.
2325 /// Subclasses may override this routine to provide different behavior.
2326 OMPClause *RebuildOMPNovariantsClause(Expr *Condition,
2327 SourceLocation StartLoc,
2328 SourceLocation LParenLoc,
2329 SourceLocation EndLoc) {
2330 return getSema().ActOnOpenMPNovariantsClause(Condition, StartLoc, LParenLoc,
2331 EndLoc);
2332 }
2333
2334 /// Build a new OpenMP 'nocontext' clause.
2335 ///
2336 /// By default, performs semantic analysis to build the new OpenMP clause.
2337 /// Subclasses may override this routine to provide different behavior.
2338 OMPClause *RebuildOMPNocontextClause(Expr *Condition, SourceLocation StartLoc,
2339 SourceLocation LParenLoc,
2340 SourceLocation EndLoc) {
2341 return getSema().ActOnOpenMPNocontextClause(Condition, StartLoc, LParenLoc,
2342 EndLoc);
2343 }
2344
2345 /// Build a new OpenMP 'filter' clause.
2346 ///
2347 /// By default, performs semantic analysis to build the new OpenMP clause.
2348 /// Subclasses may override this routine to provide different behavior.
2349 OMPClause *RebuildOMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
2350 SourceLocation LParenLoc,
2351 SourceLocation EndLoc) {
2352 return getSema().ActOnOpenMPFilterClause(ThreadID, StartLoc, LParenLoc,
2353 EndLoc);
2354 }
2355
2356 /// Build a new OpenMP 'bind' clause.
2357 ///
2358 /// By default, performs semantic analysis to build the new OpenMP clause.
2359 /// Subclasses may override this routine to provide different behavior.
2360 OMPClause *RebuildOMPBindClause(OpenMPBindClauseKind Kind,
2361 SourceLocation KindLoc,
2362 SourceLocation StartLoc,
2363 SourceLocation LParenLoc,
2364 SourceLocation EndLoc) {
2365 return getSema().ActOnOpenMPBindClause(Kind, KindLoc, StartLoc, LParenLoc,
2366 EndLoc);
2367 }
2368
2369 /// Build a new OpenMP 'ompx_dyn_cgroup_mem' clause.
2370 ///
2371 /// By default, performs semantic analysis to build the new OpenMP clause.
2372 /// Subclasses may override this routine to provide different behavior.
2373 OMPClause *RebuildOMPXDynCGroupMemClause(Expr *Size, SourceLocation StartLoc,
2374 SourceLocation LParenLoc,
2375 SourceLocation EndLoc) {
2376 return getSema().ActOnOpenMPXDynCGroupMemClause(Size, StartLoc, LParenLoc,
2377 EndLoc);
2378 }
2379
2380 /// Build a new OpenMP 'align' clause.
2381 ///
2382 /// By default, performs semantic analysis to build the new OpenMP clause.
2383 /// Subclasses may override this routine to provide different behavior.
2384 OMPClause *RebuildOMPAlignClause(Expr *A, SourceLocation StartLoc,
2385 SourceLocation LParenLoc,
2386 SourceLocation EndLoc) {
2387 return getSema().ActOnOpenMPAlignClause(A, StartLoc, LParenLoc, EndLoc);
2388 }
2389
2390 /// Build a new OpenMP 'at' clause.
2391 ///
2392 /// By default, performs semantic analysis to build the new OpenMP clause.
2393 /// Subclasses may override this routine to provide different behavior.
2394 OMPClause *RebuildOMPAtClause(OpenMPAtClauseKind Kind, SourceLocation KwLoc,
2395 SourceLocation StartLoc,
2396 SourceLocation LParenLoc,
2397 SourceLocation EndLoc) {
2398 return getSema().ActOnOpenMPAtClause(Kind, KwLoc, StartLoc, LParenLoc,
2399 EndLoc);
2400 }
2401
2402 /// Build a new OpenMP 'severity' clause.
2403 ///
2404 /// By default, performs semantic analysis to build the new OpenMP clause.
2405 /// Subclasses may override this routine to provide different behavior.
2406 OMPClause *RebuildOMPSeverityClause(OpenMPSeverityClauseKind Kind,
2407 SourceLocation KwLoc,
2408 SourceLocation StartLoc,
2409 SourceLocation LParenLoc,
2410 SourceLocation EndLoc) {
2411 return getSema().ActOnOpenMPSeverityClause(Kind, KwLoc, StartLoc, LParenLoc,
2412 EndLoc);
2413 }
2414
2415 /// Build a new OpenMP 'message' clause.
2416 ///
2417 /// By default, performs semantic analysis to build the new OpenMP clause.
2418 /// Subclasses may override this routine to provide different behavior.
2419 OMPClause *RebuildOMPMessageClause(Expr *MS, SourceLocation StartLoc,
2420 SourceLocation LParenLoc,
2421 SourceLocation EndLoc) {
2422 return getSema().ActOnOpenMPMessageClause(MS, StartLoc, LParenLoc, EndLoc);
2423 }
2424
2425 /// Rebuild the operand to an Objective-C \@synchronized statement.
2426 ///
2427 /// By default, performs semantic analysis to build the new statement.
2428 /// Subclasses may override this routine to provide different behavior.
2429 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2430 Expr *object) {
2431 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2432 }
2433
2434 /// Build a new Objective-C \@synchronized statement.
2435 ///
2436 /// By default, performs semantic analysis to build the new statement.
2437 /// Subclasses may override this routine to provide different behavior.
2438 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2439 Expr *Object, Stmt *Body) {
2440 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2441 }
2442
2443 /// Build a new Objective-C \@autoreleasepool statement.
2444 ///
2445 /// By default, performs semantic analysis to build the new statement.
2446 /// Subclasses may override this routine to provide different behavior.
2447 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2448 Stmt *Body) {
2449 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2450 }
2451
2452 /// Build a new Objective-C fast enumeration statement.
2453 ///
2454 /// By default, performs semantic analysis to build the new statement.
2455 /// Subclasses may override this routine to provide different behavior.
2456 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2457 Stmt *Element,
2458 Expr *Collection,
2459 SourceLocation RParenLoc,
2460 Stmt *Body) {
2461 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2462 Element,
2463 Collection,
2464 RParenLoc);
2465 if (ForEachStmt.isInvalid())
2466 return StmtError();
2467
2468 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2469 }
2470
2471 /// Build a new C++ exception declaration.
2472 ///
2473 /// By default, performs semantic analysis to build the new decaration.
2474 /// Subclasses may override this routine to provide different behavior.
2475 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2476 TypeSourceInfo *Declarator,
2477 SourceLocation StartLoc,
2478 SourceLocation IdLoc,
2479 IdentifierInfo *Id) {
2480 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2481 StartLoc, IdLoc, Id);
2482 if (Var)
2483 getSema().CurContext->addDecl(Var);
2484 return Var;
2485 }
2486
2487 /// Build a new C++ catch statement.
2488 ///
2489 /// By default, performs semantic analysis to build the new statement.
2490 /// Subclasses may override this routine to provide different behavior.
2491 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2492 VarDecl *ExceptionDecl,
2493 Stmt *Handler) {
2494 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2495 Handler));
2496 }
2497
2498 /// Build a new C++ try statement.
2499 ///
2500 /// By default, performs semantic analysis to build the new statement.
2501 /// Subclasses may override this routine to provide different behavior.
2502 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2503 ArrayRef<Stmt *> Handlers) {
2504 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2505 }
2506
2507 /// Build a new C++0x range-based for statement.
2508 ///
2509 /// By default, performs semantic analysis to build the new statement.
2510 /// Subclasses may override this routine to provide different behavior.
2511 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2512 SourceLocation CoawaitLoc, Stmt *Init,
2513 SourceLocation ColonLoc, Stmt *Range,
2514 Stmt *Begin, Stmt *End, Expr *Cond,
2515 Expr *Inc, Stmt *LoopVar,
2516 SourceLocation RParenLoc) {
2517 // If we've just learned that the range is actually an Objective-C
2518 // collection, treat this as an Objective-C fast enumeration loop.
2519 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2520 if (RangeStmt->isSingleDecl()) {
2521 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2522 if (RangeVar->isInvalidDecl())
2523 return StmtError();
2524
2525 Expr *RangeExpr = RangeVar->getInit();
2526 if (!RangeExpr->isTypeDependent() &&
2527 RangeExpr->getType()->isObjCObjectPointerType()) {
2528 // FIXME: Support init-statements in Objective-C++20 ranged for
2529 // statement.
2530 if (Init) {
2531 return SemaRef.Diag(Init->getBeginLoc(),
2532 diag::err_objc_for_range_init_stmt)
2533 << Init->getSourceRange();
2534 }
2535 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2536 RangeExpr, RParenLoc);
2537 }
2538 }
2539 }
2540 }
2541
2542 return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2543 Range, Begin, End, Cond, Inc, LoopVar,
2544 RParenLoc, Sema::BFRK_Rebuild);
2545 }
2546
2547 /// Build a new C++0x range-based for statement.
2548 ///
2549 /// By default, performs semantic analysis to build the new statement.
2550 /// Subclasses may override this routine to provide different behavior.
2551 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2552 bool IsIfExists,
2553 NestedNameSpecifierLoc QualifierLoc,
2554 DeclarationNameInfo NameInfo,
2555 Stmt *Nested) {
2556 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2557 QualifierLoc, NameInfo, Nested);
2558 }
2559
2560 /// Attach body to a C++0x range-based for statement.
2561 ///
2562 /// By default, performs semantic analysis to finish the new statement.
2563 /// Subclasses may override this routine to provide different behavior.
2564 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2565 return getSema().FinishCXXForRangeStmt(ForRange, Body);
2566 }
2567
2568 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2569 Stmt *TryBlock, Stmt *Handler) {
2570 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2571 }
2572
2573 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2574 Stmt *Block) {
2575 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2576 }
2577
2578 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2579 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2580 }
2581
2582 ExprResult RebuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
2583 SourceLocation LParen,
2584 SourceLocation RParen,
2585 TypeSourceInfo *TSI) {
2586 return getSema().BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
2587 }
2588
2589 /// Build a new predefined expression.
2590 ///
2591 /// By default, performs semantic analysis to build the new expression.
2592 /// Subclasses may override this routine to provide different behavior.
2593 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2594 PredefinedExpr::IdentKind IK) {
2595 return getSema().BuildPredefinedExpr(Loc, IK);
2596 }
2597
2598 /// Build a new expression that references a declaration.
2599 ///
2600 /// By default, performs semantic analysis to build the new expression.
2601 /// Subclasses may override this routine to provide different behavior.
2602 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2603 LookupResult &R,
2604 bool RequiresADL) {
2605 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2606 }
2607
2608
2609 /// Build a new expression that references a declaration.
2610 ///
2611 /// By default, performs semantic analysis to build the new expression.
2612 /// Subclasses may override this routine to provide different behavior.
2613 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2614 ValueDecl *VD,
2615 const DeclarationNameInfo &NameInfo,
2616 NamedDecl *Found,
2617 TemplateArgumentListInfo *TemplateArgs) {
2618 CXXScopeSpec SS;
2619 SS.Adopt(QualifierLoc);
2620 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2621 TemplateArgs);
2622 }
2623
2624 /// Build a new expression in parentheses.
2625 ///
2626 /// By default, performs semantic analysis to build the new expression.
2627 /// Subclasses may override this routine to provide different behavior.
2628 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2629 SourceLocation RParen) {
2630 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2631 }
2632
2633 /// Build a new pseudo-destructor expression.
2634 ///
2635 /// By default, performs semantic analysis to build the new expression.
2636 /// Subclasses may override this routine to provide different behavior.
2637 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2638 SourceLocation OperatorLoc,
2639 bool isArrow,
2640 CXXScopeSpec &SS,
2641 TypeSourceInfo *ScopeType,
2642 SourceLocation CCLoc,
2643 SourceLocation TildeLoc,
2644 PseudoDestructorTypeStorage Destroyed);
2645
2646 /// Build a new unary operator expression.
2647 ///
2648 /// By default, performs semantic analysis to build the new expression.
2649 /// Subclasses may override this routine to provide different behavior.
2650 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2651 UnaryOperatorKind Opc,
2652 Expr *SubExpr) {
2653 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2654 }
2655
2656 /// Build a new builtin offsetof expression.
2657 ///
2658 /// By default, performs semantic analysis to build the new expression.
2659 /// Subclasses may override this routine to provide different behavior.
2660 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2661 TypeSourceInfo *Type,
2662 ArrayRef<Sema::OffsetOfComponent> Components,
2663 SourceLocation RParenLoc) {
2664 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2665 RParenLoc);
2666 }
2667
2668 /// Build a new sizeof, alignof or vec_step expression with a
2669 /// type argument.
2670 ///
2671 /// By default, performs semantic analysis to build the new expression.
2672 /// Subclasses may override this routine to provide different behavior.
2673 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2674 SourceLocation OpLoc,
2675 UnaryExprOrTypeTrait ExprKind,
2676 SourceRange R) {
2677 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2678 }
2679
2680 /// Build a new sizeof, alignof or vec step expression with an
2681 /// expression argument.
2682 ///
2683 /// By default, performs semantic analysis to build the new expression.
2684 /// Subclasses may override this routine to provide different behavior.
2685 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2686 UnaryExprOrTypeTrait ExprKind,
2687 SourceRange R) {
2688 ExprResult Result
2689 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2690 if (Result.isInvalid())
2691 return ExprError();
2692
2693 return Result;
2694 }
2695
2696 /// Build a new array subscript expression.
2697 ///
2698 /// By default, performs semantic analysis to build the new expression.
2699 /// Subclasses may override this routine to provide different behavior.
2700 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2701 SourceLocation LBracketLoc,
2702 Expr *RHS,
2703 SourceLocation RBracketLoc) {
2704 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2705 LBracketLoc, RHS,
2706 RBracketLoc);
2707 }
2708
2709 /// Build a new matrix subscript expression.
2710 ///
2711 /// By default, performs semantic analysis to build the new expression.
2712 /// Subclasses may override this routine to provide different behavior.
2713 ExprResult RebuildMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
2714 Expr *ColumnIdx,
2715 SourceLocation RBracketLoc) {
2716 return getSema().CreateBuiltinMatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
2717 RBracketLoc);
2718 }
2719
2720 /// Build a new array section expression.
2721 ///
2722 /// By default, performs semantic analysis to build the new expression.
2723 /// Subclasses may override this routine to provide different behavior.
2724 ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2725 Expr *LowerBound,
2726 SourceLocation ColonLocFirst,
2727 SourceLocation ColonLocSecond,
2728 Expr *Length, Expr *Stride,
2729 SourceLocation RBracketLoc) {
2730 return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2731 ColonLocFirst, ColonLocSecond,
2732 Length, Stride, RBracketLoc);
2733 }
2734
2735 /// Build a new array shaping expression.
2736 ///
2737 /// By default, performs semantic analysis to build the new expression.
2738 /// Subclasses may override this routine to provide different behavior.
2739 ExprResult RebuildOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
2740 SourceLocation RParenLoc,
2741 ArrayRef<Expr *> Dims,
2742 ArrayRef<SourceRange> BracketsRanges) {
2743 return getSema().ActOnOMPArrayShapingExpr(Base, LParenLoc, RParenLoc, Dims,
2744 BracketsRanges);
2745 }
2746
2747 /// Build a new iterator expression.
2748 ///
2749 /// By default, performs semantic analysis to build the new expression.
2750 /// Subclasses may override this routine to provide different behavior.
2751 ExprResult RebuildOMPIteratorExpr(
2752 SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc,
2753 ArrayRef<Sema::OMPIteratorData> Data) {
2754 return getSema().ActOnOMPIteratorExpr(/*Scope=*/nullptr, IteratorKwLoc,
2755 LLoc, RLoc, Data);
2756 }
2757
2758 /// Build a new call expression.
2759 ///
2760 /// By default, performs semantic analysis to build the new expression.
2761 /// Subclasses may override this routine to provide different behavior.
2762 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2763 MultiExprArg Args,
2764 SourceLocation RParenLoc,
2765 Expr *ExecConfig = nullptr) {
2766 return getSema().ActOnCallExpr(
2767 /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc, ExecConfig);
2768 }
2769
2770 ExprResult RebuildCxxSubscriptExpr(Expr *Callee, SourceLocation LParenLoc,
2771 MultiExprArg Args,
2772 SourceLocation RParenLoc) {
2773 return getSema().ActOnArraySubscriptExpr(
18
Calling 'Sema::ActOnArraySubscriptExpr'
2774 /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc);
17
Passing value via 2nd parameter 'base'
2775 }
2776
2777 /// Build a new member access expression.
2778 ///
2779 /// By default, performs semantic analysis to build the new expression.
2780 /// Subclasses may override this routine to provide different behavior.
2781 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2782 bool isArrow,
2783 NestedNameSpecifierLoc QualifierLoc,
2784 SourceLocation TemplateKWLoc,
2785 const DeclarationNameInfo &MemberNameInfo,
2786 ValueDecl *Member,
2787 NamedDecl *FoundDecl,
2788 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2789 NamedDecl *FirstQualifierInScope) {
2790 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2791 isArrow);
2792 if (!Member->getDeclName()) {
2793 // We have a reference to an unnamed field. This is always the
2794 // base of an anonymous struct/union member access, i.e. the
2795 // field is always of record type.
2796 assert(Member->getType()->isRecordType() &&(static_cast <bool> (Member->getType()->isRecordType
() && "unnamed member not of record type?") ? void (0
) : __assert_fail ("Member->getType()->isRecordType() && \"unnamed member not of record type?\""
, "clang/lib/Sema/TreeTransform.h", 2797, __extension__ __PRETTY_FUNCTION__
))
2797 "unnamed member not of record type?")(static_cast <bool> (Member->getType()->isRecordType
() && "unnamed member not of record type?") ? void (0
) : __assert_fail ("Member->getType()->isRecordType() && \"unnamed member not of record type?\""
, "clang/lib/Sema/TreeTransform.h", 2797, __extension__ __PRETTY_FUNCTION__
))
;
2798
2799 BaseResult =
2800 getSema().PerformObjectMemberConversion(BaseResult.get(),
2801 QualifierLoc.getNestedNameSpecifier(),
2802 FoundDecl, Member);
2803 if (BaseResult.isInvalid())
2804 return ExprError();
2805 Base = BaseResult.get();
2806
2807 CXXScopeSpec EmptySS;
2808 return getSema().BuildFieldReferenceExpr(
2809 Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2810 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2811 }
2812
2813 CXXScopeSpec SS;
2814 SS.Adopt(QualifierLoc);
2815
2816 Base = BaseResult.get();
2817 QualType BaseType = Base->getType();
2818
2819 if (isArrow && !BaseType->isPointerType())
2820 return ExprError();
2821
2822 // FIXME: this involves duplicating earlier analysis in a lot of
2823 // cases; we should avoid this when possible.
2824 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2825 R.addDecl(FoundDecl);
2826 R.resolveKind();
2827
2828 if (getSema().isUnevaluatedContext() && Base->isImplicitCXXThis() &&
2829 isa<FieldDecl, IndirectFieldDecl, MSPropertyDecl>(Member)) {
2830 if (auto *ThisClass = cast<CXXThisExpr>(Base)
2831 ->getType()
2832 ->getPointeeType()
2833 ->getAsCXXRecordDecl()) {
2834 auto *Class = cast<CXXRecordDecl>(Member->getDeclContext());
2835 // In unevaluated contexts, an expression supposed to be a member access
2836 // might reference a member in an unrelated class.
2837 if (!ThisClass->Equals(Class) && !ThisClass->isDerivedFrom(Class))
2838 return getSema().BuildDeclRefExpr(Member, Member->getType(),
2839 VK_LValue, Member->getLocation());
2840 }
2841 }
2842
2843 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2844 SS, TemplateKWLoc,
2845 FirstQualifierInScope,
2846 R, ExplicitTemplateArgs,
2847 /*S*/nullptr);
2848 }
2849
2850 /// Build a new binary operator expression.
2851 ///
2852 /// By default, performs semantic analysis to build the new expression.
2853 /// Subclasses may override this routine to provide different behavior.
2854 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2855 BinaryOperatorKind Opc,
2856 Expr *LHS, Expr *RHS) {
2857 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2858 }
2859
2860 /// Build a new rewritten operator expression.
2861 ///
2862 /// By default, performs semantic analysis to build the new expression.
2863 /// Subclasses may override this routine to provide different behavior.
2864 ExprResult RebuildCXXRewrittenBinaryOperator(
2865 SourceLocation OpLoc, BinaryOperatorKind Opcode,
2866 const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2867 return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2868 RHS, /*RequiresADL*/false);
2869 }
2870
2871 /// Build a new conditional operator expression.
2872 ///
2873 /// By default, performs semantic analysis to build the new expression.
2874 /// Subclasses may override this routine to provide different behavior.
2875 ExprResult RebuildConditionalOperator(Expr *Cond,
2876 SourceLocation QuestionLoc,
2877 Expr *LHS,
2878 SourceLocation ColonLoc,
2879 Expr *RHS) {
2880 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2881 LHS, RHS);
2882 }
2883
2884 /// Build a new C-style cast expression.
2885 ///
2886 /// By default, performs semantic analysis to build the new expression.
2887 /// Subclasses may override this routine to provide different behavior.
2888 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2889 TypeSourceInfo *TInfo,
2890 SourceLocation RParenLoc,
2891 Expr *SubExpr) {
2892 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2893 SubExpr);
2894 }
2895
2896 /// Build a new compound literal expression.
2897 ///
2898 /// By default, performs semantic analysis to build the new expression.
2899 /// Subclasses may override this routine to provide different behavior.
2900 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2901 TypeSourceInfo *TInfo,
2902 SourceLocation RParenLoc,
2903 Expr *Init) {
2904 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2905 Init);
2906 }
2907
2908 /// Build a new extended vector element access expression.
2909 ///
2910 /// By default, performs semantic analysis to build the new expression.
2911 /// Subclasses may override this routine to provide different behavior.
2912 ExprResult RebuildExtVectorElementExpr(Expr *Base, SourceLocation OpLoc,
2913 bool IsArrow,
2914 SourceLocation AccessorLoc,
2915 IdentifierInfo &Accessor) {
2916
2917 CXXScopeSpec SS;
2918 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2919 return getSema().BuildMemberReferenceExpr(
2920 Base, Base->getType(), OpLoc, IsArrow, SS, SourceLocation(),
2921 /*FirstQualifierInScope*/ nullptr, NameInfo,
2922 /* TemplateArgs */ nullptr,
2923 /*S*/ nullptr);
2924 }
2925
2926 /// Build a new initializer list expression.
2927 ///
2928 /// By default, performs semantic analysis to build the new expression.
2929 /// Subclasses may override this routine to provide different behavior.
2930 ExprResult RebuildInitList(SourceLocation LBraceLoc,
2931 MultiExprArg Inits,
2932 SourceLocation RBraceLoc) {
2933 return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2934 }
2935
2936 /// Build a new designated initializer expression.
2937 ///
2938 /// By default, performs semantic analysis to build the new expression.
2939 /// Subclasses may override this routine to provide different behavior.
2940 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2941 MultiExprArg ArrayExprs,
2942 SourceLocation EqualOrColonLoc,
2943 bool GNUSyntax,
2944 Expr *Init) {
2945 ExprResult Result
2946 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2947 Init);
2948 if (Result.isInvalid())
2949 return ExprError();
2950
2951 return Result;
2952 }
2953
2954 /// Build a new value-initialized expression.
2955 ///
2956 /// By default, builds the implicit value initialization without performing
2957 /// any semantic analysis. Subclasses may override this routine to provide
2958 /// different behavior.
2959 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2960 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2961 }
2962
2963 /// Build a new \c va_arg expression.
2964 ///
2965 /// By default, performs semantic analysis to build the new expression.
2966 /// Subclasses may override this routine to provide different behavior.
2967 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2968 Expr *SubExpr, TypeSourceInfo *TInfo,
2969 SourceLocation RParenLoc) {
2970 return getSema().BuildVAArgExpr(BuiltinLoc,
2971 SubExpr, TInfo,
2972 RParenLoc);
2973 }
2974
2975 /// Build a new expression list in parentheses.
2976 ///
2977 /// By default, performs semantic analysis to build the new expression.
2978 /// Subclasses may override this routine to provide different behavior.
2979 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2980 MultiExprArg SubExprs,
2981 SourceLocation RParenLoc) {
2982 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2983 }
2984
2985 /// Build a new address-of-label expression.
2986 ///
2987 /// By default, performs semantic analysis, using the name of the label
2988 /// rather than attempting to map the label statement itself.
2989 /// Subclasses may override this routine to provide different behavior.
2990 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2991 SourceLocation LabelLoc, LabelDecl *Label) {
2992 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2993 }
2994
2995 /// Build a new GNU statement expression.
2996 ///
2997 /// By default, performs semantic analysis to build the new expression.
2998 /// Subclasses may override this routine to provide different behavior.
2999 ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
3000 SourceLocation RParenLoc, unsigned TemplateDepth) {
3001 return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
3002 TemplateDepth);
3003 }
3004
3005 /// Build a new __builtin_choose_expr expression.
3006 ///
3007 /// By default, performs semantic analysis to build the new expression.
3008 /// Subclasses may override this routine to provide different behavior.
3009 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
3010 Expr *Cond, Expr *LHS, Expr *RHS,
3011 SourceLocation RParenLoc) {
3012 return SemaRef.ActOnChooseExpr(BuiltinLoc,
3013 Cond, LHS, RHS,
3014 RParenLoc);
3015 }
3016
3017 /// Build a new generic selection expression.
3018 ///
3019 /// By default, performs semantic analysis to build the new expression.
3020 /// Subclasses may override this routine to provide different behavior.
3021 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
3022 SourceLocation DefaultLoc,
3023 SourceLocation RParenLoc,
3024 Expr *ControllingExpr,
3025 ArrayRef<TypeSourceInfo *> Types,
3026 ArrayRef<Expr *> Exprs) {
3027 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
3028 ControllingExpr, Types, Exprs);
3029 }
3030
3031 /// Build a new overloaded operator call expression.
3032 ///
3033 /// By default, performs semantic analysis to build the new expression.
3034 /// The semantic analysis provides the behavior of template instantiation,
3035 /// copying with transformations that turn what looks like an overloaded
3036 /// operator call into a use of a builtin operator, performing
3037 /// argument-dependent lookup, etc. Subclasses may override this routine to
3038 /// provide different behavior.
3039 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
3040 SourceLocation OpLoc,
3041 Expr *Callee,
3042 Expr *First,
3043 Expr *Second);
3044
3045 /// Build a new C++ "named" cast expression, such as static_cast or
3046 /// reinterpret_cast.
3047 ///
3048 /// By default, this routine dispatches to one of the more-specific routines
3049 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
3050 /// Subclasses may override this routine to provide different behavior.
3051 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
3052 Stmt::StmtClass Class,
3053 SourceLocation LAngleLoc,
3054 TypeSourceInfo *TInfo,
3055 SourceLocation RAngleLoc,
3056 SourceLocation LParenLoc,
3057 Expr *SubExpr,
3058 SourceLocation RParenLoc) {
3059 switch (Class) {
3060 case Stmt::CXXStaticCastExprClass:
3061 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
3062 RAngleLoc, LParenLoc,
3063 SubExpr, RParenLoc);
3064
3065 case Stmt::CXXDynamicCastExprClass:
3066 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
3067 RAngleLoc, LParenLoc,
3068 SubExpr, RParenLoc);
3069
3070 case Stmt::CXXReinterpretCastExprClass:
3071 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
3072 RAngleLoc, LParenLoc,
3073 SubExpr,
3074 RParenLoc);
3075
3076 case Stmt::CXXConstCastExprClass:
3077 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
3078 RAngleLoc, LParenLoc,
3079 SubExpr, RParenLoc);
3080
3081 case Stmt::CXXAddrspaceCastExprClass:
3082 return getDerived().RebuildCXXAddrspaceCastExpr(
3083 OpLoc, LAngleLoc, TInfo, RAngleLoc, LParenLoc, SubExpr, RParenLoc);
3084
3085 default:
3086 llvm_unreachable("Invalid C++ named cast")::llvm::llvm_unreachable_internal("Invalid C++ named cast", "clang/lib/Sema/TreeTransform.h"
, 3086)
;
3087 }
3088 }
3089
3090 /// Build a new C++ static_cast expression.
3091 ///
3092 /// By default, performs semantic analysis to build the new expression.
3093 /// Subclasses may override this routine to provide different behavior.
3094 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
3095 SourceLocation LAngleLoc,
3096 TypeSourceInfo *TInfo,
3097 SourceLocation RAngleLoc,
3098 SourceLocation LParenLoc,
3099 Expr *SubExpr,
3100 SourceLocation RParenLoc) {
3101 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
3102 TInfo, SubExpr,
3103 SourceRange(LAngleLoc, RAngleLoc),
3104 SourceRange(LParenLoc, RParenLoc));
3105 }
3106
3107 /// Build a new C++ dynamic_cast expression.
3108 ///
3109 /// By default, performs semantic analysis to build the new expression.
3110 /// Subclasses may override this routine to provide different behavior.
3111 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
3112 SourceLocation LAngleLoc,
3113 TypeSourceInfo *TInfo,
3114 SourceLocation RAngleLoc,
3115 SourceLocation LParenLoc,
3116 Expr *SubExpr,
3117 SourceLocation RParenLoc) {
3118 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
3119 TInfo, SubExpr,
3120 SourceRange(LAngleLoc, RAngleLoc),
3121 SourceRange(LParenLoc, RParenLoc));
3122 }
3123
3124 /// Build a new C++ reinterpret_cast expression.
3125 ///
3126 /// By default, performs semantic analysis to build the new expression.
3127 /// Subclasses may override this routine to provide different behavior.
3128 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
3129 SourceLocation LAngleLoc,
3130 TypeSourceInfo *TInfo,
3131 SourceLocation RAngleLoc,
3132 SourceLocation LParenLoc,
3133 Expr *SubExpr,
3134 SourceLocation RParenLoc) {
3135 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
3136 TInfo, SubExpr,
3137 SourceRange(LAngleLoc, RAngleLoc),
3138 SourceRange(LParenLoc, RParenLoc));
3139 }
3140
3141 /// Build a new C++ const_cast expression.
3142 ///
3143 /// By default, performs semantic analysis to build the new expression.
3144 /// Subclasses may override this routine to provide different behavior.
3145 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
3146 SourceLocation LAngleLoc,
3147 TypeSourceInfo *TInfo,
3148 SourceLocation RAngleLoc,
3149 SourceLocation LParenLoc,
3150 Expr *SubExpr,
3151 SourceLocation RParenLoc) {
3152 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
3153 TInfo, SubExpr,
3154 SourceRange(LAngleLoc, RAngleLoc),
3155 SourceRange(LParenLoc, RParenLoc));
3156 }
3157
3158 ExprResult
3159 RebuildCXXAddrspaceCastExpr(SourceLocation OpLoc, SourceLocation LAngleLoc,
3160 TypeSourceInfo *TInfo, SourceLocation RAngleLoc,
3161 SourceLocation LParenLoc, Expr *SubExpr,
3162 SourceLocation RParenLoc) {
3163 return getSema().BuildCXXNamedCast(
3164 OpLoc, tok::kw_addrspace_cast, TInfo, SubExpr,
3165 SourceRange(LAngleLoc, RAngleLoc), SourceRange(LParenLoc, RParenLoc));
3166 }
3167
3168 /// Build a new C++ functional-style cast expression.
3169 ///
3170 /// By default, performs semantic analysis to build the new expression.
3171 /// Subclasses may override this routine to provide different behavior.
3172 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
3173 SourceLocation LParenLoc,
3174 Expr *Sub,
3175 SourceLocation RParenLoc,
3176 bool ListInitialization) {
3177 // If Sub is a ParenListExpr, then Sub is the syntatic form of a
3178 // CXXParenListInitExpr. Pass its expanded arguments so that the
3179 // CXXParenListInitExpr can be rebuilt.
3180 if (auto *PLE = dyn_cast<ParenListExpr>(Sub))
3181 return getSema().BuildCXXTypeConstructExpr(
3182 TInfo, LParenLoc, MultiExprArg(PLE->getExprs(), PLE->getNumExprs()),
3183 RParenLoc, ListInitialization);
3184 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
3185 MultiExprArg(&Sub, 1), RParenLoc,
3186 ListInitialization);
3187 }
3188
3189 /// Build a new C++ __builtin_bit_cast expression.
3190 ///
3191 /// By default, performs semantic analysis to build the new expression.
3192 /// Subclasses may override this routine to provide different behavior.
3193 ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
3194 TypeSourceInfo *TSI, Expr *Sub,
3195 SourceLocation RParenLoc) {
3196 return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
3197 }
3198
3199 /// Build a new C++ typeid(type) expression.
3200 ///
3201 /// By default, performs semantic analysis to build the new expression.
3202 /// Subclasses may override this routine to provide different behavior.
3203 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3204 SourceLocation TypeidLoc,
3205 TypeSourceInfo *Operand,
3206 SourceLocation RParenLoc) {
3207 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3208 RParenLoc);
3209 }
3210
3211
3212 /// Build a new C++ typeid(expr) expression.
3213 ///
3214 /// By default, performs semantic analysis to build the new expression.
3215 /// Subclasses may override this routine to provide different behavior.
3216 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3217 SourceLocation TypeidLoc,
3218 Expr *Operand,
3219 SourceLocation RParenLoc) {
3220 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3221 RParenLoc);
3222 }
3223
3224 /// Build a new C++ __uuidof(type) expression.
3225 ///
3226 /// By default, performs semantic analysis to build the new expression.
3227 /// Subclasses may override this routine to provide different behavior.
3228 ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3229 TypeSourceInfo *Operand,
3230 SourceLocation RParenLoc) {
3231 return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3232 }
3233
3234 /// Build a new C++ __uuidof(expr) expression.
3235 ///
3236 /// By default, performs semantic analysis to build the new expression.
3237 /// Subclasses may override this routine to provide different behavior.
3238 ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3239 Expr *Operand, SourceLocation RParenLoc) {
3240 return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3241 }
3242
3243 /// Build a new C++ "this" expression.
3244 ///
3245 /// By default, builds a new "this" expression without performing any
3246 /// semantic analysis. Subclasses may override this routine to provide
3247 /// different behavior.
3248 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
3249 QualType ThisType,
3250 bool isImplicit) {
3251 return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
3252 }
3253
3254 /// Build a new C++ throw expression.
3255 ///
3256 /// By default, performs semantic analysis to build the new expression.
3257 /// Subclasses may override this routine to provide different behavior.
3258 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
3259 bool IsThrownVariableInScope) {
3260 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
3261 }
3262
3263 /// Build a new C++ default-argument expression.
3264 ///
3265 /// By default, builds a new default-argument expression, which does not
3266 /// require any semantic analysis. Subclasses may override this routine to
3267 /// provide different behavior.
3268 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param,
3269 Expr *RewrittenExpr) {
3270 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
3271 RewrittenExpr, getSema().CurContext);
3272 }
3273
3274 /// Build a new C++11 default-initialization expression.
3275 ///
3276 /// By default, builds a new default field initialization expression, which
3277 /// does not require any semantic analysis. Subclasses may override this
3278 /// routine to provide different behavior.
3279 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
3280 FieldDecl *Field) {
3281 return getSema().BuildCXXDefaultInitExpr(Loc, Field);
3282 }
3283
3284 /// Build a new C++ zero-initialization expression.
3285 ///
3286 /// By default, performs semantic analysis to build the new expression.
3287 /// Subclasses may override this routine to provide different behavior.
3288 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
3289 SourceLocation LParenLoc,
3290 SourceLocation RParenLoc) {
3291 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, std::nullopt,
3292 RParenLoc,
3293 /*ListInitialization=*/false);
3294 }
3295
3296 /// Build a new C++ "new" expression.
3297 ///
3298 /// By default, performs semantic analysis to build the new expression.
3299 /// Subclasses may override this routine to provide different behavior.
3300 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc, bool UseGlobal,
3301 SourceLocation PlacementLParen,
3302 MultiExprArg PlacementArgs,
3303 SourceLocation PlacementRParen,
3304 SourceRange TypeIdParens, QualType AllocatedType,
3305 TypeSourceInfo *AllocatedTypeInfo,
3306 std::optional<Expr *> ArraySize,
3307 SourceRange DirectInitRange, Expr *Initializer) {
3308 return getSema().BuildCXXNew(StartLoc, UseGlobal,
3309 PlacementLParen,
3310 PlacementArgs,
3311 PlacementRParen,
3312 TypeIdParens,
3313 AllocatedType,
3314 AllocatedTypeInfo,
3315 ArraySize,
3316 DirectInitRange,
3317 Initializer);
3318 }
3319
3320 /// Build a new C++ "delete" expression.
3321 ///
3322 /// By default, performs semantic analysis to build the new expression.
3323 /// Subclasses may override this routine to provide different behavior.
3324 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
3325 bool IsGlobalDelete,
3326 bool IsArrayForm,
3327 Expr *Operand) {
3328 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
3329 Operand);
3330 }
3331
3332 /// Build a new type trait expression.
3333 ///
3334 /// By default, performs semantic analysis to build the new expression.
3335 /// Subclasses may override this routine to provide different behavior.
3336 ExprResult RebuildTypeTrait(TypeTrait Trait,
3337 SourceLocation StartLoc,
3338 ArrayRef<TypeSourceInfo *> Args,
3339 SourceLocation RParenLoc) {
3340 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
3341 }
3342
3343 /// Build a new array type trait expression.
3344 ///
3345 /// By default, performs semantic analysis to build the new expression.
3346 /// Subclasses may override this routine to provide different behavior.
3347 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
3348 SourceLocation StartLoc,
3349 TypeSourceInfo *TSInfo,
3350 Expr *DimExpr,
3351 SourceLocation RParenLoc) {
3352 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
3353 }
3354
3355 /// Build a new expression trait expression.
3356 ///
3357 /// By default, performs semantic analysis to build the new expression.
3358 /// Subclasses may override this routine to provide different behavior.
3359 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
3360 SourceLocation StartLoc,
3361 Expr *Queried,
3362 SourceLocation RParenLoc) {
3363 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
3364 }
3365
3366 /// Build a new (previously unresolved) declaration reference
3367 /// expression.
3368 ///
3369 /// By default, performs semantic analysis to build the new expression.
3370 /// Subclasses may override this routine to provide different behavior.
3371 ExprResult RebuildDependentScopeDeclRefExpr(
3372 NestedNameSpecifierLoc QualifierLoc,
3373 SourceLocation TemplateKWLoc,
3374 const DeclarationNameInfo &NameInfo,
3375 const TemplateArgumentListInfo *TemplateArgs,
3376 bool IsAddressOfOperand,
3377 TypeSourceInfo **RecoveryTSI) {
3378 CXXScopeSpec SS;
3379 SS.Adopt(QualifierLoc);
3380
3381 if (TemplateArgs || TemplateKWLoc.isValid())
3382 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
3383 TemplateArgs);
3384
3385 return getSema().BuildQualifiedDeclarationNameExpr(
3386 SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
3387 }
3388
3389 /// Build a new template-id expression.
3390 ///
3391 /// By default, performs semantic analysis to build the new expression.
3392 /// Subclasses may override this routine to provide different behavior.
3393 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
3394 SourceLocation TemplateKWLoc,
3395 LookupResult &R,
3396 bool RequiresADL,
3397 const TemplateArgumentListInfo *TemplateArgs) {
3398 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
3399 TemplateArgs);
3400 }
3401
3402 /// Build a new object-construction expression.
3403 ///
3404 /// By default, performs semantic analysis to build the new expression.
3405 /// Subclasses may override this routine to provide different behavior.
3406 ExprResult RebuildCXXConstructExpr(QualType T,
3407 SourceLocation Loc,
3408 CXXConstructorDecl *Constructor,
3409 bool IsElidable,
3410 MultiExprArg Args,
3411 bool HadMultipleCandidates,
3412 bool ListInitialization,
3413 bool StdInitListInitialization,
3414 bool RequiresZeroInit,
3415 CXXConstructExpr::ConstructionKind ConstructKind,
3416 SourceRange ParenRange) {
3417 // Reconstruct the constructor we originally found, which might be
3418 // different if this is a call to an inherited constructor.
3419 CXXConstructorDecl *FoundCtor = Constructor;
3420 if (Constructor->isInheritingConstructor())
3421 FoundCtor = Constructor->getInheritedConstructor().getConstructor();
3422
3423 SmallVector<Expr *, 8> ConvertedArgs;
3424 if (getSema().CompleteConstructorCall(FoundCtor, T, Args, Loc,
3425 ConvertedArgs))
3426 return ExprError();
3427
3428 return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
3429 IsElidable,
3430 ConvertedArgs,
3431 HadMultipleCandidates,
3432 ListInitialization,
3433 StdInitListInitialization,
3434 RequiresZeroInit, ConstructKind,
3435 ParenRange);
3436 }
3437
3438 /// Build a new implicit construction via inherited constructor
3439 /// expression.
3440 ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
3441 CXXConstructorDecl *Constructor,
3442 bool ConstructsVBase,
3443 bool InheritedFromVBase) {
3444 return new (getSema().Context) CXXInheritedCtorInitExpr(
3445 Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
3446 }
3447
3448 /// Build a new object-construction expression.
3449 ///
3450 /// By default, performs semantic analysis to build the new expression.
3451 /// Subclasses may override this routine to provide different behavior.
3452 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
3453 SourceLocation LParenOrBraceLoc,
3454 MultiExprArg Args,
3455 SourceLocation RParenOrBraceLoc,
3456 bool ListInitialization) {
3457 return getSema().BuildCXXTypeConstructExpr(
3458 TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
3459 }
3460
3461 /// Build a new object-construction expression.
3462 ///
3463 /// By default, performs semantic analysis to build the new expression.
3464 /// Subclasses may override this routine to provide different behavior.
3465 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
3466 SourceLocation LParenLoc,
3467 MultiExprArg Args,
3468 SourceLocation RParenLoc,
3469 bool ListInitialization) {
3470 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
3471 RParenLoc, ListInitialization);
3472 }
3473
3474 /// Build a new member reference expression.
3475 ///
3476 /// By default, performs semantic analysis to build the new expression.
3477 /// Subclasses may override this routine to provide different behavior.
3478 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
3479 QualType BaseType,
3480 bool IsArrow,
3481 SourceLocation OperatorLoc,
3482 NestedNameSpecifierLoc QualifierLoc,
3483 SourceLocation TemplateKWLoc,
3484 NamedDecl *FirstQualifierInScope,
3485 const DeclarationNameInfo &MemberNameInfo,
3486 const TemplateArgumentListInfo *TemplateArgs) {
3487 CXXScopeSpec SS;
3488 SS.Adopt(QualifierLoc);
3489
3490 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3491 OperatorLoc, IsArrow,
3492 SS, TemplateKWLoc,
3493 FirstQualifierInScope,
3494 MemberNameInfo,
3495 TemplateArgs, /*S*/nullptr);
3496 }
3497
3498 /// Build a new member reference expression.
3499 ///
3500 /// By default, performs semantic analysis to build the new expression.
3501 /// Subclasses may override this routine to provide different behavior.
3502 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3503 SourceLocation OperatorLoc,
3504 bool IsArrow,
3505 NestedNameSpecifierLoc QualifierLoc,
3506 SourceLocation TemplateKWLoc,
3507 NamedDecl *FirstQualifierInScope,
3508 LookupResult &R,
3509 const TemplateArgumentListInfo *TemplateArgs) {
3510 CXXScopeSpec SS;
3511 SS.Adopt(QualifierLoc);
3512
3513 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3514 OperatorLoc, IsArrow,
3515 SS, TemplateKWLoc,
3516 FirstQualifierInScope,
3517 R, TemplateArgs, /*S*/nullptr);
3518 }
3519
3520 /// Build a new noexcept expression.
3521 ///
3522 /// By default, performs semantic analysis to build the new expression.
3523 /// Subclasses may override this routine to provide different behavior.
3524 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3525 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3526 }
3527
3528 /// Build a new expression to compute the length of a parameter pack.
3529 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
3530 SourceLocation PackLoc,
3531 SourceLocation RParenLoc,
3532 std::optional<unsigned> Length,
3533 ArrayRef<TemplateArgument> PartialArgs) {
3534 return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3535 RParenLoc, Length, PartialArgs);
3536 }
3537
3538 /// Build a new expression representing a call to a source location
3539 /// builtin.
3540 ///
3541 /// By default, performs semantic analysis to build the new expression.
3542 /// Subclasses may override this routine to provide different behavior.
3543 ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3544 QualType ResultTy, SourceLocation BuiltinLoc,
3545 SourceLocation RPLoc,
3546 DeclContext *ParentContext) {
3547 return getSema().BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc,
3548 ParentContext);
3549 }
3550
3551 /// Build a new Objective-C boxed expression.
3552 ///
3553 /// By default, performs semantic analysis to build the new expression.
3554 /// Subclasses may override this routine to provide different behavior.
3555 ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3556 SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3557 NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3558 TemplateArgumentListInfo *TALI) {
3559 CXXScopeSpec SS;
3560 SS.Adopt(NNS);
3561 ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3562 ConceptNameInfo,
3563 FoundDecl,
3564 NamedConcept, TALI);
3565 if (Result.isInvalid())
3566 return ExprError();
3567 return Result;
3568 }
3569
3570 /// \brief Build a new requires expression.
3571 ///
3572 /// By default, performs semantic analysis to build the new expression.
3573 /// Subclasses may override this routine to provide different behavior.
3574 ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3575 RequiresExprBodyDecl *Body,
3576 ArrayRef<ParmVarDecl *> LocalParameters,
3577 ArrayRef<concepts::Requirement *> Requirements,
3578 SourceLocation ClosingBraceLoc) {
3579 return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body,
3580 LocalParameters, Requirements, ClosingBraceLoc);
3581 }
3582
3583 concepts::TypeRequirement *
3584 RebuildTypeRequirement(
3585 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3586 return SemaRef.BuildTypeRequirement(SubstDiag);
3587 }
3588
3589 concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3590 return SemaRef.BuildTypeRequirement(T);
3591 }
3592
3593 concepts::ExprRequirement *
3594 RebuildExprRequirement(
3595 concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3596 SourceLocation NoexceptLoc,
3597 concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3598 return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3599 std::move(Ret));
3600 }
3601
3602 concepts::ExprRequirement *
3603 RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3604 concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3605 return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3606 std::move(Ret));
3607 }
3608
3609 concepts::NestedRequirement *
3610 RebuildNestedRequirement(StringRef InvalidConstraintEntity,
3611 const ASTConstraintSatisfaction &Satisfaction) {
3612 return SemaRef.BuildNestedRequirement(InvalidConstraintEntity,
3613 Satisfaction);
3614 }
3615
3616 concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3617 return SemaRef.BuildNestedRequirement(Constraint);
3618 }
3619
3620 /// \brief Build a new Objective-C boxed expression.
3621 ///
3622 /// By default, performs semantic analysis to build the new expression.
3623 /// Subclasses may override this routine to provide different behavior.
3624 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3625 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3626 }
3627
3628 /// Build a new Objective-C array literal.
3629 ///
3630 /// By default, performs semantic analysis to build the new expression.
3631 /// Subclasses may override this routine to provide different behavior.
3632 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3633 Expr **Elements, unsigned NumElements) {
3634 return getSema().BuildObjCArrayLiteral(Range,
3635 MultiExprArg(Elements, NumElements));
3636 }
3637
3638 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3639 Expr *Base, Expr *Key,
3640 ObjCMethodDecl *getterMethod,
3641 ObjCMethodDecl *setterMethod) {
3642 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3643 getterMethod, setterMethod);
3644 }
3645
3646 /// Build a new Objective-C dictionary literal.
3647 ///
3648 /// By default, performs semantic analysis to build the new expression.
3649 /// Subclasses may override this routine to provide different behavior.
3650 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3651 MutableArrayRef<ObjCDictionaryElement> Elements) {
3652 return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3653 }
3654
3655 /// Build a new Objective-C \@encode expression.
3656 ///
3657 /// By default, performs semantic analysis to build the new expression.
3658 /// Subclasses may override this routine to provide different behavior.
3659 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3660 TypeSourceInfo *EncodeTypeInfo,
3661 SourceLocation RParenLoc) {
3662 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3663 }
3664
3665 /// Build a new Objective-C class message.
3666 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3667 Selector Sel,
3668 ArrayRef<SourceLocation> SelectorLocs,
3669 ObjCMethodDecl *Method,
3670 SourceLocation LBracLoc,
3671 MultiExprArg Args,
3672 SourceLocation RBracLoc) {
3673 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3674 ReceiverTypeInfo->getType(),
3675 /*SuperLoc=*/SourceLocation(),
3676 Sel, Method, LBracLoc, SelectorLocs,
3677 RBracLoc, Args);
3678 }
3679
3680 /// Build a new Objective-C instance message.
3681 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3682 Selector Sel,
3683 ArrayRef<SourceLocation> SelectorLocs,
3684 ObjCMethodDecl *Method,
3685 SourceLocation LBracLoc,
3686 MultiExprArg Args,
3687 SourceLocation RBracLoc) {
3688 return SemaRef.BuildInstanceMessage(Receiver,
3689 Receiver->getType(),
3690 /*SuperLoc=*/SourceLocation(),
3691 Sel, Method, LBracLoc, SelectorLocs,
3692 RBracLoc, Args);
3693 }
3694
3695 /// Build a new Objective-C instance/class message to 'super'.
3696 ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3697 Selector Sel,
3698 ArrayRef<SourceLocation> SelectorLocs,
3699 QualType SuperType,
3700 ObjCMethodDecl *Method,
3701 SourceLocation LBracLoc,
3702 MultiExprArg Args,
3703 SourceLocation RBracLoc) {
3704 return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3705 SuperType,
3706 SuperLoc,
3707 Sel, Method, LBracLoc, SelectorLocs,
3708 RBracLoc, Args)
3709 : SemaRef.BuildClassMessage(nullptr,
3710 SuperType,
3711 SuperLoc,
3712 Sel, Method, LBracLoc, SelectorLocs,
3713 RBracLoc, Args);
3714
3715
3716 }
3717
3718 /// Build a new Objective-C ivar reference expression.
3719 ///
3720 /// By default, performs semantic analysis to build the new expression.
3721 /// Subclasses may override this routine to provide different behavior.
3722 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3723 SourceLocation IvarLoc,
3724 bool IsArrow, bool IsFreeIvar) {
3725 CXXScopeSpec SS;
3726 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3727 ExprResult Result = getSema().BuildMemberReferenceExpr(
3728 BaseArg, BaseArg->getType(),
3729 /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3730 /*FirstQualifierInScope=*/nullptr, NameInfo,
3731 /*TemplateArgs=*/nullptr,
3732 /*S=*/nullptr);
3733 if (IsFreeIvar && Result.isUsable())
3734 cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3735 return Result;
3736 }
3737
3738 /// Build a new Objective-C property reference expression.
3739 ///
3740 /// By default, performs semantic analysis to build the new expression.
3741 /// Subclasses may override this routine to provide different behavior.
3742 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3743 ObjCPropertyDecl *Property,
3744 SourceLocation PropertyLoc) {
3745 CXXScopeSpec SS;
3746 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3747 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3748 /*FIXME:*/PropertyLoc,
3749 /*IsArrow=*/false,
3750 SS, SourceLocation(),
3751 /*FirstQualifierInScope=*/nullptr,
3752 NameInfo,
3753 /*TemplateArgs=*/nullptr,
3754 /*S=*/nullptr);
3755 }
3756
3757 /// Build a new Objective-C property reference expression.
3758 ///
3759 /// By default, performs semantic analysis to build the new expression.
3760 /// Subclasses may override this routine to provide different behavior.
3761 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3762 ObjCMethodDecl *Getter,
3763 ObjCMethodDecl *Setter,
3764 SourceLocation PropertyLoc) {
3765 // Since these expressions can only be value-dependent, we do not
3766 // need to perform semantic analysis again.
3767 return Owned(
3768 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3769 VK_LValue, OK_ObjCProperty,
3770 PropertyLoc, Base));
3771 }
3772
3773 /// Build a new Objective-C "isa" expression.
3774 ///
3775 /// By default, performs semantic analysis to build the new expression.
3776 /// Subclasses may override this routine to provide different behavior.
3777 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3778 SourceLocation OpLoc, bool IsArrow) {
3779 CXXScopeSpec SS;
3780 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3781 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3782 OpLoc, IsArrow,
3783 SS, SourceLocation(),
3784 /*FirstQualifierInScope=*/nullptr,
3785 NameInfo,
3786 /*TemplateArgs=*/nullptr,
3787 /*S=*/nullptr);
3788 }
3789
3790 /// Build a new shuffle vector expression.
3791 ///
3792 /// By default, performs semantic analysis to build the new expression.
3793 /// Subclasses may override this routine to provide different behavior.
3794 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3795 MultiExprArg SubExprs,
3796 SourceLocation RParenLoc) {
3797 // Find the declaration for __builtin_shufflevector
3798 const IdentifierInfo &Name
3799 = SemaRef.Context.Idents.get("__builtin_shufflevector");
3800 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3801 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3802 assert(!Lookup.empty() && "No __builtin_shufflevector?")(static_cast <bool> (!Lookup.empty() && "No __builtin_shufflevector?"
) ? void (0) : __assert_fail ("!Lookup.empty() && \"No __builtin_shufflevector?\""
, "clang/lib/Sema/TreeTransform.h", 3802, __extension__ __PRETTY_FUNCTION__
))
;
3803
3804 // Build a reference to the __builtin_shufflevector builtin
3805 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3806 Expr *Callee = new (SemaRef.Context)
3807 DeclRefExpr(SemaRef.Context, Builtin, false,
3808 SemaRef.Context.BuiltinFnTy, VK_PRValue, BuiltinLoc);
3809 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3810 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3811 CK_BuiltinFnToFnPtr).get();
3812
3813 // Build the CallExpr
3814 ExprResult TheCall = CallExpr::Create(
3815 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3816 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc,
3817 FPOptionsOverride());
3818
3819 // Type-check the __builtin_shufflevector expression.
3820 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3821 }
3822
3823 /// Build a new convert vector expression.
3824 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3825 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3826 SourceLocation RParenLoc) {
3827 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3828 BuiltinLoc, RParenLoc);
3829 }
3830
3831 /// Build a new template argument pack expansion.
3832 ///
3833 /// By default, performs semantic analysis to build a new pack expansion
3834 /// for a template argument. Subclasses may override this routine to provide
3835 /// different behavior.
3836 TemplateArgumentLoc
3837 RebuildPackExpansion(TemplateArgumentLoc Pattern, SourceLocation EllipsisLoc,
3838 std::optional<unsigned> NumExpansions) {
3839 switch (Pattern.getArgument().getKind()) {
3840 case TemplateArgument::Expression: {
3841 ExprResult Result
3842 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3843 EllipsisLoc, NumExpansions);
3844 if (Result.isInvalid())
3845 return TemplateArgumentLoc();
3846
3847 return TemplateArgumentLoc(Result.get(), Result.get());
3848 }
3849
3850 case TemplateArgument::Template:
3851 return TemplateArgumentLoc(
3852 SemaRef.Context,
3853 TemplateArgument(Pattern.getArgument().getAsTemplate(),
3854 NumExpansions),
3855 Pattern.getTemplateQualifierLoc(), Pattern.getTemplateNameLoc(),
3856 EllipsisLoc);
3857
3858 case TemplateArgument::Null:
3859 case TemplateArgument::Integral:
3860 case TemplateArgument::Declaration:
3861 case TemplateArgument::Pack:
3862 case TemplateArgument::TemplateExpansion:
3863 case TemplateArgument::NullPtr:
3864 llvm_unreachable("Pack expansion pattern has no parameter packs")::llvm::llvm_unreachable_internal("Pack expansion pattern has no parameter packs"
, "clang/lib/Sema/TreeTransform.h", 3864)
;
3865
3866 case TemplateArgument::Type:
3867 if (TypeSourceInfo *Expansion
3868 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3869 EllipsisLoc,
3870 NumExpansions))
3871 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3872 Expansion);
3873 break;
3874 }
3875
3876 return TemplateArgumentLoc();
3877 }
3878
3879 /// Build a new expression pack expansion.
3880 ///
3881 /// By default, performs semantic analysis to build a new pack expansion
3882 /// for an expression. Subclasses may override this routine to provide
3883 /// different behavior.
3884 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3885 std::optional<unsigned> NumExpansions) {
3886 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3887 }
3888
3889 /// Build a new C++1z fold-expression.
3890 ///
3891 /// By default, performs semantic analysis in order to build a new fold
3892 /// expression.
3893 ExprResult RebuildCXXFoldExpr(UnresolvedLookupExpr *ULE,
3894 SourceLocation LParenLoc, Expr *LHS,
3895 BinaryOperatorKind Operator,
3896 SourceLocation EllipsisLoc, Expr *RHS,
3897 SourceLocation RParenLoc,
3898 std::optional<unsigned> NumExpansions) {
3899 return getSema().BuildCXXFoldExpr(ULE, LParenLoc, LHS, Operator,
3900 EllipsisLoc, RHS, RParenLoc,
3901 NumExpansions);
3902 }
3903
3904 /// Build an empty C++1z fold-expression with the given operator.
3905 ///
3906 /// By default, produces the fallback value for the fold-expression, or
3907 /// produce an error if there is no fallback value.
3908 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3909 BinaryOperatorKind Operator) {
3910 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3911 }
3912
3913 /// Build a new atomic operation expression.
3914 ///
3915 /// By default, performs semantic analysis to build the new expression.
3916 /// Subclasses may override this routine to provide different behavior.
3917 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3918 AtomicExpr::AtomicOp Op,
3919 SourceLocation RParenLoc) {
3920 // Use this for all of the locations, since we don't know the difference
3921 // between the call and the expr at this point.
3922 SourceRange Range{BuiltinLoc, RParenLoc};
3923 return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3924 Sema::AtomicArgumentOrder::AST);
3925 }
3926
3927 ExprResult RebuildRecoveryExpr(SourceLocation BeginLoc, SourceLocation EndLoc,
3928 ArrayRef<Expr *> SubExprs, QualType Type) {
3929 return getSema().CreateRecoveryExpr(BeginLoc, EndLoc, SubExprs, Type);
3930 }
3931
3932private:
3933 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3934 QualType ObjectType,
3935 NamedDecl *FirstQualifierInScope,
3936 CXXScopeSpec &SS);
3937
3938 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3939 QualType ObjectType,
3940 NamedDecl *FirstQualifierInScope,
3941 CXXScopeSpec &SS);
3942
3943 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3944 NamedDecl *FirstQualifierInScope,
3945 CXXScopeSpec &SS);
3946
3947 QualType TransformDependentNameType(TypeLocBuilder &TLB,
3948 DependentNameTypeLoc TL,
3949 bool DeducibleTSTContext);
3950};
3951
3952template <typename Derived>
3953StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3954 if (!S)
3955 return S;
3956
3957 switch (S->getStmtClass()) {
3958 case Stmt::NoStmtClass: break;
3959
3960 // Transform individual statement nodes
3961 // Pass SDK into statements that can produce a value
3962#define STMT(Node, Parent) \
3963 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3964#define VALUESTMT(Node, Parent) \
3965 case Stmt::Node##Class: \
3966 return getDerived().Transform##Node(cast<Node>(S), SDK);
3967#define ABSTRACT_STMT(Node)
3968#define EXPR(Node, Parent)
3969#include "clang/AST/StmtNodes.inc"
3970
3971 // Transform expressions by calling TransformExpr.
3972#define STMT(Node, Parent)
3973#define ABSTRACT_STMT(Stmt)
3974#define EXPR(Node, Parent) case Stmt::Node##Class:
3975#include "clang/AST/StmtNodes.inc"
3976 {
3977 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3978
3979 if (SDK == SDK_StmtExprResult)
3980 E = getSema().ActOnStmtExprResult(E);
3981 return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3982 }
3983 }
3984
3985 return S;
3986}
3987
3988template<typename Derived>
3989OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3990 if (!S)
3991 return S;
3992
3993 switch (S->getClauseKind()) {
3994 default: break;
3995 // Transform individual clause nodes
3996#define GEN_CLANG_CLAUSE_CLASS
3997#define CLAUSE_CLASS(Enum, Str, Class) \
3998 case Enum: \
3999 return getDerived().Transform##Class(cast<Class>(S));
4000#include "llvm/Frontend/OpenMP/OMP.inc"
4001 }
4002
4003 return S;
4004}
4005
4006
4007template<typename Derived>
4008ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
4009 if (!E)
4010 return E;
4011
4012 switch (E->getStmtClass()) {
4013 case Stmt::NoStmtClass: break;
4014#define STMT(Node, Parent) case Stmt::Node##Class: break;
4015#define ABSTRACT_STMT(Stmt)
4016#define EXPR(Node, Parent) \
4017 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
4018#include "clang/AST/StmtNodes.inc"
4019 }
4020
4021 return E;
4022}
4023
4024template<typename Derived>
4025ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
4026 bool NotCopyInit) {
4027 // Initializers are instantiated like expressions, except that various outer
4028 // layers are stripped.
4029 if (!Init)
4030 return Init;
4031
4032 if (auto *FE = dyn_cast<FullExpr>(Init))
4033 Init = FE->getSubExpr();
4034
4035 if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init)) {
4036 OpaqueValueExpr *OVE = AIL->getCommonExpr();
4037 Init = OVE->getSourceExpr();
4038 }
4039
4040 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
4041 Init = MTE->getSubExpr();
4042
4043 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
4044 Init = Binder->getSubExpr();
4045
4046 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
4047 Init = ICE->getSubExprAsWritten();
4048
4049 if (CXXStdInitializerListExpr *ILE =
4050 dyn_cast<CXXStdInitializerListExpr>(Init))
4051 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
4052
4053 // If this is copy-initialization, we only need to reconstruct
4054 // InitListExprs. Other forms of copy-initialization will be a no-op if
4055 // the initializer is already the right type.
4056 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
4057 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
4058 return getDerived().TransformExpr(Init);
4059
4060 // Revert value-initialization back to empty parens.
4061 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
4062 SourceRange Parens = VIE->getSourceRange();
4063 return getDerived().RebuildParenListExpr(Parens.getBegin(), std::nullopt,
4064 Parens.getEnd());
4065 }
4066
4067 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
4068 if (isa<ImplicitValueInitExpr>(Init))
4069 return getDerived().RebuildParenListExpr(SourceLocation(), std::nullopt,
4070 SourceLocation());
4071
4072 // Revert initialization by constructor back to a parenthesized or braced list
4073 // of expressions. Any other form of initializer can just be reused directly.
4074 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
4075 return getDerived().TransformExpr(Init);
4076
4077 // If the initialization implicitly converted an initializer list to a
4078 // std::initializer_list object, unwrap the std::initializer_list too.
4079 if (Construct && Construct->isStdInitListInitialization())
4080 return TransformInitializer(Construct->getArg(0), NotCopyInit);
4081
4082 // Enter a list-init context if this was list initialization.
4083 EnterExpressionEvaluationContext Context(
4084 getSema(), EnterExpressionEvaluationContext::InitList,
4085 Construct->isListInitialization());
4086
4087 SmallVector<Expr*, 8> NewArgs;
4088 bool ArgChanged = false;
4089 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
4090 /*IsCall*/true, NewArgs, &ArgChanged))
4091 return ExprError();
4092
4093 // If this was list initialization, revert to syntactic list form.
4094 if (Construct->isListInitialization())
4095 return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
4096 Construct->getEndLoc());
4097
4098 // Build a ParenListExpr to represent anything else.
4099 SourceRange Parens = Construct->getParenOrBraceRange();
4100 if (Parens.isInvalid()) {
4101 // This was a variable declaration's initialization for which no initializer
4102 // was specified.
4103 assert(NewArgs.empty() &&(static_cast <bool> (NewArgs.empty() && "no parens or braces but have direct init with arguments?"
) ? void (0) : __assert_fail ("NewArgs.empty() && \"no parens or braces but have direct init with arguments?\""
, "clang/lib/Sema/TreeTransform.h", 4104, __extension__ __PRETTY_FUNCTION__
))
4104 "no parens or braces but have direct init with arguments?")(static_cast <bool> (NewArgs.empty() && "no parens or braces but have direct init with arguments?"
) ? void (0) : __assert_fail ("NewArgs.empty() && \"no parens or braces but have direct init with arguments?\""
, "clang/lib/Sema/TreeTransform.h", 4104, __extension__ __PRETTY_FUNCTION__
))
;
4105 return ExprEmpty();
4106 }
4107 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
4108 Parens.getEnd());
4109}
4110
4111template<typename Derived>
4112bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
4113 unsigned NumInputs,
4114 bool IsCall,
4115 SmallVectorImpl<Expr *> &Outputs,
4116 bool *ArgChanged) {
4117 for (unsigned I = 0; I != NumInputs; ++I) {
4118 // If requested, drop call arguments that need to be dropped.
4119 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
4120 if (ArgChanged)
4121 *ArgChanged = true;
4122
4123 break;
4124 }
4125
4126 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
4127 Expr *Pattern = Expansion->getPattern();
4128
4129 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4130 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4131 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 4131, __extension__ __PRETTY_FUNCTION__
))
;
4132
4133 // Determine whether the set of unexpanded parameter packs can and should
4134 // be expanded.
4135 bool Expand = true;
4136 bool RetainExpansion = false;
4137 std::optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
4138 std::optional<unsigned> NumExpansions = OrigNumExpansions;
4139 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
4140 Pattern->getSourceRange(),
4141 Unexpanded,
4142 Expand, RetainExpansion,
4143 NumExpansions))
4144 return true;
4145
4146 if (!Expand) {
4147 // The transform has determined that we should perform a simple
4148 // transformation on the pack expansion, producing another pack
4149 // expansion.
4150 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4151 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
4152 if (OutPattern.isInvalid())
4153 return true;
4154
4155 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
4156 Expansion->getEllipsisLoc(),
4157 NumExpansions);
4158 if (Out.isInvalid())
4159 return true;
4160
4161 if (ArgChanged)
4162 *ArgChanged = true;
4163 Outputs.push_back(Out.get());
4164 continue;
4165 }
4166
4167 // Record right away that the argument was changed. This needs
4168 // to happen even if the array expands to nothing.
4169 if (ArgChanged) *ArgChanged = true;
4170
4171 // The transform has determined that we should perform an elementwise
4172 // expansion of the pattern. Do so.
4173 for (unsigned I = 0; I != *NumExpansions; ++I) {
4174 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4175 ExprResult Out = getDerived().TransformExpr(Pattern);
4176 if (Out.isInvalid())
4177 return true;
4178
4179 if (Out.get()->containsUnexpandedParameterPack()) {
4180 Out = getDerived().RebuildPackExpansion(
4181 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4182 if (Out.isInvalid())
4183 return true;
4184 }
4185
4186 Outputs.push_back(Out.get());
4187 }
4188
4189 // If we're supposed to retain a pack expansion, do so by temporarily
4190 // forgetting the partially-substituted parameter pack.
4191 if (RetainExpansion) {
4192 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4193
4194 ExprResult Out = getDerived().TransformExpr(Pattern);
4195 if (Out.isInvalid())
4196 return true;
4197
4198 Out = getDerived().RebuildPackExpansion(
4199 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4200 if (Out.isInvalid())
4201 return true;
4202
4203 Outputs.push_back(Out.get());
4204 }
4205
4206 continue;
4207 }
4208
4209 ExprResult Result =
4210 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
4211 : getDerived().TransformExpr(Inputs[I]);
4212 if (Result.isInvalid())
4213 return true;
4214
4215 if (Result.get() != Inputs[I] && ArgChanged)
4216 *ArgChanged = true;
4217
4218 Outputs.push_back(Result.get());
4219 }
4220
4221 return false;
4222}
4223
4224template <typename Derived>
4225Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
4226 SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
4227 if (Var) {
4228 VarDecl *ConditionVar = cast_or_null<VarDecl>(
4229 getDerived().TransformDefinition(Var->getLocation(), Var));
4230
4231 if (!ConditionVar)
4232 return Sema::ConditionError();
4233
4234 return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
4235 }
4236
4237 if (Expr) {
4238 ExprResult CondExpr = getDerived().TransformExpr(Expr);
4239
4240 if (CondExpr.isInvalid())
4241 return Sema::ConditionError();
4242
4243 return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind,
4244 /*MissingOK=*/true);
4245 }
4246
4247 return Sema::ConditionResult();
4248}
4249
4250template <typename Derived>
4251NestedNameSpecifierLoc TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
4252 NestedNameSpecifierLoc NNS, QualType ObjectType,
4253 NamedDecl *FirstQualifierInScope) {
4254 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
4255
4256 auto insertNNS = [&Qualifiers](NestedNameSpecifierLoc NNS) {
4257 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
4258 Qualifier = Qualifier.getPrefix())
4259 Qualifiers.push_back(Qualifier);
4260 };
4261 insertNNS(NNS);
4262
4263 CXXScopeSpec SS;
4264 while (!Qualifiers.empty()) {
4265 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
4266 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
4267
4268 switch (QNNS->getKind()) {
4269 case NestedNameSpecifier::Identifier: {
4270 Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
4271 Q.getLocalBeginLoc(), Q.getLocalEndLoc(),
4272 ObjectType);
4273 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
4274 SS, FirstQualifierInScope, false))
4275 return NestedNameSpecifierLoc();
4276 break;
4277 }
4278
4279 case NestedNameSpecifier::Namespace: {
4280 NamespaceDecl *NS =
4281 cast_or_null<NamespaceDecl>(getDerived().TransformDecl(
4282 Q.getLocalBeginLoc(), QNNS->getAsNamespace()));
4283 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
4284 break;
4285 }
4286
4287 case NestedNameSpecifier::NamespaceAlias: {
4288 NamespaceAliasDecl *Alias =
4289 cast_or_null<NamespaceAliasDecl>(getDerived().TransformDecl(
4290 Q.getLocalBeginLoc(), QNNS->getAsNamespaceAlias()));
4291 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
4292 Q.getLocalEndLoc());
4293 break;
4294 }
4295
4296 case NestedNameSpecifier::Global:
4297 // There is no meaningful transformation that one could perform on the
4298 // global scope.
4299 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
4300 break;
4301
4302 case NestedNameSpecifier::Super: {
4303 CXXRecordDecl *RD =
4304 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
4305 SourceLocation(), QNNS->getAsRecordDecl()));
4306 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
4307 break;
4308 }
4309
4310 case NestedNameSpecifier::TypeSpecWithTemplate:
4311 case NestedNameSpecifier::TypeSpec: {
4312 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
4313 FirstQualifierInScope, SS);
4314
4315 if (!TL)
4316 return NestedNameSpecifierLoc();
4317
4318 QualType T = TL.getType();
4319 if (T->isDependentType() || T->isRecordType() ||
4320 (SemaRef.getLangOpts().CPlusPlus11 && T->isEnumeralType())) {
4321 if (T->isEnumeralType())
4322 SemaRef.Diag(TL.getBeginLoc(),
4323 diag::warn_cxx98_compat_enum_nested_name_spec);
4324
4325 if (const auto ETL = TL.getAs<ElaboratedTypeLoc>()) {
4326 SS.Adopt(ETL.getQualifierLoc());
4327 TL = ETL.getNamedTypeLoc();
4328 }
4329 SS.Extend(SemaRef.Context, /*FIXME:*/ SourceLocation(), TL,
4330 Q.getLocalEndLoc());
4331 break;
4332 }
4333 // If the nested-name-specifier is an invalid type def, don't emit an
4334 // error because a previous error should have already been emitted.
4335 TypedefTypeLoc TTL = TL.getAsAdjusted<TypedefTypeLoc>();
4336 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
4337 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
4338 << T << SS.getRange();
4339 }
4340 return NestedNameSpecifierLoc();
4341 }
4342 }
4343
4344 // The qualifier-in-scope and object type only apply to the leftmost entity.
4345 FirstQualifierInScope = nullptr;
4346 ObjectType = QualType();
4347 }
4348
4349 // Don't rebuild the nested-name-specifier if we don't have to.
4350 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
4351 !getDerived().AlwaysRebuild())
4352 return NNS;
4353
4354 // If we can re-use the source-location data from the original
4355 // nested-name-specifier, do so.
4356 if (SS.location_size() == NNS.getDataLength() &&
4357 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
4358 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
4359
4360 // Allocate new nested-name-specifier location information.
4361 return SS.getWithLocInContext(SemaRef.Context);
4362}
4363
4364template<typename Derived>
4365DeclarationNameInfo
4366TreeTransform<Derived>
4367::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
4368 DeclarationName Name = NameInfo.getName();
4369 if (!Name)
4370 return DeclarationNameInfo();
4371
4372 switch (Name.getNameKind()) {
4373 case DeclarationName::Identifier:
4374 case DeclarationName::ObjCZeroArgSelector:
4375 case DeclarationName::ObjCOneArgSelector:
4376 case DeclarationName::ObjCMultiArgSelector:
4377 case DeclarationName::CXXOperatorName:
4378 case DeclarationName::CXXLiteralOperatorName:
4379 case DeclarationName::CXXUsingDirective:
4380 return NameInfo;
4381
4382 case DeclarationName::CXXDeductionGuideName: {
4383 TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
4384 TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
4385 getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
4386 if (!NewTemplate)
4387 return DeclarationNameInfo();
4388
4389 DeclarationNameInfo NewNameInfo(NameInfo);
4390 NewNameInfo.setName(
4391 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
4392 return NewNameInfo;
4393 }
4394
4395 case DeclarationName::CXXConstructorName:
4396 case DeclarationName::CXXDestructorName:
4397 case DeclarationName::CXXConversionFunctionName: {
4398 TypeSourceInfo *NewTInfo;
4399 CanQualType NewCanTy;
4400 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
4401 NewTInfo = getDerived().TransformType(OldTInfo);
4402 if (!NewTInfo)
4403 return DeclarationNameInfo();
4404 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
4405 }
4406 else {
4407 NewTInfo = nullptr;
4408 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
4409 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
4410 if (NewT.isNull())
4411 return DeclarationNameInfo();
4412 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
4413 }
4414
4415 DeclarationName NewName
4416 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
4417 NewCanTy);
4418 DeclarationNameInfo NewNameInfo(NameInfo);
4419 NewNameInfo.setName(NewName);
4420 NewNameInfo.setNamedTypeInfo(NewTInfo);
4421 return NewNameInfo;
4422 }
4423 }
4424
4425 llvm_unreachable("Unknown name kind.")::llvm::llvm_unreachable_internal("Unknown name kind.", "clang/lib/Sema/TreeTransform.h"
, 4425)
;
4426}
4427
4428template<typename Derived>
4429TemplateName
4430TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
4431 TemplateName Name,
4432 SourceLocation NameLoc,
4433 QualType ObjectType,
4434 NamedDecl *FirstQualifierInScope,
4435 bool AllowInjectedClassName) {
4436 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
4437 TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl();
4438 assert(Template && "qualified template name must refer to a template")(static_cast <bool> (Template && "qualified template name must refer to a template"
) ? void (0) : __assert_fail ("Template && \"qualified template name must refer to a template\""
, "clang/lib/Sema/TreeTransform.h", 4438, __extension__ __PRETTY_FUNCTION__
))
;
4439
4440 TemplateDecl *TransTemplate
4441 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4442 Template));
4443 if (!TransTemplate)
4444 return TemplateName();
4445
4446 if (!getDerived().AlwaysRebuild() &&
4447 SS.getScopeRep() == QTN->getQualifier() &&
4448 TransTemplate == Template)
4449 return Name;
4450
4451 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
4452 TransTemplate);
4453 }
4454
4455 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
4456 if (SS.getScopeRep()) {
4457 // These apply to the scope specifier, not the template.
4458 ObjectType = QualType();
4459 FirstQualifierInScope = nullptr;
4460 }
4461
4462 if (!getDerived().AlwaysRebuild() &&
4463 SS.getScopeRep() == DTN->getQualifier() &&
4464 ObjectType.isNull())
4465 return Name;
4466
4467 // FIXME: Preserve the location of the "template" keyword.
4468 SourceLocation TemplateKWLoc = NameLoc;
4469
4470 if (DTN->isIdentifier()) {
4471 return getDerived().RebuildTemplateName(SS,
4472 TemplateKWLoc,
4473 *DTN->getIdentifier(),
4474 NameLoc,
4475 ObjectType,
4476 FirstQualifierInScope,
4477 AllowInjectedClassName);
4478 }
4479
4480 return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
4481 DTN->getOperator(), NameLoc,
4482 ObjectType, AllowInjectedClassName);
4483 }
4484
4485 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4486 TemplateDecl *TransTemplate
4487 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4488 Template));
4489 if (!TransTemplate)
4490 return TemplateName();
4491
4492 if (!getDerived().AlwaysRebuild() &&
4493 TransTemplate == Template)
4494 return Name;
4495
4496 return TemplateName(TransTemplate);
4497 }
4498
4499 if (SubstTemplateTemplateParmPackStorage *SubstPack
4500 = Name.getAsSubstTemplateTemplateParmPack()) {
4501 return getDerived().RebuildTemplateName(
4502 SubstPack->getArgumentPack(), SubstPack->getAssociatedDecl(),
4503 SubstPack->getIndex(), SubstPack->getFinal());
4504 }
4505
4506 // These should be getting filtered out before they reach the AST.
4507 llvm_unreachable("overloaded function decl survived to here")::llvm::llvm_unreachable_internal("overloaded function decl survived to here"
, "clang/lib/Sema/TreeTransform.h", 4507)
;
4508}
4509
4510template<typename Derived>
4511void TreeTransform<Derived>::InventTemplateArgumentLoc(
4512 const TemplateArgument &Arg,
4513 TemplateArgumentLoc &Output) {
4514 Output = getSema().getTrivialTemplateArgumentLoc(
4515 Arg, QualType(), getDerived().getBaseLocation());
4516}
4517
4518template <typename Derived>
4519bool TreeTransform<Derived>::TransformTemplateArgument(
4520 const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
4521 bool Uneval) {
4522 const TemplateArgument &Arg = Input.getArgument();
4523 switch (Arg.getKind()) {
4524 case TemplateArgument::Null:
4525 case TemplateArgument::Pack:
4526 llvm_unreachable("Unexpected TemplateArgument")::llvm::llvm_unreachable_internal("Unexpected TemplateArgument"
, "clang/lib/Sema/TreeTransform.h", 4526)
;
4527
4528 case TemplateArgument::Integral:
4529 case TemplateArgument::NullPtr:
4530 case TemplateArgument::Declaration: {
4531 // Transform a resolved template argument straight to a resolved template
4532 // argument. We get here when substituting into an already-substituted
4533 // template type argument during concept satisfaction checking.
4534 QualType T = Arg.getNonTypeTemplateArgumentType();
4535 QualType NewT = getDerived().TransformType(T);
4536 if (NewT.isNull())
4537 return true;
4538
4539 ValueDecl *D = Arg.getKind() == TemplateArgument::Declaration
4540 ? Arg.getAsDecl()
4541 : nullptr;
4542 ValueDecl *NewD = D ? cast_or_null<ValueDecl>(getDerived().TransformDecl(
4543 getDerived().getBaseLocation(), D))
4544 : nullptr;
4545 if (D && !NewD)
4546 return true;
4547
4548 if (NewT == T && D == NewD)
4549 Output = Input;
4550 else if (Arg.getKind() == TemplateArgument::Integral)
4551 Output = TemplateArgumentLoc(
4552 TemplateArgument(getSema().Context, Arg.getAsIntegral(), NewT),
4553 TemplateArgumentLocInfo());
4554 else if (Arg.getKind() == TemplateArgument::NullPtr)
4555 Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true),
4556 TemplateArgumentLocInfo());
4557 else
4558 Output = TemplateArgumentLoc(TemplateArgument(NewD, NewT),
4559 TemplateArgumentLocInfo());
4560
4561 return false;
4562 }
4563
4564 case TemplateArgument::Type: {
4565 TypeSourceInfo *DI = Input.getTypeSourceInfo();
4566 if (!DI)
4567 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4568
4569 DI = getDerived().TransformType(DI);
4570 if (!DI)
4571 return true;
4572
4573 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4574 return false;
4575 }
4576
4577 case TemplateArgument::Template: {
4578 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4579 if (QualifierLoc) {
4580 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4581 if (!QualifierLoc)
4582 return true;
4583 }
4584
4585 CXXScopeSpec SS;
4586 SS.Adopt(QualifierLoc);
4587 TemplateName Template = getDerived().TransformTemplateName(
4588 SS, Arg.getAsTemplate(), Input.getTemplateNameLoc());
4589 if (Template.isNull())
4590 return true;
4591
4592 Output = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template),
4593 QualifierLoc, Input.getTemplateNameLoc());
4594 return false;
4595 }
4596
4597 case TemplateArgument::TemplateExpansion:
4598 llvm_unreachable("Caller should expand pack expansions")::llvm::llvm_unreachable_internal("Caller should expand pack expansions"
, "clang/lib/Sema/TreeTransform.h", 4598)
;
4599
4600 case TemplateArgument::Expression: {
4601 // Template argument expressions are constant expressions.
4602 EnterExpressionEvaluationContext Unevaluated(
4603 getSema(),
4604 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4605 : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4606 Sema::ReuseLambdaContextDecl, /*ExprContext=*/
4607 Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4608
4609 Expr *InputExpr = Input.getSourceExpression();
4610 if (!InputExpr)
4611 InputExpr = Input.getArgument().getAsExpr();
4612
4613 ExprResult E = getDerived().TransformExpr(InputExpr);
4614 E = SemaRef.ActOnConstantExpression(E);
4615 if (E.isInvalid())
4616 return true;
4617 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4618 return false;
4619 }
4620 }
4621
4622 // Work around bogus GCC warning
4623 return true;
4624}
4625
4626/// Iterator adaptor that invents template argument location information
4627/// for each of the template arguments in its underlying iterator.
4628template<typename Derived, typename InputIterator>
4629class TemplateArgumentLocInventIterator {
4630 TreeTransform<Derived> &Self;
4631 InputIterator Iter;
4632
4633public:
4634 typedef TemplateArgumentLoc value_type;
4635 typedef TemplateArgumentLoc reference;
4636 typedef typename std::iterator_traits<InputIterator>::difference_type
4637 difference_type;
4638 typedef std::input_iterator_tag iterator_category;
4639
4640 class pointer {
4641 TemplateArgumentLoc Arg;
4642
4643 public:
4644 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4645
4646 const TemplateArgumentLoc *operator->() const { return &Arg; }
4647 };
4648
4649 TemplateArgumentLocInventIterator() { }
4650
4651 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4652 InputIterator Iter)
4653 : Self(Self), Iter(Iter) { }
4654
4655 TemplateArgumentLocInventIterator &operator++() {
4656 ++Iter;
4657 return *this;
4658 }
4659
4660 TemplateArgumentLocInventIterator operator++(int) {
4661 TemplateArgumentLocInventIterator Old(*this);
4662 ++(*this);
4663 return Old;
4664 }
4665
4666 reference operator*() const {
4667 TemplateArgumentLoc Result;
4668 Self.InventTemplateArgumentLoc(*Iter, Result);
4669 return Result;
4670 }
4671
4672 pointer operator->() const { return pointer(**this); }
4673
4674 friend bool operator==(const TemplateArgumentLocInventIterator &X,
4675 const TemplateArgumentLocInventIterator &Y) {
4676 return X.Iter == Y.Iter;
4677 }
4678
4679 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4680 const TemplateArgumentLocInventIterator &Y) {
4681 return X.Iter != Y.Iter;
4682 }
4683};
4684
4685template<typename Derived>
4686template<typename InputIterator>
4687bool TreeTransform<Derived>::TransformTemplateArguments(
4688 InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4689 bool Uneval) {
4690 for (; First != Last; ++First) {
4691 TemplateArgumentLoc Out;
4692 TemplateArgumentLoc In = *First;
4693
4694 if (In.getArgument().getKind() == TemplateArgument::Pack) {
4695 // Unpack argument packs, which we translate them into separate
4696 // arguments.
4697 // FIXME: We could do much better if we could guarantee that the
4698 // TemplateArgumentLocInfo for the pack expansion would be usable for
4699 // all of the template arguments in the argument pack.
4700 typedef TemplateArgumentLocInventIterator<Derived,
4701 TemplateArgument::pack_iterator>
4702 PackLocIterator;
4703 if (TransformTemplateArguments(PackLocIterator(*this,
4704 In.getArgument().pack_begin()),
4705 PackLocIterator(*this,
4706 In.getArgument().pack_end()),
4707 Outputs, Uneval))
4708 return true;
4709
4710 continue;
4711 }
4712
4713 if (In.getArgument().isPackExpansion()) {
4714 // We have a pack expansion, for which we will be substituting into
4715 // the pattern.
4716 SourceLocation Ellipsis;
4717 std::optional<unsigned> OrigNumExpansions;
4718 TemplateArgumentLoc Pattern
4719 = getSema().getTemplateArgumentPackExpansionPattern(
4720 In, Ellipsis, OrigNumExpansions);
4721
4722 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4723 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4724 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 4724, __extension__ __PRETTY_FUNCTION__
))
;
4725
4726 // Determine whether the set of unexpanded parameter packs can and should
4727 // be expanded.
4728 bool Expand = true;
4729 bool RetainExpansion = false;
4730 std::optional<unsigned> NumExpansions = OrigNumExpansions;
4731 if (getDerived().TryExpandParameterPacks(Ellipsis,
4732 Pattern.getSourceRange(),
4733 Unexpanded,
4734 Expand,
4735 RetainExpansion,
4736 NumExpansions))
4737 return true;
4738
4739 if (!Expand) {
4740 // The transform has determined that we should perform a simple
4741 // transformation on the pack expansion, producing another pack
4742 // expansion.
4743 TemplateArgumentLoc OutPattern;
4744 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4745 if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4746 return true;
4747
4748 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4749 NumExpansions);
4750 if (Out.getArgument().isNull())
4751 return true;
4752
4753 Outputs.addArgument(Out);
4754 continue;
4755 }
4756
4757 // The transform has determined that we should perform an elementwise
4758 // expansion of the pattern. Do so.
4759 for (unsigned I = 0; I != *NumExpansions; ++I) {
4760 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4761
4762 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4763 return true;
4764
4765 if (Out.getArgument().containsUnexpandedParameterPack()) {
4766 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4767 OrigNumExpansions);
4768 if (Out.getArgument().isNull())
4769 return true;
4770 }
4771
4772 Outputs.addArgument(Out);
4773 }
4774
4775 // If we're supposed to retain a pack expansion, do so by temporarily
4776 // forgetting the partially-substituted parameter pack.
4777 if (RetainExpansion) {
4778 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4779
4780 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4781 return true;
4782
4783 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4784 OrigNumExpansions);
4785 if (Out.getArgument().isNull())
4786 return true;
4787
4788 Outputs.addArgument(Out);
4789 }
4790
4791 continue;
4792 }
4793
4794 // The simple case:
4795 if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4796 return true;
4797
4798 Outputs.addArgument(Out);
4799 }
4800
4801 return false;
4802
4803}
4804
4805//===----------------------------------------------------------------------===//
4806// Type transformation
4807//===----------------------------------------------------------------------===//
4808
4809template<typename Derived>
4810QualType TreeTransform<Derived>::TransformType(QualType T) {
4811 if (getDerived().AlreadyTransformed(T))
4812 return T;
4813
4814 // Temporary workaround. All of these transformations should
4815 // eventually turn into transformations on TypeLocs.
4816 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4817 getDerived().getBaseLocation());
4818
4819 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4820
4821 if (!NewDI)
4822 return QualType();
4823
4824 return NewDI->getType();
4825}
4826
4827template<typename Derived>
4828TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4829 // Refine the base location to the type's location.
4830 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4831 getDerived().getBaseEntity());
4832 if (getDerived().AlreadyTransformed(DI->getType()))
4833 return DI;
4834
4835 TypeLocBuilder TLB;
4836
4837 TypeLoc TL = DI->getTypeLoc();
4838 TLB.reserve(TL.getFullDataSize());
4839
4840 QualType Result = getDerived().TransformType(TLB, TL);
4841 if (Result.isNull())
4842 return nullptr;
4843
4844 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4845}
4846
4847template<typename Derived>
4848QualType
4849TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4850 switch (T.getTypeLocClass()) {
4851#define ABSTRACT_TYPELOC(CLASS, PARENT)
4852#define TYPELOC(CLASS, PARENT) \
4853 case TypeLoc::CLASS: \
4854 return getDerived().Transform##CLASS##Type(TLB, \
4855 T.castAs<CLASS##TypeLoc>());
4856#include "clang/AST/TypeLocNodes.def"
4857 }
4858
4859 llvm_unreachable("unhandled type loc!")::llvm::llvm_unreachable_internal("unhandled type loc!", "clang/lib/Sema/TreeTransform.h"
, 4859)
;
4860}
4861
4862template<typename Derived>
4863QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4864 if (!isa<DependentNameType>(T))
4865 return TransformType(T);
4866
4867 if (getDerived().AlreadyTransformed(T))
4868 return T;
4869 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4870 getDerived().getBaseLocation());
4871 TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4872 return NewDI ? NewDI->getType() : QualType();
4873}
4874
4875template<typename Derived>
4876TypeSourceInfo *
4877TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4878 if (!isa<DependentNameType>(DI->getType()))
4879 return TransformType(DI);
4880
4881 // Refine the base location to the type's location.
4882 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4883 getDerived().getBaseEntity());
4884 if (getDerived().AlreadyTransformed(DI->getType()))
4885 return DI;
4886
4887 TypeLocBuilder TLB;
4888
4889 TypeLoc TL = DI->getTypeLoc();
4890 TLB.reserve(TL.getFullDataSize());
4891
4892 auto QTL = TL.getAs<QualifiedTypeLoc>();
4893 if (QTL)
4894 TL = QTL.getUnqualifiedLoc();
4895
4896 auto DNTL = TL.castAs<DependentNameTypeLoc>();
4897
4898 QualType Result = getDerived().TransformDependentNameType(
4899 TLB, DNTL, /*DeducedTSTContext*/true);
4900 if (Result.isNull())
4901 return nullptr;
4902
4903 if (QTL) {
4904 Result = getDerived().RebuildQualifiedType(Result, QTL);
4905 if (Result.isNull())
4906 return nullptr;
4907 TLB.TypeWasModifiedSafely(Result);
4908 }
4909
4910 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4911}
4912
4913template<typename Derived>
4914QualType
4915TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4916 QualifiedTypeLoc T) {
4917 QualType Result;
4918 TypeLoc UnqualTL = T.getUnqualifiedLoc();
4919 auto SuppressObjCLifetime =
4920 T.getType().getLocalQualifiers().hasObjCLifetime();
4921 if (auto TTP = UnqualTL.getAs<TemplateTypeParmTypeLoc>()) {
4922 Result = getDerived().TransformTemplateTypeParmType(TLB, TTP,
4923 SuppressObjCLifetime);
4924 } else if (auto STTP = UnqualTL.getAs<SubstTemplateTypeParmPackTypeLoc>()) {
4925 Result = getDerived().TransformSubstTemplateTypeParmPackType(
4926 TLB, STTP, SuppressObjCLifetime);
4927 } else {
4928 Result = getDerived().TransformType(TLB, UnqualTL);
4929 }
4930
4931 if (Result.isNull())
4932 return QualType();
4933
4934 Result = getDerived().RebuildQualifiedType(Result, T);
4935
4936 if (Result.isNull())
4937 return QualType();
4938
4939 // RebuildQualifiedType might have updated the type, but not in a way
4940 // that invalidates the TypeLoc. (There's no location information for
4941 // qualifiers.)
4942 TLB.TypeWasModifiedSafely(Result);
4943
4944 return Result;
4945}
4946
4947template <typename Derived>
4948QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4949 QualifiedTypeLoc TL) {
4950
4951 SourceLocation Loc = TL.getBeginLoc();
4952 Qualifiers Quals = TL.getType().getLocalQualifiers();
4953
4954 if ((T.getAddressSpace() != LangAS::Default &&
4955 Quals.getAddressSpace() != LangAS::Default) &&
4956 T.getAddressSpace() != Quals.getAddressSpace()) {
4957 SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4958 << TL.getType() << T;
4959 return QualType();
4960 }
4961
4962 // C++ [dcl.fct]p7:
4963 // [When] adding cv-qualifications on top of the function type [...] the
4964 // cv-qualifiers are ignored.
4965 if (T->isFunctionType()) {
4966 T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4967 Quals.getAddressSpace());
4968 return T;
4969 }
4970
4971 // C++ [dcl.ref]p1:
4972 // when the cv-qualifiers are introduced through the use of a typedef-name
4973 // or decltype-specifier [...] the cv-qualifiers are ignored.
4974 // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4975 // applied to a reference type.
4976 if (T->isReferenceType()) {
4977 // The only qualifier that applies to a reference type is restrict.
4978 if (!Quals.hasRestrict())
4979 return T;
4980 Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4981 }
4982
4983 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4984 // resulting type.
4985 if (Quals.hasObjCLifetime()) {
4986 if (!T->isObjCLifetimeType() && !T->isDependentType())
4987 Quals.removeObjCLifetime();
4988 else if (T.getObjCLifetime()) {
4989 // Objective-C ARC:
4990 // A lifetime qualifier applied to a substituted template parameter
4991 // overrides the lifetime qualifier from the template argument.
4992 const AutoType *AutoTy;
4993 if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4994 // 'auto' types behave the same way as template parameters.
4995 QualType Deduced = AutoTy->getDeducedType();
4996 Qualifiers Qs = Deduced.getQualifiers();
4997 Qs.removeObjCLifetime();
4998 Deduced =
4999 SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
5000 T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
5001 AutoTy->isDependentType(),
5002 /*isPack=*/false,
5003 AutoTy->getTypeConstraintConcept(),
5004 AutoTy->getTypeConstraintArguments());
5005 } else {
5006 // Otherwise, complain about the addition of a qualifier to an
5007 // already-qualified type.
5008 // FIXME: Why is this check not in Sema::BuildQualifiedType?
5009 SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
5010 Quals.removeObjCLifetime();
5011 }
5012 }
5013 }
5014
5015 return SemaRef.BuildQualifiedType(T, Loc, Quals);
5016}
5017
5018template<typename Derived>
5019TypeLoc
5020TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
5021 QualType ObjectType,
5022 NamedDecl *UnqualLookup,
5023 CXXScopeSpec &SS) {
5024 if (getDerived().AlreadyTransformed(TL.getType()))
5025 return TL;
5026
5027 TypeSourceInfo *TSI =
5028 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
5029 if (TSI)
5030 return TSI->getTypeLoc();
5031 return TypeLoc();
5032}
5033
5034template<typename Derived>
5035TypeSourceInfo *
5036TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
5037 QualType ObjectType,
5038 NamedDecl *UnqualLookup,
5039 CXXScopeSpec &SS) {
5040 if (getDerived().AlreadyTransformed(TSInfo->getType()))
5041 return TSInfo;
5042
5043 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
5044 UnqualLookup, SS);
5045}
5046
5047template <typename Derived>
5048TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
5049 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
5050 CXXScopeSpec &SS) {
5051 QualType T = TL.getType();
5052 assert(!getDerived().AlreadyTransformed(T))(static_cast <bool> (!getDerived().AlreadyTransformed(T
)) ? void (0) : __assert_fail ("!getDerived().AlreadyTransformed(T)"
, "clang/lib/Sema/TreeTransform.h", 5052, __extension__ __PRETTY_FUNCTION__
))
;
5053
5054 TypeLocBuilder TLB;
5055 QualType Result;
5056
5057 if (isa<TemplateSpecializationType>(T)) {
5058 TemplateSpecializationTypeLoc SpecTL =
5059 TL.castAs<TemplateSpecializationTypeLoc>();
5060
5061 TemplateName Template = getDerived().TransformTemplateName(
5062 SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
5063 ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
5064 if (Template.isNull())
5065 return nullptr;
5066
5067 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
5068 Template);
5069 } else if (isa<DependentTemplateSpecializationType>(T)) {
5070 DependentTemplateSpecializationTypeLoc SpecTL =
5071 TL.castAs<DependentTemplateSpecializationTypeLoc>();
5072
5073 TemplateName Template
5074 = getDerived().RebuildTemplateName(SS,
5075 SpecTL.getTemplateKeywordLoc(),
5076 *SpecTL.getTypePtr()->getIdentifier(),
5077 SpecTL.getTemplateNameLoc(),
5078 ObjectType, UnqualLookup,
5079 /*AllowInjectedClassName*/true);
5080 if (Template.isNull())
5081 return nullptr;
5082
5083 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
5084 SpecTL,
5085 Template,
5086 SS);
5087 } else {
5088 // Nothing special needs to be done for these.
5089 Result = getDerived().TransformType(TLB, TL);
5090 }
5091
5092 if (Result.isNull())
5093 return nullptr;
5094
5095 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
5096}
5097
5098template <class TyLoc> static inline
5099QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
5100 TyLoc NewT = TLB.push<TyLoc>(T.getType());
5101 NewT.setNameLoc(T.getNameLoc());
5102 return T.getType();
5103}
5104
5105template<typename Derived>
5106QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
5107 BuiltinTypeLoc T) {
5108 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
5109 NewT.setBuiltinLoc(T.getBuiltinLoc());
5110 if (T.needsExtraLocalData())
5111 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
5112 return T.getType();
5113}
5114
5115template<typename Derived>
5116QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
5117 ComplexTypeLoc T) {
5118 // FIXME: recurse?
5119 return TransformTypeSpecType(TLB, T);
5120}
5121
5122template <typename Derived>
5123QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
5124 AdjustedTypeLoc TL) {
5125 // Adjustments applied during transformation are handled elsewhere.
5126 return getDerived().TransformType(TLB, TL.getOriginalLoc());
5127}
5128
5129template<typename Derived>
5130QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
5131 DecayedTypeLoc TL) {
5132 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
5133 if (OriginalType.isNull())
5134 return QualType();
5135
5136 QualType Result = TL.getType();
5137 if (getDerived().AlwaysRebuild() ||
5138 OriginalType != TL.getOriginalLoc().getType())
5139 Result = SemaRef.Context.getDecayedType(OriginalType);
5140 TLB.push<DecayedTypeLoc>(Result);
5141 // Nothing to set for DecayedTypeLoc.
5142 return Result;
5143}
5144
5145template<typename Derived>
5146QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
5147 PointerTypeLoc TL) {
5148 QualType PointeeType
5149 = getDerived().TransformType(TLB, TL.getPointeeLoc());
5150 if (PointeeType.isNull())
5151 return QualType();
5152
5153 QualType Result = TL.getType();
5154 if (PointeeType->getAs<ObjCObjectType>()) {
5155 // A dependent pointer type 'T *' has is being transformed such
5156 // that an Objective-C class type is being replaced for 'T'. The
5157 // resulting pointer type is an ObjCObjectPointerType, not a
5158 // PointerType.
5159 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
5160
5161 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
5162 NewT.setStarLoc(TL.getStarLoc());
5163 return Result;
5164 }
5165
5166 if (getDerived().AlwaysRebuild() ||
5167 PointeeType != TL.getPointeeLoc().getType()) {
5168 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
5169 if (Result.isNull())
5170 return QualType();
5171 }
5172
5173 // Objective-C ARC can add lifetime qualifiers to the type that we're
5174 // pointing to.
5175 TLB.TypeWasModifiedSafely(Result->getPointeeType());
5176
5177 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
5178 NewT.setSigilLoc(TL.getSigilLoc());
5179 return Result;
5180}
5181
5182template<typename Derived>
5183QualType
5184TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
5185 BlockPointerTypeLoc TL) {
5186 QualType PointeeType
5187 = getDerived().TransformType(TLB, TL.getPointeeLoc());
5188 if (PointeeType.isNull())
5189 return QualType();
5190
5191 QualType Result = TL.getType();
5192 if (getDerived().AlwaysRebuild() ||
5193 PointeeType != TL.getPointeeLoc().getType()) {
5194 Result = getDerived().RebuildBlockPointerType(PointeeType,
5195 TL.getSigilLoc());
5196 if (Result.isNull())
5197 return QualType();
5198 }
5199
5200 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
5201 NewT.setSigilLoc(TL.getSigilLoc());
5202 return Result;
5203}
5204
5205/// Transforms a reference type. Note that somewhat paradoxically we
5206/// don't care whether the type itself is an l-value type or an r-value
5207/// type; we only care if the type was *written* as an l-value type
5208/// or an r-value type.
5209template<typename Derived>
5210QualType
5211TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
5212 ReferenceTypeLoc TL) {
5213 const ReferenceType *T = TL.getTypePtr();
5214
5215 // Note that this works with the pointee-as-written.
5216 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5217 if (PointeeType.isNull())
5218 return QualType();
5219
5220 QualType Result = TL.getType();
5221 if (getDerived().AlwaysRebuild() ||
5222 PointeeType != T->getPointeeTypeAsWritten()) {
5223 Result = getDerived().RebuildReferenceType(PointeeType,
5224 T->isSpelledAsLValue(),
5225 TL.getSigilLoc());
5226 if (Result.isNull())
5227 return QualType();
5228 }
5229
5230 // Objective-C ARC can add lifetime qualifiers to the type that we're
5231 // referring to.
5232 TLB.TypeWasModifiedSafely(
5233 Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
5234
5235 // r-value references can be rebuilt as l-value references.
5236 ReferenceTypeLoc NewTL;
5237 if (isa<LValueReferenceType>(Result))
5238 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
5239 else
5240 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
5241 NewTL.setSigilLoc(TL.getSigilLoc());
5242
5243 return Result;
5244}
5245
5246template<typename Derived>
5247QualType
5248TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
5249 LValueReferenceTypeLoc TL) {
5250 return TransformReferenceType(TLB, TL);
5251}
5252
5253template<typename Derived>
5254QualType
5255TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
5256 RValueReferenceTypeLoc TL) {
5257 return TransformReferenceType(TLB, TL);
5258}
5259
5260template<typename Derived>
5261QualType
5262TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
5263 MemberPointerTypeLoc TL) {
5264 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5265 if (PointeeType.isNull())
5266 return QualType();
5267
5268 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
5269 TypeSourceInfo *NewClsTInfo = nullptr;
5270 if (OldClsTInfo) {
5271 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
5272 if (!NewClsTInfo)
5273 return QualType();
5274 }
5275
5276 const MemberPointerType *T = TL.getTypePtr();
5277 QualType OldClsType = QualType(T->getClass(), 0);
5278 QualType NewClsType;
5279 if (NewClsTInfo)
5280 NewClsType = NewClsTInfo->getType();
5281 else {
5282 NewClsType = getDerived().TransformType(OldClsType);
5283 if (NewClsType.isNull())
5284 return QualType();
5285 }
5286
5287 QualType Result = TL.getType();
5288 if (getDerived().AlwaysRebuild() ||
5289 PointeeType != T->getPointeeType() ||
5290 NewClsType != OldClsType) {
5291 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
5292 TL.getStarLoc());
5293 if (Result.isNull())
5294 return QualType();
5295 }
5296
5297 // If we had to adjust the pointee type when building a member pointer, make
5298 // sure to push TypeLoc info for it.
5299 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
5300 if (MPT && PointeeType != MPT->getPointeeType()) {
5301 assert(isa<AdjustedType>(MPT->getPointeeType()))(static_cast <bool> (isa<AdjustedType>(MPT->getPointeeType
())) ? void (0) : __assert_fail ("isa<AdjustedType>(MPT->getPointeeType())"
, "clang/lib/Sema/TreeTransform.h", 5301, __extension__ __PRETTY_FUNCTION__
))
;
5302 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
5303 }
5304
5305 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
5306 NewTL.setSigilLoc(TL.getSigilLoc());
5307 NewTL.setClassTInfo(NewClsTInfo);
5308
5309 return Result;
5310}
5311
5312template<typename Derived>
5313QualType
5314TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
5315 ConstantArrayTypeLoc TL) {
5316 const ConstantArrayType *T = TL.getTypePtr();
5317 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5318 if (ElementType.isNull())
5319 return QualType();
5320
5321 // Prefer the expression from the TypeLoc; the other may have been uniqued.
5322 Expr *OldSize = TL.getSizeExpr();
5323 if (!OldSize)
5324 OldSize = const_cast<Expr*>(T->getSizeExpr());
5325 Expr *NewSize = nullptr;
5326 if (OldSize) {
5327 EnterExpressionEvaluationContext Unevaluated(
5328 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5329 NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
5330 NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
5331 }
5332
5333 QualType Result = TL.getType();
5334 if (getDerived().AlwaysRebuild() ||
5335 ElementType != T->getElementType() ||
5336 (T->getSizeExpr() && NewSize != OldSize)) {
5337 Result = getDerived().RebuildConstantArrayType(ElementType,
5338 T->getSizeModifier(),
5339 T->getSize(), NewSize,
5340 T->getIndexTypeCVRQualifiers(),
5341 TL.getBracketsRange());
5342 if (Result.isNull())
5343 return QualType();
5344 }
5345
5346 // We might have either a ConstantArrayType or a VariableArrayType now:
5347 // a ConstantArrayType is allowed to have an element type which is a
5348 // VariableArrayType if the type is dependent. Fortunately, all array
5349 // types have the same location layout.
5350 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5351 NewTL.setLBracketLoc(TL.getLBracketLoc());
5352 NewTL.setRBracketLoc(TL.getRBracketLoc());
5353 NewTL.setSizeExpr(NewSize);
5354
5355 return Result;
5356}
5357
5358template<typename Derived>
5359QualType TreeTransform<Derived>::TransformIncompleteArrayType(
5360 TypeLocBuilder &TLB,
5361 IncompleteArrayTypeLoc TL) {
5362 const IncompleteArrayType *T = TL.getTypePtr();
5363 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5364 if (ElementType.isNull())
5365 return QualType();
5366
5367 QualType Result = TL.getType();
5368 if (getDerived().AlwaysRebuild() ||
5369 ElementType != T->getElementType()) {
5370 Result = getDerived().RebuildIncompleteArrayType(ElementType,
5371 T->getSizeModifier(),
5372 T->getIndexTypeCVRQualifiers(),
5373 TL.getBracketsRange());
5374 if (Result.isNull())
5375 return QualType();
5376 }
5377
5378 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
5379 NewTL.setLBracketLoc(TL.getLBracketLoc());
5380 NewTL.setRBracketLoc(TL.getRBracketLoc());
5381 NewTL.setSizeExpr(nullptr);
5382
5383 return Result;
5384}
5385
5386template<typename Derived>
5387QualType
5388TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
5389 VariableArrayTypeLoc TL) {
5390 const VariableArrayType *T = TL.getTypePtr();
5391 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5392 if (ElementType.isNull())
5393 return QualType();
5394
5395 ExprResult SizeResult;
5396 {
5397 EnterExpressionEvaluationContext Context(
5398 SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5399 SizeResult = getDerived().TransformExpr(T->getSizeExpr());
5400 }
5401 if (SizeResult.isInvalid())
5402 return QualType();
5403 SizeResult =
5404 SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
5405 if (SizeResult.isInvalid())
5406 return QualType();
5407
5408 Expr *Size = SizeResult.get();
5409
5410 QualType Result = TL.getType();
5411 if (getDerived().AlwaysRebuild() ||
5412 ElementType != T->getElementType() ||
5413 Size != T->getSizeExpr()) {
5414 Result = getDerived().RebuildVariableArrayType(ElementType,
5415 T->getSizeModifier(),
5416 Size,
5417 T->getIndexTypeCVRQualifiers(),
5418 TL.getBracketsRange());
5419 if (Result.isNull())
5420 return QualType();
5421 }
5422
5423 // We might have constant size array now, but fortunately it has the same
5424 // location layout.
5425 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5426 NewTL.setLBracketLoc(TL.getLBracketLoc());
5427 NewTL.setRBracketLoc(TL.getRBracketLoc());
5428 NewTL.setSizeExpr(Size);
5429
5430 return Result;
5431}
5432
5433template<typename Derived>
5434QualType
5435TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
5436 DependentSizedArrayTypeLoc TL) {
5437 const DependentSizedArrayType *T = TL.getTypePtr();
5438 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5439 if (ElementType.isNull())
5440 return QualType();
5441
5442 // Array bounds are constant expressions.
5443 EnterExpressionEvaluationContext Unevaluated(
5444 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5445
5446 // Prefer the expression from the TypeLoc; the other may have been uniqued.
5447 Expr *origSize = TL.getSizeExpr();
5448 if (!origSize) origSize = T->getSizeExpr();
5449
5450 ExprResult sizeResult
5451 = getDerived().TransformExpr(origSize);
5452 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
5453 if (sizeResult.isInvalid())
5454 return QualType();
5455
5456 Expr *size = sizeResult.get();
5457
5458 QualType Result = TL.getType();
5459 if (getDerived().AlwaysRebuild() ||
5460 ElementType != T->getElementType() ||
5461 size != origSize) {
5462 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
5463 T->getSizeModifier(),
5464 size,
5465 T->getIndexTypeCVRQualifiers(),
5466 TL.getBracketsRange());
5467 if (Result.isNull())
5468 return QualType();
5469 }
5470
5471 // We might have any sort of array type now, but fortunately they
5472 // all have the same location layout.
5473 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5474 NewTL.setLBracketLoc(TL.getLBracketLoc());
5475 NewTL.setRBracketLoc(TL.getRBracketLoc());
5476 NewTL.setSizeExpr(size);
5477
5478 return Result;
5479}
5480
5481template <typename Derived>
5482QualType TreeTransform<Derived>::TransformDependentVectorType(
5483 TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
5484 const DependentVectorType *T = TL.getTypePtr();
5485 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5486 if (ElementType.isNull())
5487 return QualType();
5488
5489 EnterExpressionEvaluationContext Unevaluated(
5490 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5491
5492 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5493 Size = SemaRef.ActOnConstantExpression(Size);
5494 if (Size.isInvalid())
5495 return QualType();
5496
5497 QualType Result = TL.getType();
5498 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5499 Size.get() != T->getSizeExpr()) {
5500 Result = getDerived().RebuildDependentVectorType(
5501 ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5502 if (Result.isNull())
5503 return QualType();
5504 }
5505
5506 // Result might be dependent or not.
5507 if (isa<DependentVectorType>(Result)) {
5508 DependentVectorTypeLoc NewTL =
5509 TLB.push<DependentVectorTypeLoc>(Result);
5510 NewTL.setNameLoc(TL.getNameLoc());
5511 } else {
5512 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5513 NewTL.setNameLoc(TL.getNameLoc());
5514 }
5515
5516 return Result;
5517}
5518
5519template<typename Derived>
5520QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5521 TypeLocBuilder &TLB,
5522 DependentSizedExtVectorTypeLoc TL) {
5523 const DependentSizedExtVectorType *T = TL.getTypePtr();
5524
5525 // FIXME: ext vector locs should be nested
5526 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5527 if (ElementType.isNull())
5528 return QualType();
5529
5530 // Vector sizes are constant expressions.
5531 EnterExpressionEvaluationContext Unevaluated(
5532 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5533
5534 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5535 Size = SemaRef.ActOnConstantExpression(Size);
5536 if (Size.isInvalid())
5537 return QualType();
5538
5539 QualType Result = TL.getType();
5540 if (getDerived().AlwaysRebuild() ||
5541 ElementType != T->getElementType() ||
5542 Size.get() != T->getSizeExpr()) {
5543 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5544 Size.get(),
5545 T->getAttributeLoc());
5546 if (Result.isNull())
5547 return QualType();
5548 }
5549
5550 // Result might be dependent or not.
5551 if (isa<DependentSizedExtVectorType>(Result)) {
5552 DependentSizedExtVectorTypeLoc NewTL
5553 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5554 NewTL.setNameLoc(TL.getNameLoc());
5555 } else {
5556 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5557 NewTL.setNameLoc(TL.getNameLoc());
5558 }
5559
5560 return Result;
5561}
5562
5563template <typename Derived>
5564QualType
5565TreeTransform<Derived>::TransformConstantMatrixType(TypeLocBuilder &TLB,
5566 ConstantMatrixTypeLoc TL) {
5567 const ConstantMatrixType *T = TL.getTypePtr();
5568 QualType ElementType = getDerived().TransformType(T->getElementType());
5569 if (ElementType.isNull())
5570 return QualType();
5571
5572 QualType Result = TL.getType();
5573 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType()) {
5574 Result = getDerived().RebuildConstantMatrixType(
5575 ElementType, T->getNumRows(), T->getNumColumns());
5576 if (Result.isNull())
5577 return QualType();
5578 }
5579
5580 ConstantMatrixTypeLoc NewTL = TLB.push<ConstantMatrixTypeLoc>(Result);
5581 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5582 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5583 NewTL.setAttrRowOperand(TL.getAttrRowOperand());
5584 NewTL.setAttrColumnOperand(TL.getAttrColumnOperand());
5585
5586 return Result;
5587}
5588
5589template <typename Derived>
5590QualType TreeTransform<Derived>::TransformDependentSizedMatrixType(
5591 TypeLocBuilder &TLB, DependentSizedMatrixTypeLoc TL) {
5592 const DependentSizedMatrixType *T = TL.getTypePtr();
5593
5594 QualType ElementType = getDerived().TransformType(T->getElementType());
5595 if (ElementType.isNull()) {
5596 return QualType();
5597 }
5598
5599 // Matrix dimensions are constant expressions.
5600 EnterExpressionEvaluationContext Unevaluated(
5601 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5602
5603 Expr *origRows = TL.getAttrRowOperand();
5604 if (!origRows)
5605 origRows = T->getRowExpr();
5606 Expr *origColumns = TL.getAttrColumnOperand();
5607 if (!origColumns)
5608 origColumns = T->getColumnExpr();
5609
5610 ExprResult rowResult = getDerived().TransformExpr(origRows);
5611 rowResult = SemaRef.ActOnConstantExpression(rowResult);
5612 if (rowResult.isInvalid())
5613 return QualType();
5614
5615 ExprResult columnResult = getDerived().TransformExpr(origColumns);
5616 columnResult = SemaRef.ActOnConstantExpression(columnResult);
5617 if (columnResult.isInvalid())
5618 return QualType();
5619
5620 Expr *rows = rowResult.get();
5621 Expr *columns = columnResult.get();
5622
5623 QualType Result = TL.getType();
5624 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5625 rows != origRows || columns != origColumns) {
5626 Result = getDerived().RebuildDependentSizedMatrixType(
5627 ElementType, rows, columns, T->getAttributeLoc());
5628
5629 if (Result.isNull())
5630 return QualType();
5631 }
5632
5633 // We might have any sort of matrix type now, but fortunately they
5634 // all have the same location layout.
5635 MatrixTypeLoc NewTL = TLB.push<MatrixTypeLoc>(Result);
5636 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5637 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5638 NewTL.setAttrRowOperand(rows);
5639 NewTL.setAttrColumnOperand(columns);
5640 return Result;
5641}
5642
5643template <typename Derived>
5644QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5645 TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5646 const DependentAddressSpaceType *T = TL.getTypePtr();
5647
5648 QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5649
5650 if (pointeeType.isNull())
5651 return QualType();
5652
5653 // Address spaces are constant expressions.
5654 EnterExpressionEvaluationContext Unevaluated(
5655 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5656
5657 ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5658 AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5659 if (AddrSpace.isInvalid())
5660 return QualType();
5661
5662 QualType Result = TL.getType();
5663 if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5664 AddrSpace.get() != T->getAddrSpaceExpr()) {
5665 Result = getDerived().RebuildDependentAddressSpaceType(
5666 pointeeType, AddrSpace.get(), T->getAttributeLoc());
5667 if (Result.isNull())
5668 return QualType();
5669 }
5670
5671 // Result might be dependent or not.
5672 if (isa<DependentAddressSpaceType>(Result)) {
5673 DependentAddressSpaceTypeLoc NewTL =
5674 TLB.push<DependentAddressSpaceTypeLoc>(Result);
5675
5676 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5677 NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5678 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5679
5680 } else {
5681 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5682 Result, getDerived().getBaseLocation());
5683 TransformType(TLB, DI->getTypeLoc());
5684 }
5685
5686 return Result;
5687}
5688
5689template <typename Derived>
5690QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5691 VectorTypeLoc TL) {
5692 const VectorType *T = TL.getTypePtr();
5693 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5694 if (ElementType.isNull())
5695 return QualType();
5696
5697 QualType Result = TL.getType();
5698 if (getDerived().AlwaysRebuild() ||
5699 ElementType != T->getElementType()) {
5700 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5701 T->getVectorKind());
5702 if (Result.isNull())
5703 return QualType();
5704 }
5705
5706 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5707 NewTL.setNameLoc(TL.getNameLoc());
5708
5709 return Result;
5710}
5711
5712template<typename Derived>
5713QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5714 ExtVectorTypeLoc TL) {
5715 const VectorType *T = TL.getTypePtr();
5716 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5717 if (ElementType.isNull())
5718 return QualType();
5719
5720 QualType Result = TL.getType();
5721 if (getDerived().AlwaysRebuild() ||
5722 ElementType != T->getElementType()) {
5723 Result = getDerived().RebuildExtVectorType(ElementType,
5724 T->getNumElements(),
5725 /*FIXME*/ SourceLocation());
5726 if (Result.isNull())
5727 return QualType();
5728 }
5729
5730 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5731 NewTL.setNameLoc(TL.getNameLoc());
5732
5733 return Result;
5734}
5735
5736template <typename Derived>
5737ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5738 ParmVarDecl *OldParm, int indexAdjustment,
5739 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
5740 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5741 TypeSourceInfo *NewDI = nullptr;
5742
5743 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5744 // If we're substituting into a pack expansion type and we know the
5745 // length we want to expand to, just substitute for the pattern.
5746 TypeLoc OldTL = OldDI->getTypeLoc();
5747 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5748
5749 TypeLocBuilder TLB;
5750 TypeLoc NewTL = OldDI->getTypeLoc();
5751 TLB.reserve(NewTL.getFullDataSize());
5752
5753 QualType Result = getDerived().TransformType(TLB,
5754 OldExpansionTL.getPatternLoc());
5755 if (Result.isNull())
5756 return nullptr;
5757
5758 Result = RebuildPackExpansionType(Result,
5759 OldExpansionTL.getPatternLoc().getSourceRange(),
5760 OldExpansionTL.getEllipsisLoc(),
5761 NumExpansions);
5762 if (Result.isNull())
5763 return nullptr;
5764
5765 PackExpansionTypeLoc NewExpansionTL
5766 = TLB.push<PackExpansionTypeLoc>(Result);
5767 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5768 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5769 } else
5770 NewDI = getDerived().TransformType(OldDI);
5771 if (!NewDI)
5772 return nullptr;
5773
5774 if (NewDI == OldDI && indexAdjustment == 0)
5775 return OldParm;
5776
5777 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5778 OldParm->getDeclContext(),
5779 OldParm->getInnerLocStart(),
5780 OldParm->getLocation(),
5781 OldParm->getIdentifier(),
5782 NewDI->getType(),
5783 NewDI,
5784 OldParm->getStorageClass(),
5785 /* DefArg */ nullptr);
5786 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5787 OldParm->getFunctionScopeIndex() + indexAdjustment);
5788 transformedLocalDecl(OldParm, {newParm});
5789 return newParm;
5790}
5791
5792template <typename Derived>
5793bool TreeTransform<Derived>::TransformFunctionTypeParams(
5794 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5795 const QualType *ParamTypes,
5796 const FunctionProtoType::ExtParameterInfo *ParamInfos,
5797 SmallVectorImpl<QualType> &OutParamTypes,
5798 SmallVectorImpl<ParmVarDecl *> *PVars,
5799 Sema::ExtParameterInfoBuilder &PInfos,
5800 unsigned *LastParamTransformed) {
5801 int indexAdjustment = 0;
5802
5803 unsigned NumParams = Params.size();
5804 for (unsigned i = 0; i != NumParams; ++i) {
5805 if (LastParamTransformed)
5806 *LastParamTransformed = i;
5807 if (ParmVarDecl *OldParm = Params[i]) {
5808 assert(OldParm->getFunctionScopeIndex() == i)(static_cast <bool> (OldParm->getFunctionScopeIndex(
) == i) ? void (0) : __assert_fail ("OldParm->getFunctionScopeIndex() == i"
, "clang/lib/Sema/TreeTransform.h", 5808, __extension__ __PRETTY_FUNCTION__
))
;
5809
5810 std::optional<unsigned> NumExpansions;
5811 ParmVarDecl *NewParm = nullptr;
5812 if (OldParm->isParameterPack()) {
5813 // We have a function parameter pack that may need to be expanded.
5814 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5815
5816 // Find the parameter packs that could be expanded.
5817 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5818 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5819 TypeLoc Pattern = ExpansionTL.getPatternLoc();
5820 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5821
5822 // Determine whether we should expand the parameter packs.
5823 bool ShouldExpand = false;
5824 bool RetainExpansion = false;
5825 std::optional<unsigned> OrigNumExpansions;
5826 if (Unexpanded.size() > 0) {
5827 OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5828 NumExpansions = OrigNumExpansions;
5829 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5830 Pattern.getSourceRange(),
5831 Unexpanded,
5832 ShouldExpand,
5833 RetainExpansion,
5834 NumExpansions)) {
5835 return true;
5836 }
5837 } else {
5838#ifndef NDEBUG
5839 const AutoType *AT =
5840 Pattern.getType().getTypePtr()->getContainedAutoType();
5841 assert((AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) &&(static_cast <bool> ((AT && (!AT->isDeduced(
) || AT->getDeducedType().isNull())) && "Could not find parameter packs or undeduced auto type!"
) ? void (0) : __assert_fail ("(AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) && \"Could not find parameter packs or undeduced auto type!\""
, "clang/lib/Sema/TreeTransform.h", 5842, __extension__ __PRETTY_FUNCTION__
))
5842 "Could not find parameter packs or undeduced auto type!")(static_cast <bool> ((AT && (!AT->isDeduced(
) || AT->getDeducedType().isNull())) && "Could not find parameter packs or undeduced auto type!"
) ? void (0) : __assert_fail ("(AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) && \"Could not find parameter packs or undeduced auto type!\""
, "clang/lib/Sema/TreeTransform.h", 5842, __extension__ __PRETTY_FUNCTION__
))
;
5843#endif
5844 }
5845
5846 if (ShouldExpand) {
5847 // Expand the function parameter pack into multiple, separate
5848 // parameters.
5849 getDerived().ExpandingFunctionParameterPack(OldParm);
5850 for (unsigned I = 0; I != *NumExpansions; ++I) {
5851 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5852 ParmVarDecl *NewParm
5853 = getDerived().TransformFunctionTypeParam(OldParm,
5854 indexAdjustment++,
5855 OrigNumExpansions,
5856 /*ExpectParameterPack=*/false);
5857 if (!NewParm)
5858 return true;
5859
5860 if (ParamInfos)
5861 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5862 OutParamTypes.push_back(NewParm->getType());
5863 if (PVars)
5864 PVars->push_back(NewParm);
5865 }
5866
5867 // If we're supposed to retain a pack expansion, do so by temporarily
5868 // forgetting the partially-substituted parameter pack.
5869 if (RetainExpansion) {
5870 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5871 ParmVarDecl *NewParm
5872 = getDerived().TransformFunctionTypeParam(OldParm,
5873 indexAdjustment++,
5874 OrigNumExpansions,
5875 /*ExpectParameterPack=*/false);
5876 if (!NewParm)
5877 return true;
5878
5879 if (ParamInfos)
5880 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5881 OutParamTypes.push_back(NewParm->getType());
5882 if (PVars)
5883 PVars->push_back(NewParm);
5884 }
5885
5886 // The next parameter should have the same adjustment as the
5887 // last thing we pushed, but we post-incremented indexAdjustment
5888 // on every push. Also, if we push nothing, the adjustment should
5889 // go down by one.
5890 indexAdjustment--;
5891
5892 // We're done with the pack expansion.
5893 continue;
5894 }
5895
5896 // We'll substitute the parameter now without expanding the pack
5897 // expansion.
5898 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5899 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5900 indexAdjustment,
5901 NumExpansions,
5902 /*ExpectParameterPack=*/true);
5903 assert(NewParm->isParameterPack() &&(static_cast <bool> (NewParm->isParameterPack() &&
"Parameter pack no longer a parameter pack after " "transformation."
) ? void (0) : __assert_fail ("NewParm->isParameterPack() && \"Parameter pack no longer a parameter pack after \" \"transformation.\""
, "clang/lib/Sema/TreeTransform.h", 5905, __extension__ __PRETTY_FUNCTION__
))
5904 "Parameter pack no longer a parameter pack after "(static_cast <bool> (NewParm->isParameterPack() &&
"Parameter pack no longer a parameter pack after " "transformation."
) ? void (0) : __assert_fail ("NewParm->isParameterPack() && \"Parameter pack no longer a parameter pack after \" \"transformation.\""
, "clang/lib/Sema/TreeTransform.h", 5905, __extension__ __PRETTY_FUNCTION__
))
5905 "transformation.")(static_cast <bool> (NewParm->isParameterPack() &&
"Parameter pack no longer a parameter pack after " "transformation."
) ? void (0) : __assert_fail ("NewParm->isParameterPack() && \"Parameter pack no longer a parameter pack after \" \"transformation.\""
, "clang/lib/Sema/TreeTransform.h", 5905, __extension__ __PRETTY_FUNCTION__
))
;
5906 } else {
5907 NewParm = getDerived().TransformFunctionTypeParam(
5908 OldParm, indexAdjustment, std::nullopt,
5909 /*ExpectParameterPack=*/false);
5910 }
5911
5912 if (!NewParm)
5913 return true;
5914
5915 if (ParamInfos)
5916 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5917 OutParamTypes.push_back(NewParm->getType());
5918 if (PVars)
5919 PVars->push_back(NewParm);
5920 continue;
5921 }
5922
5923 // Deal with the possibility that we don't have a parameter
5924 // declaration for this parameter.
5925 assert(ParamTypes)(static_cast <bool> (ParamTypes) ? void (0) : __assert_fail
("ParamTypes", "clang/lib/Sema/TreeTransform.h", 5925, __extension__
__PRETTY_FUNCTION__))
;
5926 QualType OldType = ParamTypes[i];
5927 bool IsPackExpansion = false;
5928 std::optional<unsigned> NumExpansions;
5929 QualType NewType;
5930 if (const PackExpansionType *Expansion
5931 = dyn_cast<PackExpansionType>(OldType)) {
5932 // We have a function parameter pack that may need to be expanded.
5933 QualType Pattern = Expansion->getPattern();
5934 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5935 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5936
5937 // Determine whether we should expand the parameter packs.
5938 bool ShouldExpand = false;
5939 bool RetainExpansion = false;
5940 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5941 Unexpanded,
5942 ShouldExpand,
5943 RetainExpansion,
5944 NumExpansions)) {
5945 return true;
5946 }
5947
5948 if (ShouldExpand) {
5949 // Expand the function parameter pack into multiple, separate
5950 // parameters.
5951 for (unsigned I = 0; I != *NumExpansions; ++I) {
5952 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5953 QualType NewType = getDerived().TransformType(Pattern);
5954 if (NewType.isNull())
5955 return true;
5956
5957 if (NewType->containsUnexpandedParameterPack()) {
5958 NewType = getSema().getASTContext().getPackExpansionType(
5959 NewType, std::nullopt);
5960
5961 if (NewType.isNull())
5962 return true;
5963 }
5964
5965 if (ParamInfos)
5966 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5967 OutParamTypes.push_back(NewType);
5968 if (PVars)
5969 PVars->push_back(nullptr);
5970 }
5971
5972 // We're done with the pack expansion.
5973 continue;
5974 }
5975
5976 // If we're supposed to retain a pack expansion, do so by temporarily
5977 // forgetting the partially-substituted parameter pack.
5978 if (RetainExpansion) {
5979 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5980 QualType NewType = getDerived().TransformType(Pattern);
5981 if (NewType.isNull())
5982 return true;
5983
5984 if (ParamInfos)
5985 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5986 OutParamTypes.push_back(NewType);
5987 if (PVars)
5988 PVars->push_back(nullptr);
5989 }
5990
5991 // We'll substitute the parameter now without expanding the pack
5992 // expansion.
5993 OldType = Expansion->getPattern();
5994 IsPackExpansion = true;
5995 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5996 NewType = getDerived().TransformType(OldType);
5997 } else {
5998 NewType = getDerived().TransformType(OldType);
5999 }
6000
6001 if (NewType.isNull())
6002 return true;
6003
6004 if (IsPackExpansion)
6005 NewType = getSema().Context.getPackExpansionType(NewType,
6006 NumExpansions);
6007
6008 if (ParamInfos)
6009 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
6010 OutParamTypes.push_back(NewType);
6011 if (PVars)
6012 PVars->push_back(nullptr);
6013 }
6014
6015#ifndef NDEBUG
6016 if (PVars) {
6017 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
6018 if (ParmVarDecl *parm = (*PVars)[i])
6019 assert(parm->getFunctionScopeIndex() == i)(static_cast <bool> (parm->getFunctionScopeIndex() ==
i) ? void (0) : __assert_fail ("parm->getFunctionScopeIndex() == i"
, "clang/lib/Sema/TreeTransform.h", 6019, __extension__ __PRETTY_FUNCTION__
))
;
6020 }
6021#endif
6022
6023 return false;
6024}
6025
6026template<typename Derived>
6027QualType
6028TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
6029 FunctionProtoTypeLoc TL) {
6030 SmallVector<QualType, 4> ExceptionStorage;
6031 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
6032 return getDerived().TransformFunctionProtoType(
6033 TLB, TL, nullptr, Qualifiers(),
6034 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
6035 return This->getDerived().TransformExceptionSpec(
6036 TL.getBeginLoc(), ESI, ExceptionStorage, Changed);
6037 });
6038}
6039
6040template<typename Derived> template<typename Fn>
6041QualType TreeTransform<Derived>::TransformFunctionProtoType(
6042 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
6043 Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
6044
6045 // Transform the parameters and return type.
6046 //
6047 // We are required to instantiate the params and return type in source order.
6048 // When the function has a trailing return type, we instantiate the
6049 // parameters before the return type, since the return type can then refer
6050 // to the parameters themselves (via decltype, sizeof, etc.).
6051 //
6052 SmallVector<QualType, 4> ParamTypes;
6053 SmallVector<ParmVarDecl*, 4> ParamDecls;
6054 Sema::ExtParameterInfoBuilder ExtParamInfos;
6055 const FunctionProtoType *T = TL.getTypePtr();
6056
6057 QualType ResultType;
6058
6059 if (T->hasTrailingReturn()) {
6060 if (getDerived().TransformFunctionTypeParams(
6061 TL.getBeginLoc(), TL.getParams(),
6062 TL.getTypePtr()->param_type_begin(),
6063 T->getExtParameterInfosOrNull(),
6064 ParamTypes, &ParamDecls, ExtParamInfos))
6065 return QualType();
6066
6067 {
6068 // C++11 [expr.prim.general]p3:
6069 // If a declaration declares a member function or member function
6070 // template of a class X, the expression this is a prvalue of type
6071 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6072 // and the end of the function-definition, member-declarator, or
6073 // declarator.
6074 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
6075
6076 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6077 if (ResultType.isNull())
6078 return QualType();
6079 }
6080 }
6081 else {
6082 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6083 if (ResultType.isNull())
6084 return QualType();
6085
6086 if (getDerived().TransformFunctionTypeParams(
6087 TL.getBeginLoc(), TL.getParams(),
6088 TL.getTypePtr()->param_type_begin(),
6089 T->getExtParameterInfosOrNull(),
6090 ParamTypes, &ParamDecls, ExtParamInfos))
6091 return QualType();
6092 }
6093
6094 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
6095
6096 bool EPIChanged = false;
6097 if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
6098 return QualType();
6099
6100 // Handle extended parameter information.
6101 if (auto NewExtParamInfos =
6102 ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
6103 if (!EPI.ExtParameterInfos ||
6104 llvm::ArrayRef(EPI.ExtParameterInfos, TL.getNumParams()) !=
6105 llvm::ArrayRef(NewExtParamInfos, ParamTypes.size())) {
6106 EPIChanged = true;
6107 }
6108 EPI.ExtParameterInfos = NewExtParamInfos;
6109 } else if (EPI.ExtParameterInfos) {
6110 EPIChanged = true;
6111 EPI.ExtParameterInfos = nullptr;
6112 }
6113
6114 QualType Result = TL.getType();
6115 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
6116 T->getParamTypes() != llvm::ArrayRef(ParamTypes) || EPIChanged) {
6117 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
6118 if (Result.isNull())
6119 return QualType();
6120 }
6121
6122 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
6123 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6124 NewTL.setLParenLoc(TL.getLParenLoc());
6125 NewTL.setRParenLoc(TL.getRParenLoc());
6126 NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
6127 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6128 for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
6129 NewTL.setParam(i, ParamDecls[i]);
6130
6131 return Result;
6132}
6133
6134template<typename Derived>
6135bool TreeTransform<Derived>::TransformExceptionSpec(
6136 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
6137 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
6138 assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated)(static_cast <bool> (ESI.Type != EST_Uninstantiated &&
ESI.Type != EST_Unevaluated) ? void (0) : __assert_fail ("ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated"
, "clang/lib/Sema/TreeTransform.h", 6138, __extension__ __PRETTY_FUNCTION__
))
;
6139
6140 // Instantiate a dynamic noexcept expression, if any.
6141 if (isComputedNoexcept(ESI.Type)) {
6142 EnterExpressionEvaluationContext Unevaluated(
6143 getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
6144 ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
6145 if (NoexceptExpr.isInvalid())
6146 return true;
6147
6148 ExceptionSpecificationType EST = ESI.Type;
6149 NoexceptExpr =
6150 getSema().ActOnNoexceptSpec(NoexceptExpr.get(), EST);
6151 if (NoexceptExpr.isInvalid())
6152 return true;
6153
6154 if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
6155 Changed = true;
6156 ESI.NoexceptExpr = NoexceptExpr.get();
6157 ESI.Type = EST;
6158 }
6159
6160 if (ESI.Type != EST_Dynamic)
6161 return false;
6162
6163 // Instantiate a dynamic exception specification's type.
6164 for (QualType T : ESI.Exceptions) {
6165 if (const PackExpansionType *PackExpansion =
6166 T->getAs<PackExpansionType>()) {
6167 Changed = true;
6168
6169 // We have a pack expansion. Instantiate it.
6170 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6171 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6172 Unexpanded);
6173 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 6173, __extension__ __PRETTY_FUNCTION__
))
;
6174
6175 // Determine whether the set of unexpanded parameter packs can and
6176 // should
6177 // be expanded.
6178 bool Expand = false;
6179 bool RetainExpansion = false;
6180 std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6181 // FIXME: Track the location of the ellipsis (and track source location
6182 // information for the types in the exception specification in general).
6183 if (getDerived().TryExpandParameterPacks(
6184 Loc, SourceRange(), Unexpanded, Expand,
6185 RetainExpansion, NumExpansions))
6186 return true;
6187
6188 if (!Expand) {
6189 // We can't expand this pack expansion into separate arguments yet;
6190 // just substitute into the pattern and create a new pack expansion
6191 // type.
6192 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6193 QualType U = getDerived().TransformType(PackExpansion->getPattern());
6194 if (U.isNull())
6195 return true;
6196
6197 U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
6198 Exceptions.push_back(U);
6199 continue;
6200 }
6201
6202 // Substitute into the pack expansion pattern for each slice of the
6203 // pack.
6204 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6205 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6206
6207 QualType U = getDerived().TransformType(PackExpansion->getPattern());
6208 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6209 return true;
6210
6211 Exceptions.push_back(U);
6212 }
6213 } else {
6214 QualType U = getDerived().TransformType(T);
6215 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6216 return true;
6217 if (T != U)
6218 Changed = true;
6219
6220 Exceptions.push_back(U);
6221 }
6222 }
6223
6224 ESI.Exceptions = Exceptions;
6225 if (ESI.Exceptions.empty())
6226 ESI.Type = EST_DynamicNone;
6227 return false;
6228}
6229
6230template<typename Derived>
6231QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
6232 TypeLocBuilder &TLB,
6233 FunctionNoProtoTypeLoc TL) {
6234 const FunctionNoProtoType *T = TL.getTypePtr();
6235 QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6236 if (ResultType.isNull())
6237 return QualType();
6238
6239 QualType Result = TL.getType();
6240 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
6241 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
6242
6243 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
6244 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6245 NewTL.setLParenLoc(TL.getLParenLoc());
6246 NewTL.setRParenLoc(TL.getRParenLoc());
6247 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6248
6249 return Result;
6250}
6251
6252template <typename Derived>
6253QualType TreeTransform<Derived>::TransformUnresolvedUsingType(
6254 TypeLocBuilder &TLB, UnresolvedUsingTypeLoc TL) {
6255 const UnresolvedUsingType *T = TL.getTypePtr();
6256 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
6257 if (!D)
6258 return QualType();
6259
6260 QualType Result = TL.getType();
6261 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
6262 Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
6263 if (Result.isNull())
6264 return QualType();
6265 }
6266
6267 // We might get an arbitrary type spec type back. We should at
6268 // least always get a type spec type, though.
6269 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
6270 NewTL.setNameLoc(TL.getNameLoc());
6271
6272 return Result;
6273}
6274
6275template <typename Derived>
6276QualType TreeTransform<Derived>::TransformUsingType(TypeLocBuilder &TLB,
6277 UsingTypeLoc TL) {
6278 const UsingType *T = TL.getTypePtr();
6279
6280 auto *Found = cast_or_null<UsingShadowDecl>(getDerived().TransformDecl(
6281 TL.getLocalSourceRange().getBegin(), T->getFoundDecl()));
6282 if (!Found)
6283 return QualType();
6284
6285 QualType Underlying = getDerived().TransformType(T->desugar());
6286 if (Underlying.isNull())
6287 return QualType();
6288
6289 QualType Result = TL.getType();
6290 if (getDerived().AlwaysRebuild() || Found != T->getFoundDecl() ||
6291 Underlying != T->getUnderlyingType()) {
6292 Result = getDerived().RebuildUsingType(Found, Underlying);
6293 if (Result.isNull())
6294 return QualType();
6295 }
6296
6297 TLB.pushTypeSpec(Result).setNameLoc(TL.getNameLoc());
6298 return Result;
6299}
6300
6301template<typename Derived>
6302QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
6303 TypedefTypeLoc TL) {
6304 const TypedefType *T = TL.getTypePtr();
6305 TypedefNameDecl *Typedef
6306 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6307 T->getDecl()));
6308 if (!Typedef)
6309 return QualType();
6310
6311 QualType Result = TL.getType();
6312 if (getDerived().AlwaysRebuild() ||
6313 Typedef != T->getDecl()) {
6314 Result = getDerived().RebuildTypedefType(Typedef);
6315 if (Result.isNull())
6316 return QualType();
6317 }
6318
6319 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
6320 NewTL.setNameLoc(TL.getNameLoc());
6321
6322 return Result;
6323}
6324
6325template<typename Derived>
6326QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
6327 TypeOfExprTypeLoc TL) {
6328 // typeof expressions are not potentially evaluated contexts
6329 EnterExpressionEvaluationContext Unevaluated(
6330 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
6331 Sema::ReuseLambdaContextDecl);
6332
6333 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
6334 if (E.isInvalid())
6335 return QualType();
6336
6337 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
6338 if (E.isInvalid())
6339 return QualType();
6340
6341 QualType Result = TL.getType();
6342 TypeOfKind Kind = Result->getAs<TypeOfExprType>()->getKind();
6343 if (getDerived().AlwaysRebuild() || E.get() != TL.getUnderlyingExpr()) {
6344 Result =
6345 getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc(), Kind);
6346 if (Result.isNull())
6347 return QualType();
6348 }
6349
6350 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
6351 NewTL.setTypeofLoc(TL.getTypeofLoc());
6352 NewTL.setLParenLoc(TL.getLParenLoc());
6353 NewTL.setRParenLoc(TL.getRParenLoc());
6354
6355 return Result;
6356}
6357
6358template<typename Derived>
6359QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
6360 TypeOfTypeLoc TL) {
6361 TypeSourceInfo* Old_Under_TI = TL.getUnmodifiedTInfo();
6362 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
6363 if (!New_Under_TI)
6364 return QualType();
6365
6366 QualType Result = TL.getType();
6367 TypeOfKind Kind = Result->getAs<TypeOfType>()->getKind();
6368 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
6369 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType(), Kind);
6370 if (Result.isNull())
6371 return QualType();
6372 }
6373
6374 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
6375 NewTL.setTypeofLoc(TL.getTypeofLoc());
6376 NewTL.setLParenLoc(TL.getLParenLoc());
6377 NewTL.setRParenLoc(TL.getRParenLoc());
6378 NewTL.setUnmodifiedTInfo(New_Under_TI);
6379
6380 return Result;
6381}
6382
6383template<typename Derived>
6384QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
6385 DecltypeTypeLoc TL) {
6386 const DecltypeType *T = TL.getTypePtr();
6387
6388 // decltype expressions are not potentially evaluated contexts
6389 EnterExpressionEvaluationContext Unevaluated(
6390 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
6391 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
6392
6393 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
6394 if (E.isInvalid())
6395 return QualType();
6396
6397 E = getSema().ActOnDecltypeExpression(E.get());
6398 if (E.isInvalid())
6399 return QualType();
6400
6401 QualType Result = TL.getType();
6402 if (getDerived().AlwaysRebuild() ||
6403 E.get() != T->getUnderlyingExpr()) {
6404 Result = getDerived().RebuildDecltypeType(E.get(), TL.getDecltypeLoc());
6405 if (Result.isNull())
6406 return QualType();
6407 }
6408 else E.get();
6409
6410 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
6411 NewTL.setDecltypeLoc(TL.getDecltypeLoc());
6412 NewTL.setRParenLoc(TL.getRParenLoc());
6413 return Result;
6414}
6415
6416template<typename Derived>
6417QualType TreeTransform<Derived>::TransformUnaryTransformType(
6418 TypeLocBuilder &TLB,
6419 UnaryTransformTypeLoc TL) {
6420 QualType Result = TL.getType();
6421 if (Result->isDependentType()) {
6422 const UnaryTransformType *T = TL.getTypePtr();
6423 QualType NewBase =
6424 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
6425 Result = getDerived().RebuildUnaryTransformType(NewBase,
6426 T->getUTTKind(),
6427 TL.getKWLoc());
6428 if (Result.isNull())
6429 return QualType();
6430 }
6431
6432 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
6433 NewTL.setKWLoc(TL.getKWLoc());
6434 NewTL.setParensRange(TL.getParensRange());
6435 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
6436 return Result;
6437}
6438
6439template<typename Derived>
6440QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
6441 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
6442 const DeducedTemplateSpecializationType *T = TL.getTypePtr();
6443
6444 CXXScopeSpec SS;
6445 TemplateName TemplateName = getDerived().TransformTemplateName(
6446 SS, T->getTemplateName(), TL.getTemplateNameLoc());
6447 if (TemplateName.isNull())
6448 return QualType();
6449
6450 QualType OldDeduced = T->getDeducedType();
6451 QualType NewDeduced;
6452 if (!OldDeduced.isNull()) {
6453 NewDeduced = getDerived().TransformType(OldDeduced);
6454 if (NewDeduced.isNull())
6455 return QualType();
6456 }
6457
6458 QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
6459 TemplateName, NewDeduced);
6460 if (Result.isNull())
6461 return QualType();
6462
6463 DeducedTemplateSpecializationTypeLoc NewTL =
6464 TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
6465 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6466
6467 return Result;
6468}
6469
6470template<typename Derived>
6471QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
6472 RecordTypeLoc TL) {
6473 const RecordType *T = TL.getTypePtr();
6474 RecordDecl *Record
6475 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6476 T->getDecl()));
6477 if (!Record)
6478 return QualType();
6479
6480 QualType Result = TL.getType();
6481 if (getDerived().AlwaysRebuild() ||
6482 Record != T->getDecl()) {
6483 Result = getDerived().RebuildRecordType(Record);
6484 if (Result.isNull())
6485 return QualType();
6486 }
6487
6488 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6489 NewTL.setNameLoc(TL.getNameLoc());
6490
6491 return Result;
6492}
6493
6494template<typename Derived>
6495QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
6496 EnumTypeLoc TL) {
6497 const EnumType *T = TL.getTypePtr();
6498 EnumDecl *Enum
6499 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6500 T->getDecl()));
6501 if (!Enum)
6502 return QualType();
6503
6504 QualType Result = TL.getType();
6505 if (getDerived().AlwaysRebuild() ||
6506 Enum != T->getDecl()) {
6507 Result = getDerived().RebuildEnumType(Enum);
6508 if (Result.isNull())
6509 return QualType();
6510 }
6511
6512 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
6513 NewTL.setNameLoc(TL.getNameLoc());
6514
6515 return Result;
6516}
6517
6518template<typename Derived>
6519QualType TreeTransform<Derived>::TransformInjectedClassNameType(
6520 TypeLocBuilder &TLB,
6521 InjectedClassNameTypeLoc TL) {
6522 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
6523 TL.getTypePtr()->getDecl());
6524 if (!D) return QualType();
6525
6526 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
6527 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
6528 return T;
6529}
6530
6531template<typename Derived>
6532QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6533 TypeLocBuilder &TLB,
6534 TemplateTypeParmTypeLoc TL) {
6535 return getDerived().TransformTemplateTypeParmType(
6536 TLB, TL,
6537 /*SuppressObjCLifetime=*/false);
6538}
6539
6540template <typename Derived>
6541QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6542 TypeLocBuilder &TLB, TemplateTypeParmTypeLoc TL, bool) {
6543 return TransformTypeSpecType(TLB, TL);
6544}
6545
6546template<typename Derived>
6547QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
6548 TypeLocBuilder &TLB,
6549 SubstTemplateTypeParmTypeLoc TL) {
6550 const SubstTemplateTypeParmType *T = TL.getTypePtr();
6551
6552 Decl *NewReplaced =
6553 getDerived().TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
6554
6555 // Substitute into the replacement type, which itself might involve something
6556 // that needs to be transformed. This only tends to occur with default
6557 // template arguments of template template parameters.
6558 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
6559 QualType Replacement = getDerived().TransformType(T->getReplacementType());
6560 if (Replacement.isNull())
6561 return QualType();
6562
6563 QualType Result = SemaRef.Context.getSubstTemplateTypeParmType(
6564 Replacement, NewReplaced, T->getIndex(), T->getPackIndex());
6565
6566 // Propagate type-source information.
6567 SubstTemplateTypeParmTypeLoc NewTL
6568 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
6569 NewTL.setNameLoc(TL.getNameLoc());
6570 return Result;
6571
6572}
6573
6574template<typename Derived>
6575QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6576 TypeLocBuilder &TLB,
6577 SubstTemplateTypeParmPackTypeLoc TL) {
6578 return getDerived().TransformSubstTemplateTypeParmPackType(
6579 TLB, TL, /*SuppressObjCLifetime=*/false);
6580}
6581
6582template <typename Derived>
6583QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6584 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL, bool) {
6585 return TransformTypeSpecType(TLB, TL);
6586}
6587
6588template<typename Derived>
6589QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6590 TypeLocBuilder &TLB,
6591 TemplateSpecializationTypeLoc TL) {
6592 const TemplateSpecializationType *T = TL.getTypePtr();
6593
6594 // The nested-name-specifier never matters in a TemplateSpecializationType,
6595 // because we can't have a dependent nested-name-specifier anyway.
6596 CXXScopeSpec SS;
6597 TemplateName Template
6598 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
6599 TL.getTemplateNameLoc());
6600 if (Template.isNull())
6601 return QualType();
6602
6603 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
6604}
6605
6606template<typename Derived>
6607QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
6608 AtomicTypeLoc TL) {
6609 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6610 if (ValueType.isNull())
6611 return QualType();
6612
6613 QualType Result = TL.getType();
6614 if (getDerived().AlwaysRebuild() ||
6615 ValueType != TL.getValueLoc().getType()) {
6616 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6617 if (Result.isNull())
6618 return QualType();
6619 }
6620
6621 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6622 NewTL.setKWLoc(TL.getKWLoc());
6623 NewTL.setLParenLoc(TL.getLParenLoc());
6624 NewTL.setRParenLoc(TL.getRParenLoc());
6625
6626 return Result;
6627}
6628
6629template <typename Derived>
6630QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6631 PipeTypeLoc TL) {
6632 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6633 if (ValueType.isNull())
6634 return QualType();
6635
6636 QualType Result = TL.getType();
6637 if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
6638 const PipeType *PT = Result->castAs<PipeType>();
6639 bool isReadPipe = PT->isReadOnly();
6640 Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6641 if (Result.isNull())
6642 return QualType();
6643 }
6644
6645 PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6646 NewTL.setKWLoc(TL.getKWLoc());
6647
6648 return Result;
6649}
6650
6651template <typename Derived>
6652QualType TreeTransform<Derived>::TransformBitIntType(TypeLocBuilder &TLB,
6653 BitIntTypeLoc TL) {
6654 const BitIntType *EIT = TL.getTypePtr();
6655 QualType Result = TL.getType();
6656
6657 if (getDerived().AlwaysRebuild()) {
6658 Result = getDerived().RebuildBitIntType(EIT->isUnsigned(),
6659 EIT->getNumBits(), TL.getNameLoc());
6660 if (Result.isNull())
6661 return QualType();
6662 }
6663
6664 BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6665 NewTL.setNameLoc(TL.getNameLoc());
6666 return Result;
6667}
6668
6669template <typename Derived>
6670QualType TreeTransform<Derived>::TransformDependentBitIntType(
6671 TypeLocBuilder &TLB, DependentBitIntTypeLoc TL) {
6672 const DependentBitIntType *EIT = TL.getTypePtr();
6673
6674 EnterExpressionEvaluationContext Unevaluated(
6675 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6676 ExprResult BitsExpr = getDerived().TransformExpr(EIT->getNumBitsExpr());
6677 BitsExpr = SemaRef.ActOnConstantExpression(BitsExpr);
6678
6679 if (BitsExpr.isInvalid())
6680 return QualType();
6681
6682 QualType Result = TL.getType();
6683
6684 if (getDerived().AlwaysRebuild() || BitsExpr.get() != EIT->getNumBitsExpr()) {
6685 Result = getDerived().RebuildDependentBitIntType(
6686 EIT->isUnsigned(), BitsExpr.get(), TL.getNameLoc());
6687
6688 if (Result.isNull())
6689 return QualType();
6690 }
6691
6692 if (isa<DependentBitIntType>(Result)) {
6693 DependentBitIntTypeLoc NewTL = TLB.push<DependentBitIntTypeLoc>(Result);
6694 NewTL.setNameLoc(TL.getNameLoc());
6695 } else {
6696 BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6697 NewTL.setNameLoc(TL.getNameLoc());
6698 }
6699 return Result;
6700}
6701
6702 /// Simple iterator that traverses the template arguments in a
6703 /// container that provides a \c getArgLoc() member function.
6704 ///
6705 /// This iterator is intended to be used with the iterator form of
6706 /// \c TreeTransform<Derived>::TransformTemplateArguments().
6707 template<typename ArgLocContainer>
6708 class TemplateArgumentLocContainerIterator {
6709 ArgLocContainer *Container;
6710 unsigned Index;
6711
6712 public:
6713 typedef TemplateArgumentLoc value_type;
6714 typedef TemplateArgumentLoc reference;
6715 typedef int difference_type;
6716 typedef std::input_iterator_tag iterator_category;
6717
6718 class pointer {
6719 TemplateArgumentLoc Arg;
6720
6721 public:
6722 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6723
6724 const TemplateArgumentLoc *operator->() const {
6725 return &Arg;
6726 }
6727 };
6728
6729
6730 TemplateArgumentLocContainerIterator() {}
6731
6732 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6733 unsigned Index)
6734 : Container(&Container), Index(Index) { }
6735
6736 TemplateArgumentLocContainerIterator &operator++() {
6737 ++Index;
6738 return *this;
6739 }
6740
6741 TemplateArgumentLocContainerIterator operator++(int) {
6742 TemplateArgumentLocContainerIterator Old(*this);
6743 ++(*this);
6744 return Old;
6745 }
6746
6747 TemplateArgumentLoc operator*() const {
6748 return Container->getArgLoc(Index);
6749 }
6750
6751 pointer operator->() const {
6752 return pointer(Container->getArgLoc(Index));
6753 }
6754
6755 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6756 const TemplateArgumentLocContainerIterator &Y) {
6757 return X.Container == Y.Container && X.Index == Y.Index;
6758 }
6759
6760 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6761 const TemplateArgumentLocContainerIterator &Y) {
6762 return !(X == Y);
6763 }
6764 };
6765
6766template<typename Derived>
6767QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6768 AutoTypeLoc TL) {
6769 const AutoType *T = TL.getTypePtr();
6770 QualType OldDeduced = T->getDeducedType();
6771 QualType NewDeduced;
6772 if (!OldDeduced.isNull()) {
6773 NewDeduced = getDerived().TransformType(OldDeduced);
6774 if (NewDeduced.isNull())
6775 return QualType();
6776 }
6777
6778 ConceptDecl *NewCD = nullptr;
6779 TemplateArgumentListInfo NewTemplateArgs;
6780 NestedNameSpecifierLoc NewNestedNameSpec;
6781 if (T->isConstrained()) {
6782 NewCD = cast_or_null<ConceptDecl>(getDerived().TransformDecl(
6783 TL.getConceptNameLoc(), T->getTypeConstraintConcept()));
6784
6785 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6786 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6787 typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6788 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6789 ArgIterator(TL,
6790 TL.getNumArgs()),
6791 NewTemplateArgs))
6792 return QualType();
6793
6794 if (TL.getNestedNameSpecifierLoc()) {
6795 NewNestedNameSpec
6796 = getDerived().TransformNestedNameSpecifierLoc(
6797 TL.getNestedNameSpecifierLoc());
6798 if (!NewNestedNameSpec)
6799 return QualType();
6800 }
6801 }
6802
6803 QualType Result = TL.getType();
6804 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6805 T->isDependentType() || T->isConstrained()) {
6806 // FIXME: Maybe don't rebuild if all template arguments are the same.
6807 llvm::SmallVector<TemplateArgument, 4> NewArgList;
6808 NewArgList.reserve(NewTemplateArgs.size());
6809 for (const auto &ArgLoc : NewTemplateArgs.arguments())
6810 NewArgList.push_back(ArgLoc.getArgument());
6811 Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6812 NewArgList);
6813 if (Result.isNull())
6814 return QualType();
6815 }
6816
6817 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6818 NewTL.setNameLoc(TL.getNameLoc());
6819 NewTL.setNestedNameSpecifierLoc(NewNestedNameSpec);
6820 NewTL.setTemplateKWLoc(TL.getTemplateKWLoc());
6821 NewTL.setConceptNameLoc(TL.getConceptNameLoc());
6822 NewTL.setFoundDecl(TL.getFoundDecl());
6823 NewTL.setLAngleLoc(TL.getLAngleLoc());
6824 NewTL.setRAngleLoc(TL.getRAngleLoc());
6825 NewTL.setRParenLoc(TL.getRParenLoc());
6826 for (unsigned I = 0; I < NewTL.getNumArgs(); ++I)
6827 NewTL.setArgLocInfo(I, NewTemplateArgs.arguments()[I].getLocInfo());
6828
6829 return Result;
6830}
6831
6832template <typename Derived>
6833QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6834 TypeLocBuilder &TLB,
6835 TemplateSpecializationTypeLoc TL,
6836 TemplateName Template) {
6837 TemplateArgumentListInfo NewTemplateArgs;
6838 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6839 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6840 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6841 ArgIterator;
6842 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6843 ArgIterator(TL, TL.getNumArgs()),
6844 NewTemplateArgs))
6845 return QualType();
6846
6847 // FIXME: maybe don't rebuild if all the template arguments are the same.
6848
6849 QualType Result =
6850 getDerived().RebuildTemplateSpecializationType(Template,
6851 TL.getTemplateNameLoc(),
6852 NewTemplateArgs);
6853
6854 if (!Result.isNull()) {
6855 // Specializations of template template parameters are represented as
6856 // TemplateSpecializationTypes, and substitution of type alias templates
6857 // within a dependent context can transform them into
6858 // DependentTemplateSpecializationTypes.
6859 if (isa<DependentTemplateSpecializationType>(Result)) {
6860 DependentTemplateSpecializationTypeLoc NewTL
6861 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6862 NewTL.setElaboratedKeywordLoc(SourceLocation());
6863 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6864 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6865 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6866 NewTL.setLAngleLoc(TL.getLAngleLoc());
6867 NewTL.setRAngleLoc(TL.getRAngleLoc());
6868 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6869 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6870 return Result;
6871 }
6872
6873 TemplateSpecializationTypeLoc NewTL
6874 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6875 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6876 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6877 NewTL.setLAngleLoc(TL.getLAngleLoc());
6878 NewTL.setRAngleLoc(TL.getRAngleLoc());
6879 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6880 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6881 }
6882
6883 return Result;
6884}
6885
6886template <typename Derived>
6887QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6888 TypeLocBuilder &TLB,
6889 DependentTemplateSpecializationTypeLoc TL,
6890 TemplateName Template,
6891 CXXScopeSpec &SS) {
6892 TemplateArgumentListInfo NewTemplateArgs;
6893 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6894 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6895 typedef TemplateArgumentLocContainerIterator<
6896 DependentTemplateSpecializationTypeLoc> ArgIterator;
6897 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6898 ArgIterator(TL, TL.getNumArgs()),
6899 NewTemplateArgs))
6900 return QualType();
6901
6902 // FIXME: maybe don't rebuild if all the template arguments are the same.
6903
6904 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6905 QualType Result = getSema().Context.getDependentTemplateSpecializationType(
6906 TL.getTypePtr()->getKeyword(), DTN->getQualifier(),
6907 DTN->getIdentifier(), NewTemplateArgs.arguments());
6908
6909 DependentTemplateSpecializationTypeLoc NewTL
6910 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6911 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6912 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6913 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6914 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6915 NewTL.setLAngleLoc(TL.getLAngleLoc());
6916 NewTL.setRAngleLoc(TL.getRAngleLoc());
6917 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6918 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6919 return Result;
6920 }
6921
6922 QualType Result
6923 = getDerived().RebuildTemplateSpecializationType(Template,
6924 TL.getTemplateNameLoc(),
6925 NewTemplateArgs);
6926
6927 if (!Result.isNull()) {
6928 /// FIXME: Wrap this in an elaborated-type-specifier?
6929 TemplateSpecializationTypeLoc NewTL
6930 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6931 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6932 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6933 NewTL.setLAngleLoc(TL.getLAngleLoc());
6934 NewTL.setRAngleLoc(TL.getRAngleLoc());
6935 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6936 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6937 }
6938
6939 return Result;
6940}
6941
6942template<typename Derived>
6943QualType
6944TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6945 ElaboratedTypeLoc TL) {
6946 const ElaboratedType *T = TL.getTypePtr();
6947
6948 NestedNameSpecifierLoc QualifierLoc;
6949 // NOTE: the qualifier in an ElaboratedType is optional.
6950 if (TL.getQualifierLoc()) {
6951 QualifierLoc
6952 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6953 if (!QualifierLoc)
6954 return QualType();
6955 }
6956
6957 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6958 if (NamedT.isNull())
6959 return QualType();
6960
6961 // C++0x [dcl.type.elab]p2:
6962 // If the identifier resolves to a typedef-name or the simple-template-id
6963 // resolves to an alias template specialization, the
6964 // elaborated-type-specifier is ill-formed.
6965 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6966 if (const TemplateSpecializationType *TST =
6967 NamedT->getAs<TemplateSpecializationType>()) {
6968 TemplateName Template = TST->getTemplateName();
6969 if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6970 Template.getAsTemplateDecl())) {
6971 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6972 diag::err_tag_reference_non_tag)
6973 << TAT << Sema::NTK_TypeAliasTemplate
6974 << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6975 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6976 }
6977 }
6978 }
6979
6980 QualType Result = TL.getType();
6981 if (getDerived().AlwaysRebuild() ||
6982 QualifierLoc != TL.getQualifierLoc() ||
6983 NamedT != T->getNamedType()) {
6984 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6985 T->getKeyword(),
6986 QualifierLoc, NamedT);
6987 if (Result.isNull())
6988 return QualType();
6989 }
6990
6991 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6992 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6993 NewTL.setQualifierLoc(QualifierLoc);
6994 return Result;
6995}
6996
6997template<typename Derived>
6998QualType TreeTransform<Derived>::TransformAttributedType(
6999 TypeLocBuilder &TLB,
7000 AttributedTypeLoc TL) {
7001 const AttributedType *oldType = TL.getTypePtr();
7002 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
7003 if (modifiedType.isNull())
7004 return QualType();
7005
7006 // oldAttr can be null if we started with a QualType rather than a TypeLoc.
7007 const Attr *oldAttr = TL.getAttr();
7008 const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
7009 if (oldAttr && !newAttr)
7010 return QualType();
7011
7012 QualType result = TL.getType();
7013
7014 // FIXME: dependent operand expressions?
7015 if (getDerived().AlwaysRebuild() ||
7016 modifiedType != oldType->getModifiedType()) {
7017 // TODO: this is really lame; we should really be rebuilding the
7018 // equivalent type from first principles.
7019 QualType equivalentType
7020 = getDerived().TransformType(oldType->getEquivalentType());
7021 if (equivalentType.isNull())
7022 return QualType();
7023
7024 // Check whether we can add nullability; it is only represented as
7025 // type sugar, and therefore cannot be diagnosed in any other way.
7026 if (auto nullability = oldType->getImmediateNullability()) {
7027 if (!modifiedType->canHaveNullability()) {
7028 SemaRef.Diag((TL.getAttr() ? TL.getAttr()->getLocation()
7029 : TL.getModifiedLoc().getBeginLoc()),
7030 diag::err_nullability_nonpointer)
7031 << DiagNullabilityKind(*nullability, false) << modifiedType;
7032 return QualType();
7033 }
7034 }
7035
7036 result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
7037 modifiedType,
7038 equivalentType);
7039 }
7040
7041 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
7042 newTL.setAttr(newAttr);
7043 return result;
7044}
7045
7046template <typename Derived>
7047QualType TreeTransform<Derived>::TransformBTFTagAttributedType(
7048 TypeLocBuilder &TLB, BTFTagAttributedTypeLoc TL) {
7049 // The BTFTagAttributedType is available for C only.
7050 llvm_unreachable("Unexpected TreeTransform for BTFTagAttributedType")::llvm::llvm_unreachable_internal("Unexpected TreeTransform for BTFTagAttributedType"
, "clang/lib/Sema/TreeTransform.h", 7050)
;
7051}
7052
7053template<typename Derived>
7054QualType
7055TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
7056 ParenTypeLoc TL) {
7057 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7058 if (Inner.isNull())
7059 return QualType();
7060
7061 QualType Result = TL.getType();
7062 if (getDerived().AlwaysRebuild() ||
7063 Inner != TL.getInnerLoc().getType()) {
7064 Result = getDerived().RebuildParenType(Inner);
7065 if (Result.isNull())
7066 return QualType();
7067 }
7068
7069 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
7070 NewTL.setLParenLoc(TL.getLParenLoc());
7071 NewTL.setRParenLoc(TL.getRParenLoc());
7072 return Result;
7073}
7074
7075template <typename Derived>
7076QualType
7077TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
7078 MacroQualifiedTypeLoc TL) {
7079 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7080 if (Inner.isNull())
7081 return QualType();
7082
7083 QualType Result = TL.getType();
7084 if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
7085 Result =
7086 getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
7087 if (Result.isNull())
7088 return QualType();
7089 }
7090
7091 MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
7092 NewTL.setExpansionLoc(TL.getExpansionLoc());
7093 return Result;
7094}
7095
7096template<typename Derived>
7097QualType TreeTransform<Derived>::TransformDependentNameType(
7098 TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
7099 return TransformDependentNameType(TLB, TL, false);
7100}
7101
7102template<typename Derived>
7103QualType TreeTransform<Derived>::TransformDependentNameType(
7104 TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
7105 const DependentNameType *T = TL.getTypePtr();
7106
7107 NestedNameSpecifierLoc QualifierLoc
7108 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7109 if (!QualifierLoc)
7110 return QualType();
7111
7112 QualType Result
7113 = getDerived().RebuildDependentNameType(T->getKeyword(),
7114 TL.getElaboratedKeywordLoc(),
7115 QualifierLoc,
7116 T->getIdentifier(),
7117 TL.getNameLoc(),
7118 DeducedTSTContext);
7119 if (Result.isNull())
7120 return QualType();
7121
7122 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
7123 QualType NamedT = ElabT->getNamedType();
7124 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
7125
7126 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7127 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7128 NewTL.setQualifierLoc(QualifierLoc);
7129 } else {
7130 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
7131 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7132 NewTL.setQualifierLoc(QualifierLoc);
7133 NewTL.setNameLoc(TL.getNameLoc());
7134 }
7135 return Result;
7136}
7137
7138template<typename Derived>
7139QualType TreeTransform<Derived>::
7140 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7141 DependentTemplateSpecializationTypeLoc TL) {
7142 NestedNameSpecifierLoc QualifierLoc;
7143 if (TL.getQualifierLoc()) {
7144 QualifierLoc
7145 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7146 if (!QualifierLoc)
7147 return QualType();
7148 }
7149
7150 return getDerived()
7151 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
7152}
7153
7154template<typename Derived>
7155QualType TreeTransform<Derived>::
7156TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7157 DependentTemplateSpecializationTypeLoc TL,
7158 NestedNameSpecifierLoc QualifierLoc) {
7159 const DependentTemplateSpecializationType *T = TL.getTypePtr();
7160
7161 TemplateArgumentListInfo NewTemplateArgs;
7162 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
7163 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
7164
7165 typedef TemplateArgumentLocContainerIterator<
7166 DependentTemplateSpecializationTypeLoc> ArgIterator;
7167 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
7168 ArgIterator(TL, TL.getNumArgs()),
7169 NewTemplateArgs))
7170 return QualType();
7171
7172 QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
7173 T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
7174 T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
7175 /*AllowInjectedClassName*/ false);
7176 if (Result.isNull())
7177 return QualType();
7178
7179 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
7180 QualType NamedT = ElabT->getNamedType();
7181
7182 // Copy information relevant to the template specialization.
7183 TemplateSpecializationTypeLoc NamedTL
7184 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
7185 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7186 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7187 NamedTL.setLAngleLoc(TL.getLAngleLoc());
7188 NamedTL.setRAngleLoc(TL.getRAngleLoc());
7189 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7190 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7191
7192 // Copy information relevant to the elaborated type.
7193 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7194 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7195 NewTL.setQualifierLoc(QualifierLoc);
7196 } else if (isa<DependentTemplateSpecializationType>(Result)) {
7197 DependentTemplateSpecializationTypeLoc SpecTL
7198 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
7199 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7200 SpecTL.setQualifierLoc(QualifierLoc);
7201 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7202 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7203 SpecTL.setLAngleLoc(TL.getLAngleLoc());
7204 SpecTL.setRAngleLoc(TL.getRAngleLoc());
7205 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7206 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7207 } else {
7208 TemplateSpecializationTypeLoc SpecTL
7209 = TLB.push<TemplateSpecializationTypeLoc>(Result);
7210 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7211 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7212 SpecTL.setLAngleLoc(TL.getLAngleLoc());
7213 SpecTL.setRAngleLoc(TL.getRAngleLoc());
7214 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7215 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7216 }
7217 return Result;
7218}
7219
7220template<typename Derived>
7221QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
7222 PackExpansionTypeLoc TL) {
7223 QualType Pattern
7224 = getDerived().TransformType(TLB, TL.getPatternLoc());
7225 if (Pattern.isNull())
7226 return QualType();
7227
7228 QualType Result = TL.getType();
7229 if (getDerived().AlwaysRebuild() ||
7230 Pattern != TL.getPatternLoc().getType()) {
7231 Result = getDerived().RebuildPackExpansionType(Pattern,
7232 TL.getPatternLoc().getSourceRange(),
7233 TL.getEllipsisLoc(),
7234 TL.getTypePtr()->getNumExpansions());
7235 if (Result.isNull())
7236 return QualType();
7237 }
7238
7239 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
7240 NewT.setEllipsisLoc(TL.getEllipsisLoc());
7241 return Result;
7242}
7243
7244template<typename Derived>
7245QualType
7246TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
7247 ObjCInterfaceTypeLoc TL) {
7248 // ObjCInterfaceType is never dependent.
7249 TLB.pushFullCopy(TL);
7250 return TL.getType();
7251}
7252
7253template<typename Derived>
7254QualType
7255TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
7256 ObjCTypeParamTypeLoc TL) {
7257 const ObjCTypeParamType *T = TL.getTypePtr();
7258 ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
7259 getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
7260 if (!OTP)
7261 return QualType();
7262
7263 QualType Result = TL.getType();
7264 if (getDerived().AlwaysRebuild() ||
7265 OTP != T->getDecl()) {
7266 Result = getDerived().RebuildObjCTypeParamType(
7267 OTP, TL.getProtocolLAngleLoc(),
7268 llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7269 TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7270 if (Result.isNull())
7271 return QualType();
7272 }
7273
7274 ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
7275 if (TL.getNumProtocols()) {
7276 NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7277 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7278 NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
7279 NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7280 }
7281 return Result;
7282}
7283
7284template<typename Derived>
7285QualType
7286TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
7287 ObjCObjectTypeLoc TL) {
7288 // Transform base type.
7289 QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
7290 if (BaseType.isNull())
7291 return QualType();
7292
7293 bool AnyChanged = BaseType != TL.getBaseLoc().getType();
7294
7295 // Transform type arguments.
7296 SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
7297 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
7298 TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
7299 TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
7300 QualType TypeArg = TypeArgInfo->getType();
7301 if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
7302 AnyChanged = true;
7303
7304 // We have a pack expansion. Instantiate it.
7305 const auto *PackExpansion = PackExpansionLoc.getType()
7306 ->castAs<PackExpansionType>();
7307 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7308 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
7309 Unexpanded);
7310 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 7310, __extension__ __PRETTY_FUNCTION__
))
;
7311
7312 // Determine whether the set of unexpanded parameter packs can
7313 // and should be expanded.
7314 TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
7315 bool Expand = false;
7316 bool RetainExpansion = false;
7317 std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
7318 if (getDerived().TryExpandParameterPacks(
7319 PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
7320 Unexpanded, Expand, RetainExpansion, NumExpansions))
7321 return QualType();
7322
7323 if (!Expand) {
7324 // We can't expand this pack expansion into separate arguments yet;
7325 // just substitute into the pattern and create a new pack expansion
7326 // type.
7327 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7328
7329 TypeLocBuilder TypeArgBuilder;
7330 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7331 QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
7332 PatternLoc);
7333 if (NewPatternType.isNull())
7334 return QualType();
7335
7336 QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
7337 NewPatternType, NumExpansions);
7338 auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
7339 NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
7340 NewTypeArgInfos.push_back(
7341 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
7342 continue;
7343 }
7344
7345 // Substitute into the pack expansion pattern for each slice of the
7346 // pack.
7347 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
7348 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
7349
7350 TypeLocBuilder TypeArgBuilder;
7351 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7352
7353 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
7354 PatternLoc);
7355 if (NewTypeArg.isNull())
7356 return QualType();
7357
7358 NewTypeArgInfos.push_back(
7359 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7360 }
7361
7362 continue;
7363 }
7364
7365 TypeLocBuilder TypeArgBuilder;
7366 TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
7367 QualType NewTypeArg =
7368 getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
7369 if (NewTypeArg.isNull())
7370 return QualType();
7371
7372 // If nothing changed, just keep the old TypeSourceInfo.
7373 if (NewTypeArg == TypeArg) {
7374 NewTypeArgInfos.push_back(TypeArgInfo);
7375 continue;
7376 }
7377
7378 NewTypeArgInfos.push_back(
7379 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7380 AnyChanged = true;
7381 }
7382
7383 QualType Result = TL.getType();
7384 if (getDerived().AlwaysRebuild() || AnyChanged) {
7385 // Rebuild the type.
7386 Result = getDerived().RebuildObjCObjectType(
7387 BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
7388 TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
7389 llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7390 TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7391
7392 if (Result.isNull())
7393 return QualType();
7394 }
7395
7396 ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
7397 NewT.setHasBaseTypeAsWritten(true);
7398 NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
7399 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
7400 NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
7401 NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
7402 NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7403 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7404 NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
7405 NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7406 return Result;
7407}
7408
7409template<typename Derived>
7410QualType
7411TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
7412 ObjCObjectPointerTypeLoc TL) {
7413 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
7414 if (PointeeType.isNull())
7415 return QualType();
7416
7417 QualType Result = TL.getType();
7418 if (getDerived().AlwaysRebuild() ||
7419 PointeeType != TL.getPointeeLoc().getType()) {
7420 Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
7421 TL.getStarLoc());
7422 if (Result.isNull())
7423 return QualType();
7424 }
7425
7426 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
7427 NewT.setStarLoc(TL.getStarLoc());
7428 return Result;
7429}
7430
7431//===----------------------------------------------------------------------===//
7432// Statement transformation
7433//===----------------------------------------------------------------------===//
7434template<typename Derived>
7435StmtResult
7436TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
7437 return S;
7438}
7439
7440template<typename Derived>
7441StmtResult
7442TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
7443 return getDerived().TransformCompoundStmt(S, false);
7444}
7445
7446template<typename Derived>
7447StmtResult
7448TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
7449 bool IsStmtExpr) {
7450 Sema::CompoundScopeRAII CompoundScope(getSema());
7451
7452 const Stmt *ExprResult = S->getStmtExprResult();
7453 bool SubStmtInvalid = false;
7454 bool SubStmtChanged = false;
7455 SmallVector<Stmt*, 8> Statements;
7456 for (auto *B : S->body()) {
7457 StmtResult Result = getDerived().TransformStmt(
7458 B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
7459
7460 if (Result.isInvalid()) {
7461 // Immediately fail if this was a DeclStmt, since it's very
7462 // likely that this will cause problems for future statements.
7463 if (isa<DeclStmt>(B))
7464 return StmtError();
7465
7466 // Otherwise, just keep processing substatements and fail later.
7467 SubStmtInvalid = true;
7468 continue;
7469 }
7470
7471 SubStmtChanged = SubStmtChanged || Result.get() != B;
7472 Statements.push_back(Result.getAs<Stmt>());
7473 }
7474
7475 if (SubStmtInvalid)
7476 return StmtError();
7477
7478 if (!getDerived().AlwaysRebuild() &&
7479 !SubStmtChanged)
7480 return S;
7481
7482 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
7483 Statements,
7484 S->getRBracLoc(),
7485 IsStmtExpr);
7486}
7487
7488template<typename Derived>
7489StmtResult
7490TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
7491 ExprResult LHS, RHS;
7492 {
7493 EnterExpressionEvaluationContext Unevaluated(
7494 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7495
7496 // Transform the left-hand case value.
7497 LHS = getDerived().TransformExpr(S->getLHS());
7498 LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
7499 if (LHS.isInvalid())
7500 return StmtError();
7501
7502 // Transform the right-hand case value (for the GNU case-range extension).
7503 RHS = getDerived().TransformExpr(S->getRHS());
7504 RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
7505 if (RHS.isInvalid())
7506 return StmtError();
7507 }
7508
7509 // Build the case statement.
7510 // Case statements are always rebuilt so that they will attached to their
7511 // transformed switch statement.
7512 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
7513 LHS.get(),
7514 S->getEllipsisLoc(),
7515 RHS.get(),
7516 S->getColonLoc());
7517 if (Case.isInvalid())
7518 return StmtError();
7519
7520 // Transform the statement following the case
7521 StmtResult SubStmt =
7522 getDerived().TransformStmt(S->getSubStmt());
7523 if (SubStmt.isInvalid())
7524 return StmtError();
7525
7526 // Attach the body to the case statement
7527 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
7528}
7529
7530template <typename Derived>
7531StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
7532 // Transform the statement following the default case
7533 StmtResult SubStmt =
7534 getDerived().TransformStmt(S->getSubStmt());
7535 if (SubStmt.isInvalid())
7536 return StmtError();
7537
7538 // Default statements are always rebuilt
7539 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
7540 SubStmt.get());
7541}
7542
7543template<typename Derived>
7544StmtResult
7545TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
7546 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7547 if (SubStmt.isInvalid())
7548 return StmtError();
7549
7550 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
7551 S->getDecl());
7552 if (!LD)
7553 return StmtError();
7554
7555 // If we're transforming "in-place" (we're not creating new local
7556 // declarations), assume we're replacing the old label statement
7557 // and clear out the reference to it.
7558 if (LD == S->getDecl())
7559 S->getDecl()->setStmt(nullptr);
7560
7561 // FIXME: Pass the real colon location in.
7562 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
7563 cast<LabelDecl>(LD), SourceLocation(),
7564 SubStmt.get());
7565}
7566
7567template <typename Derived>
7568const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
7569 if (!R)
7570 return R;
7571
7572 switch (R->getKind()) {
7573// Transform attributes by calling TransformXXXAttr.
7574#define ATTR(X) \
7575 case attr::X: \
7576 return getDerived().Transform##X##Attr(cast<X##Attr>(R));
7577#include "clang/Basic/AttrList.inc"
7578 }
7579 return R;
7580}
7581
7582template <typename Derived>
7583const Attr *TreeTransform<Derived>::TransformStmtAttr(const Stmt *OrigS,
7584 const Stmt *InstS,
7585 const Attr *R) {
7586 if (!R)
7587 return R;
7588
7589 switch (R->getKind()) {
7590// Transform attributes by calling TransformStmtXXXAttr.
7591#define ATTR(X) \
7592 case attr::X: \
7593 return getDerived().TransformStmt##X##Attr(OrigS, InstS, cast<X##Attr>(R));
7594#include "clang/Basic/AttrList.inc"
7595 }
7596 return TransformAttr(R);
7597}
7598
7599template <typename Derived>
7600StmtResult
7601TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
7602 StmtDiscardKind SDK) {
7603 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7604 if (SubStmt.isInvalid())
7605 return StmtError();
7606
7607 bool AttrsChanged = false;
7608 SmallVector<const Attr *, 1> Attrs;
7609
7610 // Visit attributes and keep track if any are transformed.
7611 for (const auto *I : S->getAttrs()) {
7612 const Attr *R =
7613 getDerived().TransformStmtAttr(S->getSubStmt(), SubStmt.get(), I);
7614 AttrsChanged |= (I != R);
7615 if (R)
7616 Attrs.push_back(R);
7617 }
7618
7619 if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
7620 return S;
7621
7622 // If transforming the attributes failed for all of the attributes in the
7623 // statement, don't make an AttributedStmt without attributes.
7624 if (Attrs.empty())
7625 return SubStmt;
7626
7627 return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
7628 SubStmt.get());
7629}
7630
7631template<typename Derived>
7632StmtResult
7633TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
7634 // Transform the initialization statement
7635 StmtResult Init = getDerived().TransformStmt(S->getInit());
7636 if (Init.isInvalid())
7637 return StmtError();
7638
7639 Sema::ConditionResult Cond;
7640 if (!S->isConsteval()) {
7641 // Transform the condition
7642 Cond = getDerived().TransformCondition(
7643 S->getIfLoc(), S->getConditionVariable(), S->getCond(),
7644 S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
7645 : Sema::ConditionKind::Boolean);
7646 if (Cond.isInvalid())
7647 return StmtError();
7648 }
7649
7650 // If this is a constexpr if, determine which arm we should instantiate.
7651 std::optional<bool> ConstexprConditionValue;
7652 if (S->isConstexpr())
7653 ConstexprConditionValue = Cond.getKnownValue();
7654
7655 // Transform the "then" branch.
7656 StmtResult Then;
7657 if (!ConstexprConditionValue || *ConstexprConditionValue) {
7658 Then = getDerived().TransformStmt(S->getThen());
7659 if (Then.isInvalid())
7660 return StmtError();
7661 } else {
7662 Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
7663 }
7664
7665 // Transform the "else" branch.
7666 StmtResult Else;
7667 if (!ConstexprConditionValue || !*ConstexprConditionValue) {
7668 Else = getDerived().TransformStmt(S->getElse());
7669 if (Else.isInvalid())
7670 return StmtError();
7671 }
7672
7673 if (!getDerived().AlwaysRebuild() &&
7674 Init.get() == S->getInit() &&
7675 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7676 Then.get() == S->getThen() &&
7677 Else.get() == S->getElse())
7678 return S;
7679
7680 return getDerived().RebuildIfStmt(
7681 S->getIfLoc(), S->getStatementKind(), S->getLParenLoc(), Cond,
7682 S->getRParenLoc(), Init.get(), Then.get(), S->getElseLoc(), Else.get());
7683}
7684
7685template<typename Derived>
7686StmtResult
7687TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
7688 // Transform the initialization statement
7689 StmtResult Init = getDerived().TransformStmt(S->getInit());
7690 if (Init.isInvalid())
7691 return StmtError();
7692
7693 // Transform the condition.
7694 Sema::ConditionResult Cond = getDerived().TransformCondition(
7695 S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7696 Sema::ConditionKind::Switch);
7697 if (Cond.isInvalid())
7698 return StmtError();
7699
7700 // Rebuild the switch statement.
7701 StmtResult Switch =
7702 getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), S->getLParenLoc(),
7703 Init.get(), Cond, S->getRParenLoc());
7704 if (Switch.isInvalid())
7705 return StmtError();
7706
7707 // Transform the body of the switch statement.
7708 StmtResult Body = getDerived().TransformStmt(S->getBody());
7709 if (Body.isInvalid())
7710 return StmtError();
7711
7712 // Complete the switch statement.
7713 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7714 Body.get());
7715}
7716
7717template<typename Derived>
7718StmtResult
7719TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7720 // Transform the condition
7721 Sema::ConditionResult Cond = getDerived().TransformCondition(
7722 S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7723 Sema::ConditionKind::Boolean);
7724 if (Cond.isInvalid())
7725 return StmtError();
7726
7727 // Transform the body
7728 StmtResult Body = getDerived().TransformStmt(S->getBody());
7729 if (Body.isInvalid())
7730 return StmtError();
7731
7732 if (!getDerived().AlwaysRebuild() &&
7733 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7734 Body.get() == S->getBody())
7735 return Owned(S);
7736
7737 return getDerived().RebuildWhileStmt(S->getWhileLoc(), S->getLParenLoc(),
7738 Cond, S->getRParenLoc(), Body.get());
7739}
7740
7741template<typename Derived>
7742StmtResult
7743TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7744 // Transform the body
7745 StmtResult Body = getDerived().TransformStmt(S->getBody());
7746 if (Body.isInvalid())
7747 return StmtError();
7748
7749 // Transform the condition
7750 ExprResult Cond = getDerived().TransformExpr(S->getCond());
7751 if (Cond.isInvalid())
7752 return StmtError();
7753
7754 if (!getDerived().AlwaysRebuild() &&
7755 Cond.get() == S->getCond() &&
7756 Body.get() == S->getBody())
7757 return S;
7758
7759 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7760 /*FIXME:*/S->getWhileLoc(), Cond.get(),
7761 S->getRParenLoc());
7762}
7763
7764template<typename Derived>
7765StmtResult
7766TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7767 if (getSema().getLangOpts().OpenMP)
7768 getSema().startOpenMPLoop();
7769
7770 // Transform the initialization statement
7771 StmtResult Init = getDerived().TransformStmt(S->getInit());
7772 if (Init.isInvalid())
7773 return StmtError();
7774
7775 // In OpenMP loop region loop control variable must be captured and be
7776 // private. Perform analysis of first part (if any).
7777 if (getSema().getLangOpts().OpenMP && Init.isUsable())
7778 getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7779
7780 // Transform the condition
7781 Sema::ConditionResult Cond = getDerived().TransformCondition(
7782 S->getForLoc(), S->getConditionVariable(), S->getCond(),
7783 Sema::ConditionKind::Boolean);
7784 if (Cond.isInvalid())
7785 return StmtError();
7786
7787 // Transform the increment
7788 ExprResult Inc = getDerived().TransformExpr(S->getInc());
7789 if (Inc.isInvalid())
7790 return StmtError();
7791
7792 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7793 if (S->getInc() && !FullInc.get())
7794 return StmtError();
7795
7796 // Transform the body
7797 StmtResult Body = getDerived().TransformStmt(S->getBody());
7798 if (Body.isInvalid())
7799 return StmtError();
7800
7801 if (!getDerived().AlwaysRebuild() &&
7802 Init.get() == S->getInit() &&
7803 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7804 Inc.get() == S->getInc() &&
7805 Body.get() == S->getBody())
7806 return S;
7807
7808 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7809 Init.get(), Cond, FullInc,
7810 S->getRParenLoc(), Body.get());
7811}
7812
7813template<typename Derived>
7814StmtResult
7815TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7816 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7817 S->getLabel());
7818 if (!LD)
7819 return StmtError();
7820
7821 // Goto statements must always be rebuilt, to resolve the label.
7822 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7823 cast<LabelDecl>(LD));
7824}
7825
7826template<typename Derived>
7827StmtResult
7828TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7829 ExprResult Target = getDerived().TransformExpr(S->getTarget());
7830 if (Target.isInvalid())
7831 return StmtError();
7832 Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7833
7834 if (!getDerived().AlwaysRebuild() &&
7835 Target.get() == S->getTarget())
7836 return S;
7837
7838 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7839 Target.get());
7840}
7841
7842template<typename Derived>
7843StmtResult
7844TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7845 return S;
7846}
7847
7848template<typename Derived>
7849StmtResult
7850TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7851 return S;
7852}
7853
7854template<typename Derived>
7855StmtResult
7856TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7857 ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7858 /*NotCopyInit*/false);
7859 if (Result.isInvalid())
7860 return StmtError();
7861
7862 // FIXME: We always rebuild the return statement because there is no way
7863 // to tell whether the return type of the function has changed.
7864 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7865}
7866
7867template<typename Derived>
7868StmtResult
7869TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7870 bool DeclChanged = false;
7871 SmallVector<Decl *, 4> Decls;
7872 for (auto *D : S->decls()) {
7873 Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7874 if (!Transformed)
7875 return StmtError();
7876
7877 if (Transformed != D)
7878 DeclChanged = true;
7879
7880 Decls.push_back(Transformed);
7881 }
7882
7883 if (!getDerived().AlwaysRebuild() && !DeclChanged)
7884 return S;
7885
7886 return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7887}
7888
7889template<typename Derived>
7890StmtResult
7891TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7892
7893 SmallVector<Expr*, 8> Constraints;
7894 SmallVector<Expr*, 8> Exprs;
7895 SmallVector<IdentifierInfo *, 4> Names;
7896
7897 ExprResult AsmString;
7898 SmallVector<Expr*, 8> Clobbers;
7899
7900 bool ExprsChanged = false;
7901
7902 // Go through the outputs.
7903 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7904 Names.push_back(S->getOutputIdentifier(I));
7905
7906 // No need to transform the constraint literal.
7907 Constraints.push_back(S->getOutputConstraintLiteral(I));
7908
7909 // Transform the output expr.
7910 Expr *OutputExpr = S->getOutputExpr(I);
7911 ExprResult Result = getDerived().TransformExpr(OutputExpr);
7912 if (Result.isInvalid())
7913 return StmtError();
7914
7915 ExprsChanged |= Result.get() != OutputExpr;
7916
7917 Exprs.push_back(Result.get());
7918 }
7919
7920 // Go through the inputs.
7921 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7922 Names.push_back(S->getInputIdentifier(I));
7923
7924 // No need to transform the constraint literal.
7925 Constraints.push_back(S->getInputConstraintLiteral(I));
7926
7927 // Transform the input expr.
7928 Expr *InputExpr = S->getInputExpr(I);
7929 ExprResult Result = getDerived().TransformExpr(InputExpr);
7930 if (Result.isInvalid())
7931 return StmtError();
7932
7933 ExprsChanged |= Result.get() != InputExpr;
7934
7935 Exprs.push_back(Result.get());
7936 }
7937
7938 // Go through the Labels.
7939 for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7940 Names.push_back(S->getLabelIdentifier(I));
7941
7942 ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7943 if (Result.isInvalid())
7944 return StmtError();
7945 ExprsChanged |= Result.get() != S->getLabelExpr(I);
7946 Exprs.push_back(Result.get());
7947 }
7948 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7949 return S;
7950
7951 // Go through the clobbers.
7952 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7953 Clobbers.push_back(S->getClobberStringLiteral(I));
7954
7955 // No need to transform the asm string literal.
7956 AsmString = S->getAsmString();
7957 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7958 S->isVolatile(), S->getNumOutputs(),
7959 S->getNumInputs(), Names.data(),
7960 Constraints, Exprs, AsmString.get(),
7961 Clobbers, S->getNumLabels(),
7962 S->getRParenLoc());
7963}
7964
7965template<typename Derived>
7966StmtResult
7967TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7968 ArrayRef<Token> AsmToks = llvm::ArrayRef(S->getAsmToks(), S->getNumAsmToks());
7969
7970 bool HadError = false, HadChange = false;
7971
7972 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7973 SmallVector<Expr*, 8> TransformedExprs;
7974 TransformedExprs.reserve(SrcExprs.size());
7975 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7976 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7977 if (!Result.isUsable()) {
7978 HadError = true;
7979 } else {
7980 HadChange |= (Result.get() != SrcExprs[i]);
7981 TransformedExprs.push_back(Result.get());
7982 }
7983 }
7984
7985 if (HadError) return StmtError();
7986 if (!HadChange && !getDerived().AlwaysRebuild())
7987 return Owned(S);
7988
7989 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7990 AsmToks, S->getAsmString(),
7991 S->getNumOutputs(), S->getNumInputs(),
7992 S->getAllConstraints(), S->getClobbers(),
7993 TransformedExprs, S->getEndLoc());
7994}
7995
7996// C++ Coroutines
7997template<typename Derived>
7998StmtResult
7999TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
8000 auto *ScopeInfo = SemaRef.getCurFunction();
8001 auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
8002 assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
8003 ScopeInfo->NeedsCoroutineSuspends &&(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
8004 ScopeInfo->CoroutineSuspends.first == nullptr &&(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
8005 ScopeInfo->CoroutineSuspends.second == nullptr &&(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
8006 "expected clean scope info")(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
;
8007
8008 // Set that we have (possibly-invalid) suspend points before we do anything
8009 // that may fail.
8010 ScopeInfo->setNeedsCoroutineSuspends(false);
8011
8012 // We re-build the coroutine promise object (and the coroutine parameters its
8013 // type and constructor depend on) based on the types used in our current
8014 // function. We must do so, and set it on the current FunctionScopeInfo,
8015 // before attempting to transform the other parts of the coroutine body
8016 // statement, such as the implicit suspend statements (because those
8017 // statements reference the FunctionScopeInfo::CoroutinePromise).
8018 if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
8019 return StmtError();
8020 auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
8021 if (!Promise)
8022 return StmtError();
8023 getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
8024 ScopeInfo->CoroutinePromise = Promise;
8025
8026 // Transform the implicit coroutine statements constructed using dependent
8027 // types during the previous parse: initial and final suspensions, the return
8028 // object, and others. We also transform the coroutine function's body.
8029 StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
8030 if (InitSuspend.isInvalid())
8031 return StmtError();
8032 StmtResult FinalSuspend =
8033 getDerived().TransformStmt(S->getFinalSuspendStmt());
8034 if (FinalSuspend.isInvalid() ||
8035 !SemaRef.checkFinalSuspendNoThrow(FinalSuspend.get()))
8036 return StmtError();
8037 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
8038 assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()))(static_cast <bool> (isa<Expr>(InitSuspend.get())
&& isa<Expr>(FinalSuspend.get())) ? void (0) :
__assert_fail ("isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get())"
, "clang/lib/Sema/TreeTransform.h", 8038, __extension__ __PRETTY_FUNCTION__
))
;
8039
8040 StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
8041 if (BodyRes.isInvalid())
8042 return StmtError();
8043
8044 CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
8045 if (Builder.isInvalid())
8046 return StmtError();
8047
8048 Expr *ReturnObject = S->getReturnValueInit();
8049 assert(ReturnObject && "the return object is expected to be valid")(static_cast <bool> (ReturnObject && "the return object is expected to be valid"
) ? void (0) : __assert_fail ("ReturnObject && \"the return object is expected to be valid\""
, "clang/lib/Sema/TreeTransform.h", 8049, __extension__ __PRETTY_FUNCTION__
))
;
8050 ExprResult Res = getDerived().TransformInitializer(ReturnObject,
8051 /*NoCopyInit*/ false);
8052 if (Res.isInvalid())
8053 return StmtError();
8054 Builder.ReturnValue = Res.get();
8055
8056 // If during the previous parse the coroutine still had a dependent promise
8057 // statement, we may need to build some implicit coroutine statements
8058 // (such as exception and fallthrough handlers) for the first time.
8059 if (S->hasDependentPromiseType()) {
8060 // We can only build these statements, however, if the current promise type
8061 // is not dependent.
8062 if (!Promise->getType()->isDependentType()) {
8063 assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&(static_cast <bool> (!S->getFallthroughHandler() &&
!S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure
() && !S->getDeallocate() && "these nodes should not have been built yet"
) ? void (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "clang/lib/Sema/TreeTransform.h", 8065, __extension__ __PRETTY_FUNCTION__
))
8064 !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&(static_cast <bool> (!S->getFallthroughHandler() &&
!S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure
() && !S->getDeallocate() && "these nodes should not have been built yet"
) ? void (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "clang/lib/Sema/TreeTransform.h", 8065, __extension__ __PRETTY_FUNCTION__
))
8065 "these nodes should not have been built yet")(static_cast <bool> (!S->getFallthroughHandler() &&
!S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure
() && !S->getDeallocate() && "these nodes should not have been built yet"
) ? void (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "clang/lib/Sema/TreeTransform.h", 8065, __extension__ __PRETTY_FUNCTION__
))
;
8066 if (!Builder.buildDependentStatements())
8067 return StmtError();
8068 }
8069 } else {
8070 if (auto *OnFallthrough = S->getFallthroughHandler()) {
8071 StmtResult Res = getDerived().TransformStmt(OnFallthrough);
8072 if (Res.isInvalid())
8073 return StmtError();
8074 Builder.OnFallthrough = Res.get();
8075 }
8076
8077 if (auto *OnException = S->getExceptionHandler()) {
8078 StmtResult Res = getDerived().TransformStmt(OnException);
8079 if (Res.isInvalid())
8080 return StmtError();
8081 Builder.OnException = Res.get();
8082 }
8083
8084 if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
8085 StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
8086 if (Res.isInvalid())
8087 return StmtError();
8088 Builder.ReturnStmtOnAllocFailure = Res.get();
8089 }
8090
8091 // Transform any additional statements we may have already built
8092 assert(S->getAllocate() && S->getDeallocate() &&(static_cast <bool> (S->getAllocate() && S->
getDeallocate() && "allocation and deallocation calls must already be built"
) ? void (0) : __assert_fail ("S->getAllocate() && S->getDeallocate() && \"allocation and deallocation calls must already be built\""
, "clang/lib/Sema/TreeTransform.h", 8093, __extension__ __PRETTY_FUNCTION__
))
8093 "allocation and deallocation calls must already be built")(static_cast <bool> (S->getAllocate() && S->
getDeallocate() && "allocation and deallocation calls must already be built"
) ? void (0) : __assert_fail ("S->getAllocate() && S->getDeallocate() && \"allocation and deallocation calls must already be built\""
, "clang/lib/Sema/TreeTransform.h", 8093, __extension__ __PRETTY_FUNCTION__
))
;
8094 ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
8095 if (AllocRes.isInvalid())
8096 return StmtError();
8097 Builder.Allocate = AllocRes.get();
8098
8099 ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
8100 if (DeallocRes.isInvalid())
8101 return StmtError();
8102 Builder.Deallocate = DeallocRes.get();
8103
8104 if (auto *ResultDecl = S->getResultDecl()) {
8105 StmtResult Res = getDerived().TransformStmt(ResultDecl);
8106 if (Res.isInvalid())
8107 return StmtError();
8108 Builder.ResultDecl = Res.get();
8109 }
8110
8111 if (auto *ReturnStmt = S->getReturnStmt()) {
8112 StmtResult Res = getDerived().TransformStmt(ReturnStmt);
8113 if (Res.isInvalid())
8114 return StmtError();
8115 Builder.ReturnStmt = Res.get();
8116 }
8117 }
8118
8119 return getDerived().RebuildCoroutineBodyStmt(Builder);
8120}
8121
8122template<typename Derived>
8123StmtResult
8124TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
8125 ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
8126 /*NotCopyInit*/false);
8127 if (Result.isInvalid())
8128 return StmtError();
8129
8130 // Always rebuild; we don't know if this needs to be injected into a new
8131 // context or if the promise type has changed.
8132 return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
8133 S->isImplicit());
8134}
8135
8136template <typename Derived>
8137ExprResult TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
8138 ExprResult Operand = getDerived().TransformInitializer(E->getOperand(),
8139 /*NotCopyInit*/ false);
8140 if (Operand.isInvalid())
8141 return ExprError();
8142
8143 // Rebuild the common-expr from the operand rather than transforming it
8144 // separately.
8145
8146 // FIXME: getCurScope() should not be used during template instantiation.
8147 // We should pick up the set of unqualified lookup results for operator
8148 // co_await during the initial parse.
8149 ExprResult Lookup = getSema().BuildOperatorCoawaitLookupExpr(
8150 getSema().getCurScope(), E->getKeywordLoc());
8151
8152 // Always rebuild; we don't know if this needs to be injected into a new
8153 // context or if the promise type has changed.
8154 return getDerived().RebuildCoawaitExpr(
8155 E->getKeywordLoc(), Operand.get(),
8156 cast<UnresolvedLookupExpr>(Lookup.get()), E->isImplicit());
8157}
8158
8159template <typename Derived>
8160ExprResult
8161TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
8162 ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
8163 /*NotCopyInit*/ false);
8164 if (OperandResult.isInvalid())
8165 return ExprError();
8166
8167 ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
8168 E->getOperatorCoawaitLookup());
8169
8170 if (LookupResult.isInvalid())
8171 return ExprError();
8172
8173 // Always rebuild; we don't know if this needs to be injected into a new
8174 // context or if the promise type has changed.
8175 return getDerived().RebuildDependentCoawaitExpr(
8176 E->getKeywordLoc(), OperandResult.get(),
8177 cast<UnresolvedLookupExpr>(LookupResult.get()));
8178}
8179
8180template<typename Derived>
8181ExprResult
8182TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
8183 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
8184 /*NotCopyInit*/false);
8185 if (Result.isInvalid())
8186 return ExprError();
8187
8188 // Always rebuild; we don't know if this needs to be injected into a new
8189 // context or if the promise type has changed.
8190 return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
8191}
8192
8193// Objective-C Statements.
8194
8195template<typename Derived>
8196StmtResult
8197TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
8198 // Transform the body of the @try.
8199 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
8200 if (TryBody.isInvalid())
8201 return StmtError();
8202
8203 // Transform the @catch statements (if present).
8204 bool AnyCatchChanged = false;
8205 SmallVector<Stmt*, 8> CatchStmts;
8206 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
8207 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
8208 if (Catch.isInvalid())
8209 return StmtError();
8210 if (Catch.get() != S->getCatchStmt(I))
8211 AnyCatchChanged = true;
8212 CatchStmts.push_back(Catch.get());
8213 }
8214
8215 // Transform the @finally statement (if present).
8216 StmtResult Finally;
8217 if (S->getFinallyStmt()) {
8218 Finally = getDerived().TransformStmt(S->getFinallyStmt());
8219 if (Finally.isInvalid())
8220 return StmtError();
8221 }
8222
8223 // If nothing changed, just retain this statement.
8224 if (!getDerived().AlwaysRebuild() &&
8225 TryBody.get() == S->getTryBody() &&
8226 !AnyCatchChanged &&
8227 Finally.get() == S->getFinallyStmt())
8228 return S;
8229
8230 // Build a new statement.
8231 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
8232 CatchStmts, Finally.get());
8233}
8234
8235template<typename Derived>
8236StmtResult
8237TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
8238 // Transform the @catch parameter, if there is one.
8239 VarDecl *Var = nullptr;
8240 if (VarDecl *FromVar = S->getCatchParamDecl()) {
8241 TypeSourceInfo *TSInfo = nullptr;
8242 if (FromVar->getTypeSourceInfo()) {
8243 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
8244 if (!TSInfo)
8245 return StmtError();
8246 }
8247
8248 QualType T;
8249 if (TSInfo)
8250 T = TSInfo->getType();
8251 else {
8252 T = getDerived().TransformType(FromVar->getType());
8253 if (T.isNull())
8254 return StmtError();
8255 }
8256
8257 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
8258 if (!Var)
8259 return StmtError();
8260 }
8261
8262 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
8263 if (Body.isInvalid())
8264 return StmtError();
8265
8266 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
8267 S->getRParenLoc(),
8268 Var, Body.get());
8269}
8270
8271template<typename Derived>
8272StmtResult
8273TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
8274 // Transform the body.
8275 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
8276 if (Body.isInvalid())
8277 return StmtError();
8278
8279 // If nothing changed, just retain this statement.
8280 if (!getDerived().AlwaysRebuild() &&
8281 Body.get() == S->getFinallyBody())
8282 return S;
8283
8284 // Build a new statement.
8285 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
8286 Body.get());
8287}
8288
8289template<typename Derived>
8290StmtResult
8291TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
8292 ExprResult Operand;
8293 if (S->getThrowExpr()) {
8294 Operand = getDerived().TransformExpr(S->getThrowExpr());
8295 if (Operand.isInvalid())
8296 return StmtError();
8297 }
8298
8299 if (!getDerived().AlwaysRebuild() &&
8300 Operand.get() == S->getThrowExpr())
8301 return S;
8302
8303 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
8304}
8305
8306template<typename Derived>
8307StmtResult
8308TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
8309 ObjCAtSynchronizedStmt *S) {
8310 // Transform the object we are locking.
8311 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
8312 if (Object.isInvalid())
8313 return StmtError();
8314 Object =
8315 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
8316 Object.get());
8317 if (Object.isInvalid())
8318 return StmtError();
8319
8320 // Transform the body.
8321 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
8322 if (Body.isInvalid())
8323 return StmtError();
8324
8325 // If nothing change, just retain the current statement.
8326 if (!getDerived().AlwaysRebuild() &&
8327 Object.get() == S->getSynchExpr() &&
8328 Body.get() == S->getSynchBody())
8329 return S;
8330
8331 // Build a new statement.
8332 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
8333 Object.get(), Body.get());
8334}
8335
8336template<typename Derived>
8337StmtResult
8338TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
8339 ObjCAutoreleasePoolStmt *S) {
8340 // Transform the body.
8341 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
8342 if (Body.isInvalid())
8343 return StmtError();
8344
8345 // If nothing changed, just retain this statement.
8346 if (!getDerived().AlwaysRebuild() &&
8347 Body.get() == S->getSubStmt())
8348 return S;
8349
8350 // Build a new statement.
8351 return getDerived().RebuildObjCAutoreleasePoolStmt(
8352 S->getAtLoc(), Body.get());
8353}
8354
8355template<typename Derived>
8356StmtResult
8357TreeTransform<Derived>::TransformObjCForCollectionStmt(
8358 ObjCForCollectionStmt *S) {
8359 // Transform the element statement.
8360 StmtResult Element =
8361 getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
8362 if (Element.isInvalid())
8363 return StmtError();
8364
8365 // Transform the collection expression.
8366 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
8367 if (Collection.isInvalid())
8368 return StmtError();
8369
8370 // Transform the body.
8371 StmtResult Body = getDerived().TransformStmt(S->getBody());
8372 if (Body.isInvalid())
8373 return StmtError();
8374
8375 // If nothing changed, just retain this statement.
8376 if (!getDerived().AlwaysRebuild() &&
8377 Element.get() == S->getElement() &&
8378 Collection.get() == S->getCollection() &&
8379 Body.get() == S->getBody())
8380 return S;
8381
8382 // Build a new statement.
8383 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
8384 Element.get(),
8385 Collection.get(),
8386 S->getRParenLoc(),
8387 Body.get());
8388}
8389
8390template <typename Derived>
8391StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
8392 // Transform the exception declaration, if any.
8393 VarDecl *Var = nullptr;
8394 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
8395 TypeSourceInfo *T =
8396 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
8397 if (!T)
8398 return StmtError();
8399
8400 Var = getDerived().RebuildExceptionDecl(
8401 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
8402 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
8403 if (!Var || Var->isInvalidDecl())
8404 return StmtError();
8405 }
8406
8407 // Transform the actual exception handler.
8408 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
8409 if (Handler.isInvalid())
8410 return StmtError();
8411
8412 if (!getDerived().AlwaysRebuild() && !Var &&
8413 Handler.get() == S->getHandlerBlock())
8414 return S;
8415
8416 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
8417}
8418
8419template <typename Derived>
8420StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
8421 // Transform the try block itself.
8422 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8423 if (TryBlock.isInvalid())
8424 return StmtError();
8425
8426 // Transform the handlers.
8427 bool HandlerChanged = false;
8428 SmallVector<Stmt *, 8> Handlers;
8429 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
8430 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
8431 if (Handler.isInvalid())
8432 return StmtError();
8433
8434 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
8435 Handlers.push_back(Handler.getAs<Stmt>());
8436 }
8437
8438 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8439 !HandlerChanged)
8440 return S;
8441
8442 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
8443 Handlers);
8444}
8445
8446template<typename Derived>
8447StmtResult
8448TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
8449 StmtResult Init =
8450 S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
8451 if (Init.isInvalid())
8452 return StmtError();
8453
8454 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
8455 if (Range.isInvalid())
8456 return StmtError();
8457
8458 StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
8459 if (Begin.isInvalid())
8460 return StmtError();
8461 StmtResult End = getDerived().TransformStmt(S->getEndStmt());
8462 if (End.isInvalid())
8463 return StmtError();
8464
8465 ExprResult Cond = getDerived().TransformExpr(S->getCond());
8466 if (Cond.isInvalid())
8467 return StmtError();
8468 if (Cond.get())
8469 Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
8470 if (Cond.isInvalid())
8471 return StmtError();
8472 if (Cond.get())
8473 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
8474
8475 ExprResult Inc = getDerived().TransformExpr(S->getInc());
8476 if (Inc.isInvalid())
8477 return StmtError();
8478 if (Inc.get())
8479 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
8480
8481 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
8482 if (LoopVar.isInvalid())
8483 return StmtError();
8484
8485 StmtResult NewStmt = S;
8486 if (getDerived().AlwaysRebuild() ||
8487 Init.get() != S->getInit() ||
8488 Range.get() != S->getRangeStmt() ||
8489 Begin.get() != S->getBeginStmt() ||
8490 End.get() != S->getEndStmt() ||
8491 Cond.get() != S->getCond() ||
8492 Inc.get() != S->getInc() ||
8493 LoopVar.get() != S->getLoopVarStmt()) {
8494 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8495 S->getCoawaitLoc(), Init.get(),
8496 S->getColonLoc(), Range.get(),
8497 Begin.get(), End.get(),
8498 Cond.get(),
8499 Inc.get(), LoopVar.get(),
8500 S->getRParenLoc());
8501 if (NewStmt.isInvalid() && LoopVar.get() != S->getLoopVarStmt()) {
8502 // Might not have attached any initializer to the loop variable.
8503 getSema().ActOnInitializerError(
8504 cast<DeclStmt>(LoopVar.get())->getSingleDecl());
8505 return StmtError();
8506 }
8507 }
8508
8509 StmtResult Body = getDerived().TransformStmt(S->getBody());
8510 if (Body.isInvalid())
8511 return StmtError();
8512
8513 // Body has changed but we didn't rebuild the for-range statement. Rebuild
8514 // it now so we have a new statement to attach the body to.
8515 if (Body.get() != S->getBody() && NewStmt.get() == S) {
8516 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8517 S->getCoawaitLoc(), Init.get(),
8518 S->getColonLoc(), Range.get(),
8519 Begin.get(), End.get(),
8520 Cond.get(),
8521 Inc.get(), LoopVar.get(),
8522 S->getRParenLoc());
8523 if (NewStmt.isInvalid())
8524 return StmtError();
8525 }
8526
8527 if (NewStmt.get() == S)
8528 return S;
8529
8530 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
8531}
8532
8533template<typename Derived>
8534StmtResult
8535TreeTransform<Derived>::TransformMSDependentExistsStmt(
8536 MSDependentExistsStmt *S) {
8537 // Transform the nested-name-specifier, if any.
8538 NestedNameSpecifierLoc QualifierLoc;
8539 if (S->getQualifierLoc()) {
8540 QualifierLoc
8541 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
8542 if (!QualifierLoc)
8543 return StmtError();
8544 }
8545
8546 // Transform the declaration name.
8547 DeclarationNameInfo NameInfo = S->getNameInfo();
8548 if (NameInfo.getName()) {
8549 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8550 if (!NameInfo.getName())
8551 return StmtError();
8552 }
8553
8554 // Check whether anything changed.
8555 if (!getDerived().AlwaysRebuild() &&
8556 QualifierLoc == S->getQualifierLoc() &&
8557 NameInfo.getName() == S->getNameInfo().getName())
8558 return S;
8559
8560 // Determine whether this name exists, if we can.
8561 CXXScopeSpec SS;
8562 SS.Adopt(QualifierLoc);
8563 bool Dependent = false;
8564 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
8565 case Sema::IER_Exists:
8566 if (S->isIfExists())
8567 break;
8568
8569 return new (getSema().Context) NullStmt(S->getKeywordLoc());
8570
8571 case Sema::IER_DoesNotExist:
8572 if (S->isIfNotExists())
8573 break;
8574
8575 return new (getSema().Context) NullStmt(S->getKeywordLoc());
8576
8577 case Sema::IER_Dependent:
8578 Dependent = true;
8579 break;
8580
8581 case Sema::IER_Error:
8582 return StmtError();
8583 }
8584
8585 // We need to continue with the instantiation, so do so now.
8586 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
8587 if (SubStmt.isInvalid())
8588 return StmtError();
8589
8590 // If we have resolved the name, just transform to the substatement.
8591 if (!Dependent)
8592 return SubStmt;
8593
8594 // The name is still dependent, so build a dependent expression again.
8595 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
8596 S->isIfExists(),
8597 QualifierLoc,
8598 NameInfo,
8599 SubStmt.get());
8600}
8601
8602template<typename Derived>
8603ExprResult
8604TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
8605 NestedNameSpecifierLoc QualifierLoc;
8606 if (E->getQualifierLoc()) {
8607 QualifierLoc
8608 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8609 if (!QualifierLoc)
8610 return ExprError();
8611 }
8612
8613 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
8614 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
8615 if (!PD)
8616 return ExprError();
8617
8618 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8619 if (Base.isInvalid())
8620 return ExprError();
8621
8622 return new (SemaRef.getASTContext())
8623 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
8624 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
8625 QualifierLoc, E->getMemberLoc());
8626}
8627
8628template <typename Derived>
8629ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
8630 MSPropertySubscriptExpr *E) {
8631 auto BaseRes = getDerived().TransformExpr(E->getBase());
8632 if (BaseRes.isInvalid())
8633 return ExprError();
8634 auto IdxRes = getDerived().TransformExpr(E->getIdx());
8635 if (IdxRes.isInvalid())
8636 return ExprError();
8637
8638 if (!getDerived().AlwaysRebuild() &&
8639 BaseRes.get() == E->getBase() &&
8640 IdxRes.get() == E->getIdx())
8641 return E;
8642
8643 return getDerived().RebuildArraySubscriptExpr(
8644 BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
8645}
8646
8647template <typename Derived>
8648StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
8649 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8650 if (TryBlock.isInvalid())
8651 return StmtError();
8652
8653 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
8654 if (Handler.isInvalid())
8655 return StmtError();
8656
8657 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8658 Handler.get() == S->getHandler())
8659 return S;
8660
8661 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
8662 TryBlock.get(), Handler.get());
8663}
8664
8665template <typename Derived>
8666StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
8667 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8668 if (Block.isInvalid())
8669 return StmtError();
8670
8671 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
8672}
8673
8674template <typename Derived>
8675StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
8676 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
8677 if (FilterExpr.isInvalid())
8678 return StmtError();
8679
8680 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8681 if (Block.isInvalid())
8682 return StmtError();
8683
8684 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
8685 Block.get());
8686}
8687
8688template <typename Derived>
8689StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
8690 if (isa<SEHFinallyStmt>(Handler))
8691 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
8692 else
8693 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
8694}
8695
8696template<typename Derived>
8697StmtResult
8698TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
8699 return S;
8700}
8701
8702//===----------------------------------------------------------------------===//
8703// OpenMP directive transformation
8704//===----------------------------------------------------------------------===//
8705
8706template <typename Derived>
8707StmtResult
8708TreeTransform<Derived>::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
8709 // OMPCanonicalLoops are eliminated during transformation, since they will be
8710 // recomputed by semantic analysis of the associated OMPLoopBasedDirective
8711 // after transformation.
8712 return getDerived().TransformStmt(L->getLoopStmt());
8713}
8714
8715template <typename Derived>
8716StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
8717 OMPExecutableDirective *D) {
8718
8719 // Transform the clauses
8720 llvm::SmallVector<OMPClause *, 16> TClauses;
8721 ArrayRef<OMPClause *> Clauses = D->clauses();
8722 TClauses.reserve(Clauses.size());
8723 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8724 I != E; ++I) {
8725 if (*I) {
8726 getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8727 OMPClause *Clause = getDerived().TransformOMPClause(*I);
8728 getDerived().getSema().EndOpenMPClause();
8729 if (Clause)
8730 TClauses.push_back(Clause);
8731 } else {
8732 TClauses.push_back(nullptr);
8733 }
8734 }
8735 StmtResult AssociatedStmt;
8736 if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8737 getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8738 /*CurScope=*/nullptr);
8739 StmtResult Body;
8740 {
8741 Sema::CompoundScopeRAII CompoundScope(getSema());
8742 Stmt *CS;
8743 if (D->getDirectiveKind() == OMPD_atomic ||
8744 D->getDirectiveKind() == OMPD_critical ||
8745 D->getDirectiveKind() == OMPD_section ||
8746 D->getDirectiveKind() == OMPD_master)
8747 CS = D->getAssociatedStmt();
8748 else
8749 CS = D->getRawStmt();
8750 Body = getDerived().TransformStmt(CS);
8751 if (Body.isUsable() && isOpenMPLoopDirective(D->getDirectiveKind()) &&
8752 getSema().getLangOpts().OpenMPIRBuilder)
8753 Body = getDerived().RebuildOMPCanonicalLoop(Body.get());
8754 }
8755 AssociatedStmt =
8756 getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8757 if (AssociatedStmt.isInvalid()) {
8758 return StmtError();
8759 }
8760 }
8761 if (TClauses.size() != Clauses.size()) {
8762 return StmtError();
8763 }
8764
8765 // Transform directive name for 'omp critical' directive.
8766 DeclarationNameInfo DirName;
8767 if (D->getDirectiveKind() == OMPD_critical) {
8768 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8769 DirName = getDerived().TransformDeclarationNameInfo(DirName);
8770 }
8771 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8772 if (D->getDirectiveKind() == OMPD_cancellation_point) {
8773 CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8774 } else if (D->getDirectiveKind() == OMPD_cancel) {
8775 CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8776 }
8777
8778 return getDerived().RebuildOMPExecutableDirective(
8779 D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8780 AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
8781}
8782
8783template <typename Derived>
8784StmtResult
8785TreeTransform<Derived>::TransformOMPMetaDirective(OMPMetaDirective *D) {
8786 // TODO: Fix This
8787 SemaRef.Diag(D->getBeginLoc(), diag::err_omp_instantiation_not_supported)
8788 << getOpenMPDirectiveName(D->getDirectiveKind());
8789 return StmtError();
8790}
8791
8792template <typename Derived>
8793StmtResult
8794TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8795 DeclarationNameInfo DirName;
8796 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8797 D->getBeginLoc());
8798 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8799 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8800 return Res;
8801}
8802
8803template <typename Derived>
8804StmtResult
8805TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8806 DeclarationNameInfo DirName;
8807 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8808 D->getBeginLoc());
8809 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8810 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8811 return Res;
8812}
8813
8814template <typename Derived>
8815StmtResult
8816TreeTransform<Derived>::TransformOMPTileDirective(OMPTileDirective *D) {
8817 DeclarationNameInfo DirName;
8818 getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8819 nullptr, D->getBeginLoc());
8820 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8821 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8822 return Res;
8823}
8824
8825template <typename Derived>
8826StmtResult
8827TreeTransform<Derived>::TransformOMPUnrollDirective(OMPUnrollDirective *D) {
8828 DeclarationNameInfo DirName;
8829 getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8830 nullptr, D->getBeginLoc());
8831 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8832 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8833 return Res;
8834}
8835
8836template <typename Derived>
8837StmtResult
8838TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8839 DeclarationNameInfo DirName;
8840 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8841 D->getBeginLoc());
8842 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8843 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8844 return Res;
8845}
8846
8847template <typename Derived>
8848StmtResult
8849TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8850 DeclarationNameInfo DirName;
8851 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8852 D->getBeginLoc());
8853 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8854 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8855 return Res;
8856}
8857
8858template <typename Derived>
8859StmtResult
8860TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8861 DeclarationNameInfo DirName;
8862 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8863 D->getBeginLoc());
8864 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8865 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8866 return Res;
8867}
8868
8869template <typename Derived>
8870StmtResult
8871TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8872 DeclarationNameInfo DirName;
8873 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8874 D->getBeginLoc());
8875 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8876 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8877 return Res;
8878}
8879
8880template <typename Derived>
8881StmtResult
8882TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8883 DeclarationNameInfo DirName;
8884 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8885 D->getBeginLoc());
8886 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8887 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8888 return Res;
8889}
8890
8891template <typename Derived>
8892StmtResult
8893TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8894 DeclarationNameInfo DirName;
8895 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8896 D->getBeginLoc());
8897 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8898 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8899 return Res;
8900}
8901
8902template <typename Derived>
8903StmtResult
8904TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8905 getDerived().getSema().StartOpenMPDSABlock(
8906 OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8907 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8908 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8909 return Res;
8910}
8911
8912template <typename Derived>
8913StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8914 OMPParallelForDirective *D) {
8915 DeclarationNameInfo DirName;
8916 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8917 nullptr, D->getBeginLoc());
8918 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8919 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8920 return Res;
8921}
8922
8923template <typename Derived>
8924StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8925 OMPParallelForSimdDirective *D) {
8926 DeclarationNameInfo DirName;
8927 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8928 nullptr, D->getBeginLoc());
8929 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8930 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8931 return Res;
8932}
8933
8934template <typename Derived>
8935StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
8936 OMPParallelMasterDirective *D) {
8937 DeclarationNameInfo DirName;
8938 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
8939 nullptr, D->getBeginLoc());
8940 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8941 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8942 return Res;
8943}
8944
8945template <typename Derived>
8946StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedDirective(
8947 OMPParallelMaskedDirective *D) {
8948 DeclarationNameInfo DirName;
8949 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_masked, DirName,
8950 nullptr, D->getBeginLoc());
8951 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8952 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8953 return Res;
8954}
8955
8956template <typename Derived>
8957StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8958 OMPParallelSectionsDirective *D) {
8959 DeclarationNameInfo DirName;
8960 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8961 nullptr, D->getBeginLoc());
8962 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8963 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8964 return Res;
8965}
8966
8967template <typename Derived>
8968StmtResult
8969TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8970 DeclarationNameInfo DirName;
8971 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8972 D->getBeginLoc());
8973 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8974 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8975 return Res;
8976}
8977
8978template <typename Derived>
8979StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8980 OMPTaskyieldDirective *D) {
8981 DeclarationNameInfo DirName;
8982 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8983 D->getBeginLoc());
8984 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8985 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8986 return Res;
8987}
8988
8989template <typename Derived>
8990StmtResult
8991TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8992 DeclarationNameInfo DirName;
8993 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8994 D->getBeginLoc());
8995 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8996 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8997 return Res;
8998}
8999
9000template <typename Derived>
9001StmtResult
9002TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
9003 DeclarationNameInfo DirName;
9004 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
9005 D->getBeginLoc());
9006 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9007 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9008 return Res;
9009}
9010
9011template <typename Derived>
9012StmtResult
9013TreeTransform<Derived>::TransformOMPErrorDirective(OMPErrorDirective *D) {
9014 DeclarationNameInfo DirName;
9015 getDerived().getSema().StartOpenMPDSABlock(OMPD_error, DirName, nullptr,
9016 D->getBeginLoc());
9017 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9018 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9019 return Res;
9020}
9021
9022template <typename Derived>
9023StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
9024 OMPTaskgroupDirective *D) {
9025 DeclarationNameInfo DirName;
9026 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
9027 D->getBeginLoc());
9028 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9029 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9030 return Res;
9031}
9032
9033template <typename Derived>
9034StmtResult
9035TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
9036 DeclarationNameInfo DirName;
9037 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
9038 D->getBeginLoc());
9039 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9040 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9041 return Res;
9042}
9043
9044template <typename Derived>
9045StmtResult
9046TreeTransform<Derived>::TransformOMPDepobjDirective(OMPDepobjDirective *D) {
9047 DeclarationNameInfo DirName;
9048 getDerived().getSema().StartOpenMPDSABlock(OMPD_depobj, DirName, nullptr,
9049 D->getBeginLoc());
9050 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9051 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9052 return Res;
9053}
9054
9055template <typename Derived>
9056StmtResult
9057TreeTransform<Derived>::TransformOMPScanDirective(OMPScanDirective *D) {
9058 DeclarationNameInfo DirName;
9059 getDerived().getSema().StartOpenMPDSABlock(OMPD_scan, DirName, nullptr,
9060 D->getBeginLoc());
9061 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9062 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9063 return Res;
9064}
9065
9066template <typename Derived>
9067StmtResult
9068TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
9069 DeclarationNameInfo DirName;
9070 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
9071 D->getBeginLoc());
9072 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9073 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9074 return Res;
9075}
9076
9077template <typename Derived>
9078StmtResult
9079TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
9080 DeclarationNameInfo DirName;
9081 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
9082 D->getBeginLoc());
9083 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9084 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9085 return Res;
9086}
9087
9088template <typename Derived>
9089StmtResult
9090TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
9091 DeclarationNameInfo DirName;
9092 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
9093 D->getBeginLoc());
9094 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9095 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9096 return Res;
9097}
9098
9099template <typename Derived>
9100StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
9101 OMPTargetDataDirective *D) {
9102 DeclarationNameInfo DirName;
9103 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
9104 D->getBeginLoc());
9105 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9106 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9107 return Res;
9108}
9109
9110template <typename Derived>
9111StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
9112 OMPTargetEnterDataDirective *D) {
9113 DeclarationNameInfo DirName;
9114 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
9115 nullptr, D->getBeginLoc());
9116 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9117 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9118 return Res;
9119}
9120
9121template <typename Derived>
9122StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
9123 OMPTargetExitDataDirective *D) {
9124 DeclarationNameInfo DirName;
9125 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
9126 nullptr, D->getBeginLoc());
9127 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9128 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9129 return Res;
9130}
9131
9132template <typename Derived>
9133StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
9134 OMPTargetParallelDirective *D) {
9135 DeclarationNameInfo DirName;
9136 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
9137 nullptr, D->getBeginLoc());
9138 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9139 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9140 return Res;
9141}
9142
9143template <typename Derived>
9144StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
9145 OMPTargetParallelForDirective *D) {
9146 DeclarationNameInfo DirName;
9147 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
9148 nullptr, D->getBeginLoc());
9149 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9150 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9151 return Res;
9152}
9153
9154template <typename Derived>
9155StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
9156 OMPTargetUpdateDirective *D) {
9157 DeclarationNameInfo DirName;
9158 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
9159 nullptr, D->getBeginLoc());
9160 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9161 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9162 return Res;
9163}
9164
9165template <typename Derived>
9166StmtResult
9167TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
9168 DeclarationNameInfo DirName;
9169 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
9170 D->getBeginLoc());
9171 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9172 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9173 return Res;
9174}
9175
9176template <typename Derived>
9177StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
9178 OMPCancellationPointDirective *D) {
9179 DeclarationNameInfo DirName;
9180 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
9181 nullptr, D->getBeginLoc());
9182 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9183 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9184 return Res;
9185}
9186
9187template <typename Derived>
9188StmtResult
9189TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
9190 DeclarationNameInfo DirName;
9191 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
9192 D->getBeginLoc());
9193 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9194 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9195 return Res;
9196}
9197
9198template <typename Derived>
9199StmtResult
9200TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
9201 DeclarationNameInfo DirName;
9202 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
9203 D->getBeginLoc());
9204 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9205 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9206 return Res;
9207}
9208
9209template <typename Derived>
9210StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
9211 OMPTaskLoopSimdDirective *D) {
9212 DeclarationNameInfo DirName;
9213 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
9214 nullptr, D->getBeginLoc());
9215 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9216 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9217 return Res;
9218}
9219
9220template <typename Derived>
9221StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
9222 OMPMasterTaskLoopDirective *D) {
9223 DeclarationNameInfo DirName;
9224 getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
9225 nullptr, D->getBeginLoc());
9226 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9227 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9228 return Res;
9229}
9230
9231template <typename Derived>
9232StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopDirective(
9233 OMPMaskedTaskLoopDirective *D) {
9234 DeclarationNameInfo DirName;
9235 getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop, DirName,
9236 nullptr, D->getBeginLoc());
9237 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9238 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9239 return Res;
9240}
9241
9242template <typename Derived>
9243StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
9244 OMPMasterTaskLoopSimdDirective *D) {
9245 DeclarationNameInfo DirName;
9246 getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
9247 nullptr, D->getBeginLoc());
9248 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9249 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9250 return Res;
9251}
9252
9253template <typename Derived>
9254StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopSimdDirective(
9255 OMPMaskedTaskLoopSimdDirective *D) {
9256 DeclarationNameInfo DirName;
9257 getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop_simd, DirName,
9258 nullptr, D->getBeginLoc());
9259 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9260 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9261 return Res;
9262}
9263
9264template <typename Derived>
9265StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
9266 OMPParallelMasterTaskLoopDirective *D) {
9267 DeclarationNameInfo DirName;
9268 getDerived().getSema().StartOpenMPDSABlock(
9269 OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
9270 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9271 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9272 return Res;
9273}
9274
9275template <typename Derived>
9276StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopDirective(
9277 OMPParallelMaskedTaskLoopDirective *D) {
9278 DeclarationNameInfo DirName;
9279 getDerived().getSema().StartOpenMPDSABlock(
9280 OMPD_parallel_masked_taskloop, DirName, nullptr, D->getBeginLoc());
9281 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9282 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9283 return Res;
9284}
9285
9286template <typename Derived>
9287StmtResult
9288TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
9289 OMPParallelMasterTaskLoopSimdDirective *D) {
9290 DeclarationNameInfo DirName;
9291 getDerived().getSema().StartOpenMPDSABlock(
9292 OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9293 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9294 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9295 return Res;
9296}
9297
9298template <typename Derived>
9299StmtResult
9300TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopSimdDirective(
9301 OMPParallelMaskedTaskLoopSimdDirective *D) {
9302 DeclarationNameInfo DirName;
9303 getDerived().getSema().StartOpenMPDSABlock(
9304 OMPD_parallel_masked_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9305 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9306 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9307 return Res;
9308}
9309
9310template <typename Derived>
9311StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
9312 OMPDistributeDirective *D) {
9313 DeclarationNameInfo DirName;
9314 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
9315 D->getBeginLoc());
9316 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9317 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9318 return Res;
9319}
9320
9321template <typename Derived>
9322StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
9323 OMPDistributeParallelForDirective *D) {
9324 DeclarationNameInfo DirName;
9325 getDerived().getSema().StartOpenMPDSABlock(
9326 OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9327 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9328 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9329 return Res;
9330}
9331
9332template <typename Derived>
9333StmtResult
9334TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
9335 OMPDistributeParallelForSimdDirective *D) {
9336 DeclarationNameInfo DirName;
9337 getDerived().getSema().StartOpenMPDSABlock(
9338 OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9339 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9340 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9341 return Res;
9342}
9343
9344template <typename Derived>
9345StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
9346 OMPDistributeSimdDirective *D) {
9347 DeclarationNameInfo DirName;
9348 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
9349 nullptr, D->getBeginLoc());
9350 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9351 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9352 return Res;
9353}
9354
9355template <typename Derived>
9356StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
9357 OMPTargetParallelForSimdDirective *D) {
9358 DeclarationNameInfo DirName;
9359 getDerived().getSema().StartOpenMPDSABlock(
9360 OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9361 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9362 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9363 return Res;
9364}
9365
9366template <typename Derived>
9367StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
9368 OMPTargetSimdDirective *D) {
9369 DeclarationNameInfo DirName;
9370 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
9371 D->getBeginLoc());
9372 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9373 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9374 return Res;
9375}
9376
9377template <typename Derived>
9378StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
9379 OMPTeamsDistributeDirective *D) {
9380 DeclarationNameInfo DirName;
9381 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
9382 nullptr, D->getBeginLoc());
9383 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9384 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9385 return Res;
9386}
9387
9388template <typename Derived>
9389StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
9390 OMPTeamsDistributeSimdDirective *D) {
9391 DeclarationNameInfo DirName;
9392 getDerived().getSema().StartOpenMPDSABlock(
9393 OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9394 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9395 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9396 return Res;
9397}
9398
9399template <typename Derived>
9400StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
9401 OMPTeamsDistributeParallelForSimdDirective *D) {
9402 DeclarationNameInfo DirName;
9403 getDerived().getSema().StartOpenMPDSABlock(
9404 OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
9405 D->getBeginLoc());
9406 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9407 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9408 return Res;
9409}
9410
9411template <typename Derived>
9412StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
9413 OMPTeamsDistributeParallelForDirective *D) {
9414 DeclarationNameInfo DirName;
9415 getDerived().getSema().StartOpenMPDSABlock(
9416 OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9417 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9418 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9419 return Res;
9420}
9421
9422template <typename Derived>
9423StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
9424 OMPTargetTeamsDirective *D) {
9425 DeclarationNameInfo DirName;
9426 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
9427 nullptr, D->getBeginLoc());
9428 auto Res = getDerived().TransformOMPExecutableDirective(D);
9429 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9430 return Res;
9431}
9432
9433template <typename Derived>
9434StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
9435 OMPTargetTeamsDistributeDirective *D) {
9436 DeclarationNameInfo DirName;
9437 getDerived().getSema().StartOpenMPDSABlock(
9438 OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
9439 auto Res = getDerived().TransformOMPExecutableDirective(D);
9440 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9441 return Res;
9442}
9443
9444template <typename Derived>
9445StmtResult
9446TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
9447 OMPTargetTeamsDistributeParallelForDirective *D) {
9448 DeclarationNameInfo DirName;
9449 getDerived().getSema().StartOpenMPDSABlock(
9450 OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
9451 D->getBeginLoc());
9452 auto Res = getDerived().TransformOMPExecutableDirective(D);
9453 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9454 return Res;
9455}
9456
9457template <typename Derived>
9458StmtResult TreeTransform<Derived>::
9459 TransformOMPTargetTeamsDistributeParallelForSimdDirective(
9460 OMPTargetTeamsDistributeParallelForSimdDirective *D) {
9461 DeclarationNameInfo DirName;
9462 getDerived().getSema().StartOpenMPDSABlock(
9463 OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
9464 D->getBeginLoc());
9465 auto Res = getDerived().TransformOMPExecutableDirective(D);
9466 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9467 return Res;
9468}
9469
9470template <typename Derived>
9471StmtResult
9472TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
9473 OMPTargetTeamsDistributeSimdDirective *D) {
9474 DeclarationNameInfo DirName;
9475 getDerived().getSema().StartOpenMPDSABlock(
9476 OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9477 auto Res = getDerived().TransformOMPExecutableDirective(D);
9478 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9479 return Res;
9480}
9481
9482template <typename Derived>
9483StmtResult
9484TreeTransform<Derived>::TransformOMPInteropDirective(OMPInteropDirective *D) {
9485 DeclarationNameInfo DirName;
9486 getDerived().getSema().StartOpenMPDSABlock(OMPD_interop, DirName, nullptr,
9487 D->getBeginLoc());
9488 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9489 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9490 return Res;
9491}
9492
9493template <typename Derived>
9494StmtResult
9495TreeTransform<Derived>::TransformOMPDispatchDirective(OMPDispatchDirective *D) {
9496 DeclarationNameInfo DirName;
9497 getDerived().getSema().StartOpenMPDSABlock(OMPD_dispatch, DirName, nullptr,
9498 D->getBeginLoc());
9499 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9500 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9501 return Res;
9502}
9503
9504template <typename Derived>
9505StmtResult
9506TreeTransform<Derived>::TransformOMPMaskedDirective(OMPMaskedDirective *D) {
9507 DeclarationNameInfo DirName;
9508 getDerived().getSema().StartOpenMPDSABlock(OMPD_masked, DirName, nullptr,
9509 D->getBeginLoc());
9510 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9511 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9512 return Res;
9513}
9514
9515template <typename Derived>
9516StmtResult TreeTransform<Derived>::TransformOMPGenericLoopDirective(
9517 OMPGenericLoopDirective *D) {
9518 DeclarationNameInfo DirName;
9519 getDerived().getSema().StartOpenMPDSABlock(OMPD_loop, DirName, nullptr,
9520 D->getBeginLoc());
9521 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9522 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9523 return Res;
9524}
9525
9526template <typename Derived>
9527StmtResult TreeTransform<Derived>::TransformOMPTeamsGenericLoopDirective(
9528 OMPTeamsGenericLoopDirective *D) {
9529 DeclarationNameInfo DirName;
9530 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_loop, DirName, nullptr,
9531 D->getBeginLoc());
9532 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9533 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9534 return Res;
9535}
9536
9537template <typename Derived>
9538StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsGenericLoopDirective(
9539 OMPTargetTeamsGenericLoopDirective *D) {
9540 DeclarationNameInfo DirName;
9541 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams_loop, DirName,
9542 nullptr, D->getBeginLoc());
9543 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9544 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9545 return Res;
9546}
9547
9548template <typename Derived>
9549StmtResult TreeTransform<Derived>::TransformOMPParallelGenericLoopDirective(
9550 OMPParallelGenericLoopDirective *D) {
9551 DeclarationNameInfo DirName;
9552 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_loop, DirName,
9553 nullptr, D->getBeginLoc());
9554 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9555 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9556 return Res;
9557}
9558
9559template <typename Derived>
9560StmtResult
9561TreeTransform<Derived>::TransformOMPTargetParallelGenericLoopDirective(
9562 OMPTargetParallelGenericLoopDirective *D) {
9563 DeclarationNameInfo DirName;
9564 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_loop, DirName,
9565 nullptr, D->getBeginLoc());
9566 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9567 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9568 return Res;
9569}
9570
9571//===----------------------------------------------------------------------===//
9572// OpenMP clause transformation
9573//===----------------------------------------------------------------------===//
9574template <typename Derived>
9575OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
9576 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9577 if (Cond.isInvalid())
9578 return nullptr;
9579 return getDerived().RebuildOMPIfClause(
9580 C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
9581 C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
9582}
9583
9584template <typename Derived>
9585OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
9586 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9587 if (Cond.isInvalid())
9588 return nullptr;
9589 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
9590 C->getLParenLoc(), C->getEndLoc());
9591}
9592
9593template <typename Derived>
9594OMPClause *
9595TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
9596 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
9597 if (NumThreads.isInvalid())
9598 return nullptr;
9599 return getDerived().RebuildOMPNumThreadsClause(
9600 NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9601}
9602
9603template <typename Derived>
9604OMPClause *
9605TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
9606 ExprResult E = getDerived().TransformExpr(C->getSafelen());
9607 if (E.isInvalid())
9608 return nullptr;
9609 return getDerived().RebuildOMPSafelenClause(
9610 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9611}
9612
9613template <typename Derived>
9614OMPClause *
9615TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
9616 ExprResult E = getDerived().TransformExpr(C->getAllocator());
9617 if (E.isInvalid())
9618 return nullptr;
9619 return getDerived().RebuildOMPAllocatorClause(
9620 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9621}
9622
9623template <typename Derived>
9624OMPClause *
9625TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
9626 ExprResult E = getDerived().TransformExpr(C->getSimdlen());
9627 if (E.isInvalid())
9628 return nullptr;
9629 return getDerived().RebuildOMPSimdlenClause(
9630 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9631}
9632
9633template <typename Derived>
9634OMPClause *TreeTransform<Derived>::TransformOMPSizesClause(OMPSizesClause *C) {
9635 SmallVector<Expr *, 4> TransformedSizes;
9636 TransformedSizes.reserve(C->getNumSizes());
9637 bool Changed = false;
9638 for (Expr *E : C->getSizesRefs()) {
9639 if (!E) {
9640 TransformedSizes.push_back(nullptr);
9641 continue;
9642 }
9643
9644 ExprResult T = getDerived().TransformExpr(E);
9645 if (T.isInvalid())
9646 return nullptr;
9647 if (E != T.get())
9648 Changed = true;
9649 TransformedSizes.push_back(T.get());
9650 }
9651
9652 if (!Changed && !getDerived().AlwaysRebuild())
9653 return C;
9654 return RebuildOMPSizesClause(TransformedSizes, C->getBeginLoc(),
9655 C->getLParenLoc(), C->getEndLoc());
9656}
9657
9658template <typename Derived>
9659OMPClause *TreeTransform<Derived>::TransformOMPFullClause(OMPFullClause *C) {
9660 if (!getDerived().AlwaysRebuild())
9661 return C;
9662 return RebuildOMPFullClause(C->getBeginLoc(), C->getEndLoc());
9663}
9664
9665template <typename Derived>
9666OMPClause *
9667TreeTransform<Derived>::TransformOMPPartialClause(OMPPartialClause *C) {
9668 ExprResult T = getDerived().TransformExpr(C->getFactor());
9669 if (T.isInvalid())
9670 return nullptr;
9671 Expr *Factor = T.get();
9672 bool Changed = Factor != C->getFactor();
9673
9674 if (!Changed && !getDerived().AlwaysRebuild())
9675 return C;
9676 return RebuildOMPPartialClause(Factor, C->getBeginLoc(), C->getLParenLoc(),
9677 C->getEndLoc());
9678}
9679
9680template <typename Derived>
9681OMPClause *
9682TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
9683 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
9684 if (E.isInvalid())
9685 return nullptr;
9686 return getDerived().RebuildOMPCollapseClause(
9687 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9688}
9689
9690template <typename Derived>
9691OMPClause *
9692TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
9693 return getDerived().RebuildOMPDefaultClause(
9694 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
9695 C->getLParenLoc(), C->getEndLoc());
9696}
9697
9698template <typename Derived>
9699OMPClause *
9700TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
9701 return getDerived().RebuildOMPProcBindClause(
9702 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
9703 C->getLParenLoc(), C->getEndLoc());
9704}
9705
9706template <typename Derived>
9707OMPClause *
9708TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
9709 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9710 if (E.isInvalid())
9711 return nullptr;
9712 return getDerived().RebuildOMPScheduleClause(
9713 C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
9714 C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9715 C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
9716 C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9717}
9718
9719template <typename Derived>
9720OMPClause *
9721TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
9722 ExprResult E;
9723 if (auto *Num = C->getNumForLoops()) {
9724 E = getDerived().TransformExpr(Num);
9725 if (E.isInvalid())
9726 return nullptr;
9727 }
9728 return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
9729 C->getLParenLoc(), E.get());
9730}
9731
9732template <typename Derived>
9733OMPClause *
9734TreeTransform<Derived>::TransformOMPDetachClause(OMPDetachClause *C) {
9735 ExprResult E;
9736 if (Expr *Evt = C->getEventHandler()) {
9737 E = getDerived().TransformExpr(Evt);
9738 if (E.isInvalid())
9739 return nullptr;
9740 }
9741 return getDerived().RebuildOMPDetachClause(E.get(), C->getBeginLoc(),
9742 C->getLParenLoc(), C->getEndLoc());
9743}
9744
9745template <typename Derived>
9746OMPClause *
9747TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
9748 // No need to rebuild this clause, no template-dependent parameters.
9749 return C;
9750}
9751
9752template <typename Derived>
9753OMPClause *
9754TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
9755 // No need to rebuild this clause, no template-dependent parameters.
9756 return C;
9757}
9758
9759template <typename Derived>
9760OMPClause *
9761TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
9762 // No need to rebuild this clause, no template-dependent parameters.
9763 return C;
9764}
9765
9766template <typename Derived>
9767OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
9768 // No need to rebuild this clause, no template-dependent parameters.
9769 return C;
9770}
9771
9772template <typename Derived>
9773OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
9774 // No need to rebuild this clause, no template-dependent parameters.
9775 return C;
9776}
9777
9778template <typename Derived>
9779OMPClause *
9780TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
9781 // No need to rebuild this clause, no template-dependent parameters.
9782 return C;
9783}
9784
9785template <typename Derived>
9786OMPClause *
9787TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
9788 // No need to rebuild this clause, no template-dependent parameters.
9789 return C;
9790}
9791
9792template <typename Derived>
9793OMPClause *
9794TreeTransform<Derived>::TransformOMPCompareClause(OMPCompareClause *C) {
9795 // No need to rebuild this clause, no template-dependent parameters.
9796 return C;
9797}
9798
9799template <typename Derived>
9800OMPClause *
9801TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
9802 // No need to rebuild this clause, no template-dependent parameters.
9803 return C;
9804}
9805
9806template <typename Derived>
9807OMPClause *
9808TreeTransform<Derived>::TransformOMPAcqRelClause(OMPAcqRelClause *C) {
9809 // No need to rebuild this clause, no template-dependent parameters.
9810 return C;
9811}
9812
9813template <typename Derived>
9814OMPClause *
9815TreeTransform<Derived>::TransformOMPAcquireClause(OMPAcquireClause *C) {
9816 // No need to rebuild this clause, no template-dependent parameters.
9817 return C;
9818}
9819
9820template <typename Derived>
9821OMPClause *
9822TreeTransform<Derived>::TransformOMPReleaseClause(OMPReleaseClause *C) {
9823 // No need to rebuild this clause, no template-dependent parameters.
9824 return C;
9825}
9826
9827template <typename Derived>
9828OMPClause *
9829TreeTransform<Derived>::TransformOMPRelaxedClause(OMPRelaxedClause *C) {
9830 // No need to rebuild this clause, no template-dependent parameters.
9831 return C;
9832}
9833
9834template <typename Derived>
9835OMPClause *
9836TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
9837 // No need to rebuild this clause, no template-dependent parameters.
9838 return C;
9839}
9840
9841template <typename Derived>
9842OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
9843 // No need to rebuild this clause, no template-dependent parameters.
9844 return C;
9845}
9846
9847template <typename Derived>
9848OMPClause *
9849TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
9850 // No need to rebuild this clause, no template-dependent parameters.
9851 return C;
9852}
9853
9854template <typename Derived>
9855OMPClause *TreeTransform<Derived>::TransformOMPInitClause(OMPInitClause *C) {
9856 ExprResult IVR = getDerived().TransformExpr(C->getInteropVar());
9857 if (IVR.isInvalid())
9858 return nullptr;
9859
9860 OMPInteropInfo InteropInfo(C->getIsTarget(), C->getIsTargetSync());
9861 InteropInfo.PreferTypes.reserve(C->varlist_size() - 1);
9862 for (Expr *E : llvm::drop_begin(C->varlists())) {
9863 ExprResult ER = getDerived().TransformExpr(cast<Expr>(E));
9864 if (ER.isInvalid())
9865 return nullptr;
9866 InteropInfo.PreferTypes.push_back(ER.get());
9867 }
9868 return getDerived().RebuildOMPInitClause(IVR.get(), InteropInfo,
9869 C->getBeginLoc(), C->getLParenLoc(),
9870 C->getVarLoc(), C->getEndLoc());
9871}
9872
9873template <typename Derived>
9874OMPClause *TreeTransform<Derived>::TransformOMPUseClause(OMPUseClause *C) {
9875 ExprResult ER = getDerived().TransformExpr(C->getInteropVar());
9876 if (ER.isInvalid())
9877 return nullptr;
9878 return getDerived().RebuildOMPUseClause(ER.get(), C->getBeginLoc(),
9879 C->getLParenLoc(), C->getVarLoc(),
9880 C->getEndLoc());
9881}
9882
9883template <typename Derived>
9884OMPClause *
9885TreeTransform<Derived>::TransformOMPDestroyClause(OMPDestroyClause *C) {
9886 ExprResult ER;
9887 if (Expr *IV = C->getInteropVar()) {
9888 ER = getDerived().TransformExpr(IV);
9889 if (ER.isInvalid())
9890 return nullptr;
9891 }
9892 return getDerived().RebuildOMPDestroyClause(ER.get(), C->getBeginLoc(),
9893 C->getLParenLoc(), C->getVarLoc(),
9894 C->getEndLoc());
9895}
9896
9897template <typename Derived>
9898OMPClause *
9899TreeTransform<Derived>::TransformOMPNovariantsClause(OMPNovariantsClause *C) {
9900 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9901 if (Cond.isInvalid())
9902 return nullptr;
9903 return getDerived().RebuildOMPNovariantsClause(
9904 Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9905}
9906
9907template <typename Derived>
9908OMPClause *
9909TreeTransform<Derived>::TransformOMPNocontextClause(OMPNocontextClause *C) {
9910 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9911 if (Cond.isInvalid())
9912 return nullptr;
9913 return getDerived().RebuildOMPNocontextClause(
9914 Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9915}
9916
9917template <typename Derived>
9918OMPClause *
9919TreeTransform<Derived>::TransformOMPFilterClause(OMPFilterClause *C) {
9920 ExprResult ThreadID = getDerived().TransformExpr(C->getThreadID());
9921 if (ThreadID.isInvalid())
9922 return nullptr;
9923 return getDerived().RebuildOMPFilterClause(ThreadID.get(), C->getBeginLoc(),
9924 C->getLParenLoc(), C->getEndLoc());
9925}
9926
9927template <typename Derived>
9928OMPClause *TreeTransform<Derived>::TransformOMPAlignClause(OMPAlignClause *C) {
9929 ExprResult E = getDerived().TransformExpr(C->getAlignment());
9930 if (E.isInvalid())
9931 return nullptr;
9932 return getDerived().RebuildOMPAlignClause(E.get(), C->getBeginLoc(),
9933 C->getLParenLoc(), C->getEndLoc());
9934}
9935
9936template <typename Derived>
9937OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
9938 OMPUnifiedAddressClause *C) {
9939 llvm_unreachable("unified_address clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("unified_address clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9939)
;
9940}
9941
9942template <typename Derived>
9943OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
9944 OMPUnifiedSharedMemoryClause *C) {
9945 llvm_unreachable(::llvm::llvm_unreachable_internal("unified_shared_memory clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9946)
9946 "unified_shared_memory clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("unified_shared_memory clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9946)
;
9947}
9948
9949template <typename Derived>
9950OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
9951 OMPReverseOffloadClause *C) {
9952 llvm_unreachable("reverse_offload clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("reverse_offload clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9952)
;
9953}
9954
9955template <typename Derived>
9956OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
9957 OMPDynamicAllocatorsClause *C) {
9958 llvm_unreachable(::llvm::llvm_unreachable_internal("dynamic_allocators clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9959)
9959 "dynamic_allocators clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("dynamic_allocators clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9959)
;
9960}
9961
9962template <typename Derived>
9963OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
9964 OMPAtomicDefaultMemOrderClause *C) {
9965 llvm_unreachable(::llvm::llvm_unreachable_internal("atomic_default_mem_order clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9966)
9966 "atomic_default_mem_order clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("atomic_default_mem_order clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9966)
;
9967}
9968
9969template <typename Derived>
9970OMPClause *TreeTransform<Derived>::TransformOMPAtClause(OMPAtClause *C) {
9971 return getDerived().RebuildOMPAtClause(C->getAtKind(), C->getAtKindKwLoc(),
9972 C->getBeginLoc(), C->getLParenLoc(),
9973 C->getEndLoc());
9974}
9975
9976template <typename Derived>
9977OMPClause *
9978TreeTransform<Derived>::TransformOMPSeverityClause(OMPSeverityClause *C) {
9979 return getDerived().RebuildOMPSeverityClause(
9980 C->getSeverityKind(), C->getSeverityKindKwLoc(), C->getBeginLoc(),
9981 C->getLParenLoc(), C->getEndLoc());
9982}
9983
9984template <typename Derived>
9985OMPClause *
9986TreeTransform<Derived>::TransformOMPMessageClause(OMPMessageClause *C) {
9987 ExprResult E = getDerived().TransformExpr(C->getMessageString());
9988 if (E.isInvalid())
9989 return nullptr;
9990 return getDerived().RebuildOMPMessageClause(
9991 C->getMessageString(), C->getBeginLoc(), C->getLParenLoc(),
9992 C->getEndLoc());
9993}
9994
9995template <typename Derived>
9996OMPClause *
9997TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
9998 llvm::SmallVector<Expr *, 16> Vars;
9999 Vars.reserve(C->varlist_size());
10000 for (auto *VE : C->varlists()) {
10001 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10002 if (EVar.isInvalid())
10003 return nullptr;
10004 Vars.push_back(EVar.get());
10005 }
10006 return getDerived().RebuildOMPPrivateClause(
10007 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10008}
10009
10010template <typename Derived>
10011OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
10012 OMPFirstprivateClause *C) {
10013 llvm::SmallVector<Expr *, 16> Vars;
10014 Vars.reserve(C->varlist_size());
10015 for (auto *VE : C->varlists()) {
10016 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10017 if (EVar.isInvalid())
10018 return nullptr;
10019 Vars.push_back(EVar.get());
10020 }
10021 return getDerived().RebuildOMPFirstprivateClause(
10022 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10023}
10024
10025template <typename Derived>
10026OMPClause *
10027TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
10028 llvm::SmallVector<Expr *, 16> Vars;
10029 Vars.reserve(C->varlist_size());
10030 for (auto *VE : C->varlists()) {
10031 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10032 if (EVar.isInvalid())
10033 return nullptr;
10034 Vars.push_back(EVar.get());
10035 }
10036 return getDerived().RebuildOMPLastprivateClause(
10037 Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
10038 C->getLParenLoc(), C->getEndLoc());
10039}
10040
10041template <typename Derived>
10042OMPClause *
10043TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
10044 llvm::SmallVector<Expr *, 16> Vars;
10045 Vars.reserve(C->varlist_size());
10046 for (auto *VE : C->varlists()) {
10047 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10048 if (EVar.isInvalid())
10049 return nullptr;
10050 Vars.push_back(EVar.get());
10051 }
10052 return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
10053 C->getLParenLoc(), C->getEndLoc());
10054}
10055
10056template <typename Derived>
10057OMPClause *
10058TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
10059 llvm::SmallVector<Expr *, 16> Vars;
10060 Vars.reserve(C->varlist_size());
10061 for (auto *VE : C->varlists()) {
10062 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10063 if (EVar.isInvalid())
10064 return nullptr;
10065 Vars.push_back(EVar.get());
10066 }
10067 CXXScopeSpec ReductionIdScopeSpec;
10068 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10069
10070 DeclarationNameInfo NameInfo = C->getNameInfo();
10071 if (NameInfo.getName()) {
10072 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10073 if (!NameInfo.getName())
10074 return nullptr;
10075 }
10076 // Build a list of all UDR decls with the same names ranged by the Scopes.
10077 // The Scope boundary is a duplication of the previous decl.
10078 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10079 for (auto *E : C->reduction_ops()) {
10080 // Transform all the decls.
10081 if (E) {
10082 auto *ULE = cast<UnresolvedLookupExpr>(E);
10083 UnresolvedSet<8> Decls;
10084 for (auto *D : ULE->decls()) {
10085 NamedDecl *InstD =
10086 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10087 Decls.addDecl(InstD, InstD->getAccess());
10088 }
10089 UnresolvedReductions.push_back(
10090 UnresolvedLookupExpr::Create(
10091 SemaRef.Context, /*NamingClass=*/nullptr,
10092 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
10093 NameInfo, /*ADL=*/true, ULE->isOverloaded(),
10094 Decls.begin(), Decls.end()));
10095 } else
10096 UnresolvedReductions.push_back(nullptr);
10097 }
10098 return getDerived().RebuildOMPReductionClause(
10099 Vars, C->getModifier(), C->getBeginLoc(), C->getLParenLoc(),
10100 C->getModifierLoc(), C->getColonLoc(), C->getEndLoc(),
10101 ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10102}
10103
10104template <typename Derived>
10105OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
10106 OMPTaskReductionClause *C) {
10107 llvm::SmallVector<Expr *, 16> Vars;
10108 Vars.reserve(C->varlist_size());
10109 for (auto *VE : C->varlists()) {
10110 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10111 if (EVar.isInvalid())
10112 return nullptr;
10113 Vars.push_back(EVar.get());
10114 }
10115 CXXScopeSpec ReductionIdScopeSpec;
10116 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10117
10118 DeclarationNameInfo NameInfo = C->getNameInfo();
10119 if (NameInfo.getName()) {
10120 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10121 if (!NameInfo.getName())
10122 return nullptr;
10123 }
10124 // Build a list of all UDR decls with the same names ranged by the Scopes.
10125 // The Scope boundary is a duplication of the previous decl.
10126 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10127 for (auto *E : C->reduction_ops()) {
10128 // Transform all the decls.
10129 if (E) {
10130 auto *ULE = cast<UnresolvedLookupExpr>(E);
10131 UnresolvedSet<8> Decls;
10132 for (auto *D : ULE->decls()) {
10133 NamedDecl *InstD =
10134 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10135 Decls.addDecl(InstD, InstD->getAccess());
10136 }
10137 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10138 SemaRef.Context, /*NamingClass=*/nullptr,
10139 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10140 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10141 } else
10142 UnresolvedReductions.push_back(nullptr);
10143 }
10144 return getDerived().RebuildOMPTaskReductionClause(
10145 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10146 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10147}
10148
10149template <typename Derived>
10150OMPClause *
10151TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
10152 llvm::SmallVector<Expr *, 16> Vars;
10153 Vars.reserve(C->varlist_size());
10154 for (auto *VE : C->varlists()) {
10155 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10156 if (EVar.isInvalid())
10157 return nullptr;
10158 Vars.push_back(EVar.get());
10159 }
10160 CXXScopeSpec ReductionIdScopeSpec;
10161 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10162
10163 DeclarationNameInfo NameInfo = C->getNameInfo();
10164 if (NameInfo.getName()) {
10165 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10166 if (!NameInfo.getName())
10167 return nullptr;
10168 }
10169 // Build a list of all UDR decls with the same names ranged by the Scopes.
10170 // The Scope boundary is a duplication of the previous decl.
10171 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10172 for (auto *E : C->reduction_ops()) {
10173 // Transform all the decls.
10174 if (E) {
10175 auto *ULE = cast<UnresolvedLookupExpr>(E);
10176 UnresolvedSet<8> Decls;
10177 for (auto *D : ULE->decls()) {
10178 NamedDecl *InstD =
10179 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10180 Decls.addDecl(InstD, InstD->getAccess());
10181 }
10182 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10183 SemaRef.Context, /*NamingClass=*/nullptr,
10184 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10185 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10186 } else
10187 UnresolvedReductions.push_back(nullptr);
10188 }
10189 return getDerived().RebuildOMPInReductionClause(
10190 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10191 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10192}
10193
10194template <typename Derived>
10195OMPClause *
10196TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
10197 llvm::SmallVector<Expr *, 16> Vars;
10198 Vars.reserve(C->varlist_size());
10199 for (auto *VE : C->varlists()) {
10200 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10201 if (EVar.isInvalid())
10202 return nullptr;
10203 Vars.push_back(EVar.get());
10204 }
10205 ExprResult Step = getDerived().TransformExpr(C->getStep());
10206 if (Step.isInvalid())
10207 return nullptr;
10208 return getDerived().RebuildOMPLinearClause(
10209 Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
10210 C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
10211}
10212
10213template <typename Derived>
10214OMPClause *
10215TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
10216 llvm::SmallVector<Expr *, 16> Vars;
10217 Vars.reserve(C->varlist_size());
10218 for (auto *VE : C->varlists()) {
10219 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10220 if (EVar.isInvalid())
10221 return nullptr;
10222 Vars.push_back(EVar.get());
10223 }
10224 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
10225 if (Alignment.isInvalid())
10226 return nullptr;
10227 return getDerived().RebuildOMPAlignedClause(
10228 Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
10229 C->getColonLoc(), C->getEndLoc());
10230}
10231
10232template <typename Derived>
10233OMPClause *
10234TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
10235 llvm::SmallVector<Expr *, 16> Vars;
10236 Vars.reserve(C->varlist_size());
10237 for (auto *VE : C->varlists()) {
10238 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10239 if (EVar.isInvalid())
10240 return nullptr;
10241 Vars.push_back(EVar.get());
10242 }
10243 return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
10244 C->getLParenLoc(), C->getEndLoc());
10245}
10246
10247template <typename Derived>
10248OMPClause *
10249TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
10250 llvm::SmallVector<Expr *, 16> Vars;
10251 Vars.reserve(C->varlist_size());
10252 for (auto *VE : C->varlists()) {
10253 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10254 if (EVar.isInvalid())
10255 return nullptr;
10256 Vars.push_back(EVar.get());
10257 }
10258 return getDerived().RebuildOMPCopyprivateClause(
10259 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10260}
10261
10262template <typename Derived>
10263OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
10264 llvm::SmallVector<Expr *, 16> Vars;
10265 Vars.reserve(C->varlist_size());
10266 for (auto *VE : C->varlists()) {
10267 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10268 if (EVar.isInvalid())
10269 return nullptr;
10270 Vars.push_back(EVar.get());
10271 }
10272 return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
10273 C->getLParenLoc(), C->getEndLoc());
10274}
10275
10276template <typename Derived>
10277OMPClause *
10278TreeTransform<Derived>::TransformOMPDepobjClause(OMPDepobjClause *C) {
10279 ExprResult E = getDerived().TransformExpr(C->getDepobj());
10280 if (E.isInvalid())
10281 return nullptr;
10282 return getDerived().RebuildOMPDepobjClause(E.get(), C->getBeginLoc(),
10283 C->getLParenLoc(), C->getEndLoc());
10284}
10285
10286template <typename Derived>
10287OMPClause *
10288TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
10289 llvm::SmallVector<Expr *, 16> Vars;
10290 Expr *DepModifier = C->getModifier();
10291 if (DepModifier) {
10292 ExprResult DepModRes = getDerived().TransformExpr(DepModifier);
10293 if (DepModRes.isInvalid())
10294 return nullptr;
10295 DepModifier = DepModRes.get();
10296 }
10297 Vars.reserve(C->varlist_size());
10298 for (auto *VE : C->varlists()) {
10299 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10300 if (EVar.isInvalid())
10301 return nullptr;
10302 Vars.push_back(EVar.get());
10303 }
10304 return getDerived().RebuildOMPDependClause(
10305 {C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(),
10306 C->getOmpAllMemoryLoc()},
10307 DepModifier, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10308}
10309
10310template <typename Derived>
10311OMPClause *
10312TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
10313 ExprResult E = getDerived().TransformExpr(C->getDevice());
10314 if (E.isInvalid())
10315 return nullptr;
10316 return getDerived().RebuildOMPDeviceClause(
10317 C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10318 C->getModifierLoc(), C->getEndLoc());
10319}
10320
10321template <typename Derived, class T>
10322bool transformOMPMappableExprListClause(
10323 TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
10324 llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
10325 DeclarationNameInfo &MapperIdInfo,
10326 llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
10327 // Transform expressions in the list.
10328 Vars.reserve(C->varlist_size());
10329 for (auto *VE : C->varlists()) {
10330 ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
10331 if (EVar.isInvalid())
10332 return true;
10333 Vars.push_back(EVar.get());
10334 }
10335 // Transform mapper scope specifier and identifier.
10336 NestedNameSpecifierLoc QualifierLoc;
10337 if (C->getMapperQualifierLoc()) {
10338 QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
10339 C->getMapperQualifierLoc());
10340 if (!QualifierLoc)
10341 return true;
10342 }
10343 MapperIdScopeSpec.Adopt(QualifierLoc);
10344 MapperIdInfo = C->getMapperIdInfo();
10345 if (MapperIdInfo.getName()) {
10346 MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
10347 if (!MapperIdInfo.getName())
10348 return true;
10349 }
10350 // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
10351 // the previous user-defined mapper lookup in dependent environment.
10352 for (auto *E : C->mapperlists()) {
10353 // Transform all the decls.
10354 if (E) {
10355 auto *ULE = cast<UnresolvedLookupExpr>(E);
10356 UnresolvedSet<8> Decls;
10357 for (auto *D : ULE->decls()) {
10358 NamedDecl *InstD =
10359 cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
10360 Decls.addDecl(InstD, InstD->getAccess());
10361 }
10362 UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
10363 TT.getSema().Context, /*NamingClass=*/nullptr,
10364 MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
10365 MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
10366 Decls.end()));
10367 } else {
10368 UnresolvedMappers.push_back(nullptr);
10369 }
10370 }
10371 return false;
10372}
10373
10374template <typename Derived>
10375OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
10376 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10377 llvm::SmallVector<Expr *, 16> Vars;
10378 Expr *IteratorModifier = C->getIteratorModifier();
10379 if (IteratorModifier) {
10380 ExprResult MapModRes = getDerived().TransformExpr(IteratorModifier);
10381 if (MapModRes.isInvalid())
10382 return nullptr;
10383 IteratorModifier = MapModRes.get();
10384 }
10385 CXXScopeSpec MapperIdScopeSpec;
10386 DeclarationNameInfo MapperIdInfo;
10387 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10388 if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
10389 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10390 return nullptr;
10391 return getDerived().RebuildOMPMapClause(
10392 IteratorModifier, C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
10393 MapperIdScopeSpec, MapperIdInfo, C->getMapType(), C->isImplicitMapType(),
10394 C->getMapLoc(), C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10395}
10396
10397template <typename Derived>
10398OMPClause *
10399TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
10400 Expr *Allocator = C->getAllocator();
10401 if (Allocator) {
10402 ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
10403 if (AllocatorRes.isInvalid())
10404 return nullptr;
10405 Allocator = AllocatorRes.get();
10406 }
10407 llvm::SmallVector<Expr *, 16> Vars;
10408 Vars.reserve(C->varlist_size());
10409 for (auto *VE : C->varlists()) {
10410 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10411 if (EVar.isInvalid())
10412 return nullptr;
10413 Vars.push_back(EVar.get());
10414 }
10415 return getDerived().RebuildOMPAllocateClause(
10416 Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10417 C->getEndLoc());
10418}
10419
10420template <typename Derived>
10421OMPClause *
10422TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
10423 ExprResult E = getDerived().TransformExpr(C->getNumTeams());
10424 if (E.isInvalid())
10425 return nullptr;
10426 return getDerived().RebuildOMPNumTeamsClause(
10427 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10428}
10429
10430template <typename Derived>
10431OMPClause *
10432TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
10433 ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
10434 if (E.isInvalid())
10435 return nullptr;
10436 return getDerived().RebuildOMPThreadLimitClause(
10437 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10438}
10439
10440template <typename Derived>
10441OMPClause *
10442TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
10443 ExprResult E = getDerived().TransformExpr(C->getPriority());
10444 if (E.isInvalid())
10445 return nullptr;
10446 return getDerived().RebuildOMPPriorityClause(
10447 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10448}
10449
10450template <typename Derived>
10451OMPClause *
10452TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
10453 ExprResult E = getDerived().TransformExpr(C->getGrainsize());
10454 if (E.isInvalid())
10455 return nullptr;
10456 return getDerived().RebuildOMPGrainsizeClause(
10457 C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10458 C->getModifierLoc(), C->getEndLoc());
10459}
10460
10461template <typename Derived>
10462OMPClause *
10463TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
10464 ExprResult E = getDerived().TransformExpr(C->getNumTasks());
10465 if (E.isInvalid())
10466 return nullptr;
10467 return getDerived().RebuildOMPNumTasksClause(
10468 C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10469 C->getModifierLoc(), C->getEndLoc());
10470}
10471
10472template <typename Derived>
10473OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
10474 ExprResult E = getDerived().TransformExpr(C->getHint());
10475 if (E.isInvalid())
10476 return nullptr;
10477 return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
10478 C->getLParenLoc(), C->getEndLoc());
10479}
10480
10481template <typename Derived>
10482OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
10483 OMPDistScheduleClause *C) {
10484 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
10485 if (E.isInvalid())
10486 return nullptr;
10487 return getDerived().RebuildOMPDistScheduleClause(
10488 C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10489 C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
10490}
10491
10492template <typename Derived>
10493OMPClause *
10494TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
10495 // Rebuild Defaultmap Clause since we need to invoke the checking of
10496 // defaultmap(none:variable-category) after template initialization.
10497 return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
10498 C->getDefaultmapKind(),
10499 C->getBeginLoc(),
10500 C->getLParenLoc(),
10501 C->getDefaultmapModifierLoc(),
10502 C->getDefaultmapKindLoc(),
10503 C->getEndLoc());
10504}
10505
10506template <typename Derived>
10507OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
10508 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10509 llvm::SmallVector<Expr *, 16> Vars;
10510 CXXScopeSpec MapperIdScopeSpec;
10511 DeclarationNameInfo MapperIdInfo;
10512 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10513 if (transformOMPMappableExprListClause<Derived, OMPToClause>(
10514 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10515 return nullptr;
10516 return getDerived().RebuildOMPToClause(
10517 C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10518 MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10519}
10520
10521template <typename Derived>
10522OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
10523 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10524 llvm::SmallVector<Expr *, 16> Vars;
10525 CXXScopeSpec MapperIdScopeSpec;
10526 DeclarationNameInfo MapperIdInfo;
10527 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10528 if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
10529 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10530 return nullptr;
10531 return getDerived().RebuildOMPFromClause(
10532 C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10533 MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10534}
10535
10536template <typename Derived>
10537OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
10538 OMPUseDevicePtrClause *C) {
10539 llvm::SmallVector<Expr *, 16> Vars;
10540 Vars.reserve(C->varlist_size());
10541 for (auto *VE : C->varlists()) {
10542 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10543 if (EVar.isInvalid())
10544 return nullptr;
10545 Vars.push_back(EVar.get());
10546 }
10547 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10548 return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
10549}
10550
10551template <typename Derived>
10552OMPClause *TreeTransform<Derived>::TransformOMPUseDeviceAddrClause(
10553 OMPUseDeviceAddrClause *C) {
10554 llvm::SmallVector<Expr *, 16> Vars;
10555 Vars.reserve(C->varlist_size());
10556 for (auto *VE : C->varlists()) {
10557 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10558 if (EVar.isInvalid())
10559 return nullptr;
10560 Vars.push_back(EVar.get());
10561 }
10562 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10563 return getDerived().RebuildOMPUseDeviceAddrClause(Vars, Locs);
10564}
10565
10566template <typename Derived>
10567OMPClause *
10568TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
10569 llvm::SmallVector<Expr *, 16> Vars;
10570 Vars.reserve(C->varlist_size());
10571 for (auto *VE : C->varlists()) {
10572 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10573 if (EVar.isInvalid())
10574 return nullptr;
10575 Vars.push_back(EVar.get());
10576 }
10577 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10578 return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
10579}
10580
10581template <typename Derived>
10582OMPClause *TreeTransform<Derived>::TransformOMPHasDeviceAddrClause(
10583 OMPHasDeviceAddrClause *C) {
10584 llvm::SmallVector<Expr *, 16> Vars;
10585 Vars.reserve(C->varlist_size());
10586 for (auto *VE : C->varlists()) {
10587 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10588 if (EVar.isInvalid())
10589 return nullptr;
10590 Vars.push_back(EVar.get());
10591 }
10592 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10593 return getDerived().RebuildOMPHasDeviceAddrClause(Vars, Locs);
10594}
10595
10596template <typename Derived>
10597OMPClause *
10598TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
10599 llvm::SmallVector<Expr *, 16> Vars;
10600 Vars.reserve(C->varlist_size());
10601 for (auto *VE : C->varlists()) {
10602 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10603 if (EVar.isInvalid())
10604 return nullptr;
10605 Vars.push_back(EVar.get());
10606 }
10607 return getDerived().RebuildOMPNontemporalClause(
10608 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10609}
10610
10611template <typename Derived>
10612OMPClause *
10613TreeTransform<Derived>::TransformOMPInclusiveClause(OMPInclusiveClause *C) {
10614 llvm::SmallVector<Expr *, 16> Vars;
10615 Vars.reserve(C->varlist_size());
10616 for (auto *VE : C->varlists()) {
10617 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10618 if (EVar.isInvalid())
10619 return nullptr;
10620 Vars.push_back(EVar.get());
10621 }
10622 return getDerived().RebuildOMPInclusiveClause(
10623 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10624}
10625
10626template <typename Derived>
10627OMPClause *
10628TreeTransform<Derived>::TransformOMPExclusiveClause(OMPExclusiveClause *C) {
10629 llvm::SmallVector<Expr *, 16> Vars;
10630 Vars.reserve(C->varlist_size());
10631 for (auto *VE : C->varlists()) {
10632 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10633 if (EVar.isInvalid())
10634 return nullptr;
10635 Vars.push_back(EVar.get());
10636 }
10637 return getDerived().RebuildOMPExclusiveClause(
10638 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10639}
10640
10641template <typename Derived>
10642OMPClause *TreeTransform<Derived>::TransformOMPUsesAllocatorsClause(
10643 OMPUsesAllocatorsClause *C) {
10644 SmallVector<Sema::UsesAllocatorsData, 16> Data;
10645 Data.reserve(C->getNumberOfAllocators());
10646 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
10647 OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
10648 ExprResult Allocator = getDerived().TransformExpr(D.Allocator);
10649 if (Allocator.isInvalid())
10650 continue;
10651 ExprResult AllocatorTraits;
10652 if (Expr *AT = D.AllocatorTraits) {
10653 AllocatorTraits = getDerived().TransformExpr(AT);
10654 if (AllocatorTraits.isInvalid())
10655 continue;
10656 }
10657 Sema::UsesAllocatorsData &NewD = Data.emplace_back();
10658 NewD.Allocator = Allocator.get();
10659 NewD.AllocatorTraits = AllocatorTraits.get();
10660 NewD.LParenLoc = D.LParenLoc;
10661 NewD.RParenLoc = D.RParenLoc;
10662 }
10663 return getDerived().RebuildOMPUsesAllocatorsClause(
10664 Data, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10665}
10666
10667template <typename Derived>
10668OMPClause *
10669TreeTransform<Derived>::TransformOMPAffinityClause(OMPAffinityClause *C) {
10670 SmallVector<Expr *, 4> Locators;
10671 Locators.reserve(C->varlist_size());
10672 ExprResult ModifierRes;
10673 if (Expr *Modifier = C->getModifier()) {
10674 ModifierRes = getDerived().TransformExpr(Modifier);
10675 if (ModifierRes.isInvalid())
10676 return nullptr;
10677 }
10678 for (Expr *E : C->varlists()) {
10679 ExprResult Locator = getDerived().TransformExpr(E);
10680 if (Locator.isInvalid())
10681 continue;
10682 Locators.push_back(Locator.get());
10683 }
10684 return getDerived().RebuildOMPAffinityClause(
10685 C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(), C->getEndLoc(),
10686 ModifierRes.get(), Locators);
10687}
10688
10689template <typename Derived>
10690OMPClause *TreeTransform<Derived>::TransformOMPOrderClause(OMPOrderClause *C) {
10691 return getDerived().RebuildOMPOrderClause(
10692 C->getKind(), C->getKindKwLoc(), C->getBeginLoc(), C->getLParenLoc(),
10693 C->getEndLoc(), C->getModifier(), C->getModifierKwLoc());
10694}
10695
10696template <typename Derived>
10697OMPClause *TreeTransform<Derived>::TransformOMPBindClause(OMPBindClause *C) {
10698 return getDerived().RebuildOMPBindClause(
10699 C->getBindKind(), C->getBindKindLoc(), C->getBeginLoc(),
10700 C->getLParenLoc(), C->getEndLoc());
10701}
10702
10703template <typename Derived>
10704OMPClause *TreeTransform<Derived>::TransformOMPXDynCGroupMemClause(
10705 OMPXDynCGroupMemClause *C) {
10706 ExprResult Size = getDerived().TransformExpr(C->getSize());
10707 if (Size.isInvalid())
10708 return nullptr;
10709 return getDerived().RebuildOMPXDynCGroupMemClause(
10710 Size.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10711}
10712
10713//===----------------------------------------------------------------------===//
10714// Expression transformation
10715//===----------------------------------------------------------------------===//
10716template<typename Derived>
10717ExprResult
10718TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
10719 return TransformExpr(E->getSubExpr());
10720}
10721
10722template <typename Derived>
10723ExprResult TreeTransform<Derived>::TransformSYCLUniqueStableNameExpr(
10724 SYCLUniqueStableNameExpr *E) {
10725 if (!E->isTypeDependent())
10726 return E;
10727
10728 TypeSourceInfo *NewT = getDerived().TransformType(E->getTypeSourceInfo());
10729
10730 if (!NewT)
10731 return ExprError();
10732
10733 if (!getDerived().AlwaysRebuild() && E->getTypeSourceInfo() == NewT)
10734 return E;
10735
10736 return getDerived().RebuildSYCLUniqueStableNameExpr(
10737 E->getLocation(), E->getLParenLocation(), E->getRParenLocation(), NewT);
10738}
10739
10740template<typename Derived>
10741ExprResult
10742TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
10743 if (!E->isTypeDependent())
10744 return E;
10745
10746 return getDerived().RebuildPredefinedExpr(E->getLocation(),
10747 E->getIdentKind());
10748}
10749
10750template<typename Derived>
10751ExprResult
10752TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
10753 NestedNameSpecifierLoc QualifierLoc;
10754 if (E->getQualifierLoc()) {
10755 QualifierLoc
10756 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10757 if (!QualifierLoc)
10758 return ExprError();
10759 }
10760
10761 ValueDecl *ND
10762 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
10763 E->getDecl()));
10764 if (!ND)
10765 return ExprError();
10766
10767 NamedDecl *Found = ND;
10768 if (E->getFoundDecl() != E->getDecl()) {
10769 Found = cast_or_null<NamedDecl>(
10770 getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
10771 if (!Found)
10772 return ExprError();
10773 }
10774
10775 DeclarationNameInfo NameInfo = E->getNameInfo();
10776 if (NameInfo.getName()) {
10777 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10778 if (!NameInfo.getName())
10779 return ExprError();
10780 }
10781
10782 if (!getDerived().AlwaysRebuild() &&
10783 QualifierLoc == E->getQualifierLoc() &&
10784 ND == E->getDecl() &&
10785 Found == E->getFoundDecl() &&
10786 NameInfo.getName() == E->getDecl()->getDeclName() &&
10787 !E->hasExplicitTemplateArgs()) {
10788
10789 // Mark it referenced in the new context regardless.
10790 // FIXME: this is a bit instantiation-specific.
10791 SemaRef.MarkDeclRefReferenced(E);
10792
10793 return E;
10794 }
10795
10796 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
10797 if (E->hasExplicitTemplateArgs()) {
10798 TemplateArgs = &TransArgs;
10799 TransArgs.setLAngleLoc(E->getLAngleLoc());
10800 TransArgs.setRAngleLoc(E->getRAngleLoc());
10801 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10802 E->getNumTemplateArgs(),
10803 TransArgs))
10804 return ExprError();
10805 }
10806
10807 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
10808 Found, TemplateArgs);
10809}
10810
10811template<typename Derived>
10812ExprResult
10813TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
10814 return E;
10815}
10816
10817template <typename Derived>
10818ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
10819 FixedPointLiteral *E) {
10820 return E;
10821}
10822
10823template<typename Derived>
10824ExprResult
10825TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
10826 return E;
10827}
10828
10829template<typename Derived>
10830ExprResult
10831TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
10832 return E;
10833}
10834
10835template<typename Derived>
10836ExprResult
10837TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
10838 return E;
10839}
10840
10841template<typename Derived>
10842ExprResult
10843TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
10844 return E;
10845}
10846
10847template<typename Derived>
10848ExprResult
10849TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
10850 return getDerived().TransformCallExpr(E);
10851}
10852
10853template<typename Derived>
10854ExprResult
10855TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
10856 ExprResult ControllingExpr =
10857 getDerived().TransformExpr(E->getControllingExpr());
10858 if (ControllingExpr.isInvalid())
10859 return ExprError();
10860
10861 SmallVector<Expr *, 4> AssocExprs;
10862 SmallVector<TypeSourceInfo *, 4> AssocTypes;
10863 for (const GenericSelectionExpr::Association Assoc : E->associations()) {
10864 TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
10865 if (TSI) {
10866 TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
10867 if (!AssocType)
10868 return ExprError();
10869 AssocTypes.push_back(AssocType);
10870 } else {
10871 AssocTypes.push_back(nullptr);
10872 }
10873
10874 ExprResult AssocExpr =
10875 getDerived().TransformExpr(Assoc.getAssociationExpr());
10876 if (AssocExpr.isInvalid())
10877 return ExprError();
10878 AssocExprs.push_back(AssocExpr.get());
10879 }
10880
10881 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
10882 E->getDefaultLoc(),
10883 E->getRParenLoc(),
10884 ControllingExpr.get(),
10885 AssocTypes,
10886 AssocExprs);
10887}
10888
10889template<typename Derived>
10890ExprResult
10891TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
10892 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10893 if (SubExpr.isInvalid())
10894 return ExprError();
10895
10896 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10897 return E;
10898
10899 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
10900 E->getRParen());
10901}
10902
10903/// The operand of a unary address-of operator has special rules: it's
10904/// allowed to refer to a non-static member of a class even if there's no 'this'
10905/// object available.
10906template<typename Derived>
10907ExprResult
10908TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
10909 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
10910 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
10911 else
10912 return getDerived().TransformExpr(E);
10913}
10914
10915template<typename Derived>
10916ExprResult
10917TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
10918 ExprResult SubExpr;
10919 if (E->getOpcode() == UO_AddrOf)
10920 SubExpr = TransformAddressOfOperand(E->getSubExpr());
10921 else
10922 SubExpr = TransformExpr(E->getSubExpr());
10923 if (SubExpr.isInvalid())
10924 return ExprError();
10925
10926 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10927 return E;
10928
10929 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
10930 E->getOpcode(),
10931 SubExpr.get());
10932}
10933
10934template<typename Derived>
10935ExprResult
10936TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
10937 // Transform the type.
10938 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10939 if (!Type)
10940 return ExprError();
10941
10942 // Transform all of the components into components similar to what the
10943 // parser uses.
10944 // FIXME: It would be slightly more efficient in the non-dependent case to
10945 // just map FieldDecls, rather than requiring the rebuilder to look for
10946 // the fields again. However, __builtin_offsetof is rare enough in
10947 // template code that we don't care.
10948 bool ExprChanged = false;
10949 typedef Sema::OffsetOfComponent Component;
10950 SmallVector<Component, 4> Components;
10951 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
10952 const OffsetOfNode &ON = E->getComponent(I);
10953 Component Comp;
10954 Comp.isBrackets = true;
10955 Comp.LocStart = ON.getSourceRange().getBegin();
10956 Comp.LocEnd = ON.getSourceRange().getEnd();
10957 switch (ON.getKind()) {
10958 case OffsetOfNode::Array: {
10959 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
10960 ExprResult Index = getDerived().TransformExpr(FromIndex);
10961 if (Index.isInvalid())
10962 return ExprError();
10963
10964 ExprChanged = ExprChanged || Index.get() != FromIndex;
10965 Comp.isBrackets = true;
10966 Comp.U.E = Index.get();
10967 break;
10968 }
10969
10970 case OffsetOfNode::Field:
10971 case OffsetOfNode::Identifier:
10972 Comp.isBrackets = false;
10973 Comp.U.IdentInfo = ON.getFieldName();
10974 if (!Comp.U.IdentInfo)
10975 continue;
10976
10977 break;
10978
10979 case OffsetOfNode::Base:
10980 // Will be recomputed during the rebuild.
10981 continue;
10982 }
10983
10984 Components.push_back(Comp);
10985 }
10986
10987 // If nothing changed, retain the existing expression.
10988 if (!getDerived().AlwaysRebuild() &&
10989 Type == E->getTypeSourceInfo() &&
10990 !ExprChanged)
10991 return E;
10992
10993 // Build a new offsetof expression.
10994 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
10995 Components, E->getRParenLoc());
10996}
10997
10998template<typename Derived>
10999ExprResult
11000TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
11001 assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&(static_cast <bool> ((!E->getSourceExpr() || getDerived
().AlreadyTransformed(E->getType())) && "opaque value expression requires transformation"
) ? void (0) : __assert_fail ("(!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) && \"opaque value expression requires transformation\""
, "clang/lib/Sema/TreeTransform.h", 11002, __extension__ __PRETTY_FUNCTION__
))
11002 "opaque value expression requires transformation")(static_cast <bool> ((!E->getSourceExpr() || getDerived
().AlreadyTransformed(E->getType())) && "opaque value expression requires transformation"
) ? void (0) : __assert_fail ("(!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) && \"opaque value expression requires transformation\""
, "clang/lib/Sema/TreeTransform.h", 11002, __extension__ __PRETTY_FUNCTION__
))
;
11003 return E;
11004}
11005
11006template<typename Derived>
11007ExprResult
11008TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
11009 return E;
11010}
11011
11012template <typename Derived>
11013ExprResult TreeTransform<Derived>::TransformRecoveryExpr(RecoveryExpr *E) {
11014 llvm::SmallVector<Expr *, 8> Children;
11015 bool Changed = false;
11016 for (Expr *C : E->subExpressions()) {
11017 ExprResult NewC = getDerived().TransformExpr(C);
11018 if (NewC.isInvalid())
11019 return ExprError();
11020 Children.push_back(NewC.get());
11021
11022 Changed |= NewC.get() != C;
11023 }
11024 if (!getDerived().AlwaysRebuild() && !Changed)
11025 return E;
11026 return getDerived().RebuildRecoveryExpr(E->getBeginLoc(), E->getEndLoc(),
11027 Children, E->getType());
11028}
11029
11030template<typename Derived>
11031ExprResult
11032TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
11033 // Rebuild the syntactic form. The original syntactic form has
11034 // opaque-value expressions in it, so strip those away and rebuild
11035 // the result. This is a really awful way of doing this, but the
11036 // better solution (rebuilding the semantic expressions and
11037 // rebinding OVEs as necessary) doesn't work; we'd need
11038 // TreeTransform to not strip away implicit conversions.
11039 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
11040 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
11041 if (result.isInvalid()) return ExprError();
11042
11043 // If that gives us a pseudo-object result back, the pseudo-object
11044 // expression must have been an lvalue-to-rvalue conversion which we
11045 // should reapply.
11046 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
11047 result = SemaRef.checkPseudoObjectRValue(result.get());
11048
11049 return result;
11050}
11051
11052template<typename Derived>
11053ExprResult
11054TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
11055 UnaryExprOrTypeTraitExpr *E) {
11056 if (E->isArgumentType()) {
11057 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
11058
11059 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11060 if (!NewT)
11061 return ExprError();
11062
11063 if (!getDerived().AlwaysRebuild() && OldT == NewT)
11064 return E;
11065
11066 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
11067 E->getKind(),
11068 E->getSourceRange());
11069 }
11070
11071 // C++0x [expr.sizeof]p1:
11072 // The operand is either an expression, which is an unevaluated operand
11073 // [...]
11074 EnterExpressionEvaluationContext Unevaluated(
11075 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
11076 Sema::ReuseLambdaContextDecl);
11077
11078 // Try to recover if we have something like sizeof(T::X) where X is a type.
11079 // Notably, there must be *exactly* one set of parens if X is a type.
11080 TypeSourceInfo *RecoveryTSI = nullptr;
11081 ExprResult SubExpr;
11082 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
11083 if (auto *DRE =
11084 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
11085 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
11086 PE, DRE, false, &RecoveryTSI);
11087 else
11088 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
11089
11090 if (RecoveryTSI) {
11091 return getDerived().RebuildUnaryExprOrTypeTrait(
11092 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
11093 } else if (SubExpr.isInvalid())
11094 return ExprError();
11095
11096 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
11097 return E;
11098
11099 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
11100 E->getOperatorLoc(),
11101 E->getKind(),
11102 E->getSourceRange());
11103}
11104
11105template<typename Derived>
11106ExprResult
11107TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
11108 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11109 if (LHS.isInvalid())
11110 return ExprError();
11111
11112 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11113 if (RHS.isInvalid())
11114 return ExprError();
11115
11116
11117 if (!getDerived().AlwaysRebuild() &&
11118 LHS.get() == E->getLHS() &&
11119 RHS.get() == E->getRHS())
11120 return E;
11121
11122 return getDerived().RebuildArraySubscriptExpr(
11123 LHS.get(),
11124 /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
11125}
11126
11127template <typename Derived>
11128ExprResult
11129TreeTransform<Derived>::TransformMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
11130 ExprResult Base = getDerived().TransformExpr(E->getBase());
11131 if (Base.isInvalid())
11132 return ExprError();
11133
11134 ExprResult RowIdx = getDerived().TransformExpr(E->getRowIdx());
11135 if (RowIdx.isInvalid())
11136 return ExprError();
11137
11138 ExprResult ColumnIdx = getDerived().TransformExpr(E->getColumnIdx());
11139 if (ColumnIdx.isInvalid())
11140 return ExprError();
11141
11142 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11143 RowIdx.get() == E->getRowIdx() && ColumnIdx.get() == E->getColumnIdx())
11144 return E;
11145
11146 return getDerived().RebuildMatrixSubscriptExpr(
11147 Base.get(), RowIdx.get(), ColumnIdx.get(), E->getRBracketLoc());
11148}
11149
11150template <typename Derived>
11151ExprResult
11152TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
11153 ExprResult Base = getDerived().TransformExpr(E->getBase());
11154 if (Base.isInvalid())
11155 return ExprError();
11156
11157 ExprResult LowerBound;
11158 if (E->getLowerBound()) {
11159 LowerBound = getDerived().TransformExpr(E->getLowerBound());
11160 if (LowerBound.isInvalid())
11161 return ExprError();
11162 }
11163
11164 ExprResult Length;
11165 if (E->getLength()) {
11166 Length = getDerived().TransformExpr(E->getLength());
11167 if (Length.isInvalid())
11168 return ExprError();
11169 }
11170
11171 ExprResult Stride;
11172 if (Expr *Str = E->getStride()) {
11173 Stride = getDerived().TransformExpr(Str);
11174 if (Stride.isInvalid())
11175 return ExprError();
11176 }
11177
11178 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11179 LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
11180 return E;
11181
11182 return getDerived().RebuildOMPArraySectionExpr(
11183 Base.get(), E->getBase()->getEndLoc(), LowerBound.get(),
11184 E->getColonLocFirst(), E->getColonLocSecond(), Length.get(), Stride.get(),
11185 E->getRBracketLoc());
11186}
11187
11188template <typename Derived>
11189ExprResult
11190TreeTransform<Derived>::TransformOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
11191 ExprResult Base = getDerived().TransformExpr(E->getBase());
11192 if (Base.isInvalid())
11193 return ExprError();
11194
11195 SmallVector<Expr *, 4> Dims;
11196 bool ErrorFound = false;
11197 for (Expr *Dim : E->getDimensions()) {
11198 ExprResult DimRes = getDerived().TransformExpr(Dim);
11199 if (DimRes.isInvalid()) {
11200 ErrorFound = true;
11201 continue;
11202 }
11203 Dims.push_back(DimRes.get());
11204 }
11205
11206 if (ErrorFound)
11207 return ExprError();
11208 return getDerived().RebuildOMPArrayShapingExpr(Base.get(), E->getLParenLoc(),
11209 E->getRParenLoc(), Dims,
11210 E->getBracketsRanges());
11211}
11212
11213template <typename Derived>
11214ExprResult
11215TreeTransform<Derived>::TransformOMPIteratorExpr(OMPIteratorExpr *E) {
11216 unsigned NumIterators = E->numOfIterators();
11217 SmallVector<Sema::OMPIteratorData, 4> Data(NumIterators);
11218
11219 bool ErrorFound = false;
11220 bool NeedToRebuild = getDerived().AlwaysRebuild();
11221 for (unsigned I = 0; I < NumIterators; ++I) {
11222 auto *D = cast<VarDecl>(E->getIteratorDecl(I));
11223 Data[I].DeclIdent = D->getIdentifier();
11224 Data[I].DeclIdentLoc = D->getLocation();
11225 if (D->getLocation() == D->getBeginLoc()) {
11226 assert(SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) &&(static_cast <bool> (SemaRef.Context.hasSameType(D->
getType(), SemaRef.Context.IntTy) && "Implicit type must be int."
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) && \"Implicit type must be int.\""
, "clang/lib/Sema/TreeTransform.h", 11227, __extension__ __PRETTY_FUNCTION__
))
11227 "Implicit type must be int.")(static_cast <bool> (SemaRef.Context.hasSameType(D->
getType(), SemaRef.Context.IntTy) && "Implicit type must be int."
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) && \"Implicit type must be int.\""
, "clang/lib/Sema/TreeTransform.h", 11227, __extension__ __PRETTY_FUNCTION__
))
;
11228 } else {
11229 TypeSourceInfo *TSI = getDerived().TransformType(D->getTypeSourceInfo());
11230 QualType DeclTy = getDerived().TransformType(D->getType());
11231 Data[I].Type = SemaRef.CreateParsedType(DeclTy, TSI);
11232 }
11233 OMPIteratorExpr::IteratorRange Range = E->getIteratorRange(I);
11234 ExprResult Begin = getDerived().TransformExpr(Range.Begin);
11235 ExprResult End = getDerived().TransformExpr(Range.End);
11236 ExprResult Step = getDerived().TransformExpr(Range.Step);
11237 ErrorFound = ErrorFound ||
11238 !(!D->getTypeSourceInfo() || (Data[I].Type.getAsOpaquePtr() &&
11239 !Data[I].Type.get().isNull())) ||
11240 Begin.isInvalid() || End.isInvalid() || Step.isInvalid();
11241 if (ErrorFound)
11242 continue;
11243 Data[I].Range.Begin = Begin.get();
11244 Data[I].Range.End = End.get();
11245 Data[I].Range.Step = Step.get();
11246 Data[I].AssignLoc = E->getAssignLoc(I);
11247 Data[I].ColonLoc = E->getColonLoc(I);
11248 Data[I].SecColonLoc = E->getSecondColonLoc(I);
11249 NeedToRebuild =
11250 NeedToRebuild ||
11251 (D->getTypeSourceInfo() && Data[I].Type.get().getTypePtrOrNull() !=
11252 D->getType().getTypePtrOrNull()) ||
11253 Range.Begin != Data[I].Range.Begin || Range.End != Data[I].Range.End ||
11254 Range.Step != Data[I].Range.Step;
11255 }
11256 if (ErrorFound)
11257 return ExprError();
11258 if (!NeedToRebuild)
11259 return E;
11260
11261 ExprResult Res = getDerived().RebuildOMPIteratorExpr(
11262 E->getIteratorKwLoc(), E->getLParenLoc(), E->getRParenLoc(), Data);
11263 if (!Res.isUsable())
11264 return Res;
11265 auto *IE = cast<OMPIteratorExpr>(Res.get());
11266 for (unsigned I = 0; I < NumIterators; ++I)
11267 getDerived().transformedLocalDecl(E->getIteratorDecl(I),
11268 IE->getIteratorDecl(I));
11269 return Res;
11270}
11271
11272template<typename Derived>
11273ExprResult
11274TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
11275 // Transform the callee.
11276 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11277 if (Callee.isInvalid())
11278 return ExprError();
11279
11280 // Transform arguments.
11281 bool ArgChanged = false;
11282 SmallVector<Expr*, 8> Args;
11283 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11284 &ArgChanged))
11285 return ExprError();
11286
11287 if (!getDerived().AlwaysRebuild() &&
11288 Callee.get() == E->getCallee() &&
11289 !ArgChanged)
11290 return SemaRef.MaybeBindToTemporary(E);
11291
11292 // FIXME: Wrong source location information for the '('.
11293 SourceLocation FakeLParenLoc
11294 = ((Expr *)Callee.get())->getSourceRange().getBegin();
11295
11296 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11297 if (E->hasStoredFPFeatures()) {
11298 FPOptionsOverride NewOverrides = E->getFPFeatures();
11299 getSema().CurFPFeatures =
11300 NewOverrides.applyOverrides(getSema().getLangOpts());
11301 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11302 }
11303
11304 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11305 Args,
11306 E->getRParenLoc());
11307}
11308
11309template<typename Derived>
11310ExprResult
11311TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
11312 ExprResult Base = getDerived().TransformExpr(E->getBase());
11313 if (Base.isInvalid())
11314 return ExprError();
11315
11316 NestedNameSpecifierLoc QualifierLoc;
11317 if (E->hasQualifier()) {
11318 QualifierLoc
11319 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11320
11321 if (!QualifierLoc)
11322 return ExprError();
11323 }
11324 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11325
11326 ValueDecl *Member
11327 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
11328 E->getMemberDecl()));
11329 if (!Member)
11330 return ExprError();
11331
11332 NamedDecl *FoundDecl = E->getFoundDecl();
11333 if (FoundDecl == E->getMemberDecl()) {
11334 FoundDecl = Member;
11335 } else {
11336 FoundDecl = cast_or_null<NamedDecl>(
11337 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
11338 if (!FoundDecl)
11339 return ExprError();
11340 }
11341
11342 if (!getDerived().AlwaysRebuild() &&
11343 Base.get() == E->getBase() &&
11344 QualifierLoc == E->getQualifierLoc() &&
11345 Member == E->getMemberDecl() &&
11346 FoundDecl == E->getFoundDecl() &&
11347 !E->hasExplicitTemplateArgs()) {
11348
11349 // Skip for member expression of (this->f), rebuilt thisi->f is needed
11350 // for Openmp where the field need to be privatizized in the case.
11351 if (!(isa<CXXThisExpr>(E->getBase()) &&
11352 getSema().isOpenMPRebuildMemberExpr(cast<ValueDecl>(Member)))) {
11353 // Mark it referenced in the new context regardless.
11354 // FIXME: this is a bit instantiation-specific.
11355 SemaRef.MarkMemberReferenced(E);
11356 return E;
11357 }
11358 }
11359
11360 TemplateArgumentListInfo TransArgs;
11361 if (E->hasExplicitTemplateArgs()) {
11362 TransArgs.setLAngleLoc(E->getLAngleLoc());
11363 TransArgs.setRAngleLoc(E->getRAngleLoc());
11364 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11365 E->getNumTemplateArgs(),
11366 TransArgs))
11367 return ExprError();
11368 }
11369
11370 // FIXME: Bogus source location for the operator
11371 SourceLocation FakeOperatorLoc =
11372 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
11373
11374 // FIXME: to do this check properly, we will need to preserve the
11375 // first-qualifier-in-scope here, just in case we had a dependent
11376 // base (and therefore couldn't do the check) and a
11377 // nested-name-qualifier (and therefore could do the lookup).
11378 NamedDecl *FirstQualifierInScope = nullptr;
11379 DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
11380 if (MemberNameInfo.getName()) {
11381 MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
11382 if (!MemberNameInfo.getName())
11383 return ExprError();
11384 }
11385
11386 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
11387 E->isArrow(),
11388 QualifierLoc,
11389 TemplateKWLoc,
11390 MemberNameInfo,
11391 Member,
11392 FoundDecl,
11393 (E->hasExplicitTemplateArgs()
11394 ? &TransArgs : nullptr),
11395 FirstQualifierInScope);
11396}
11397
11398template<typename Derived>
11399ExprResult
11400TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
11401 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11402 if (LHS.isInvalid())
11403 return ExprError();
11404
11405 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11406 if (RHS.isInvalid())
11407 return ExprError();
11408
11409 if (!getDerived().AlwaysRebuild() &&
11410 LHS.get() == E->getLHS() &&
11411 RHS.get() == E->getRHS())
11412 return E;
11413
11414 if (E->isCompoundAssignmentOp())
11415 // FPFeatures has already been established from trailing storage
11416 return getDerived().RebuildBinaryOperator(
11417 E->getOperatorLoc(), E->getOpcode(), LHS.get(), RHS.get());
11418 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11419 FPOptionsOverride NewOverrides(E->getFPFeatures());
11420 getSema().CurFPFeatures =
11421 NewOverrides.applyOverrides(getSema().getLangOpts());
11422 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11423 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
11424 LHS.get(), RHS.get());
11425}
11426
11427template <typename Derived>
11428ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
11429 CXXRewrittenBinaryOperator *E) {
11430 CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
11431
11432 ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
11433 if (LHS.isInvalid())
11434 return ExprError();
11435
11436 ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
11437 if (RHS.isInvalid())
11438 return ExprError();
11439
11440 // Extract the already-resolved callee declarations so that we can restrict
11441 // ourselves to using them as the unqualified lookup results when rebuilding.
11442 UnresolvedSet<2> UnqualLookups;
11443 bool ChangedAnyLookups = false;
11444 Expr *PossibleBinOps[] = {E->getSemanticForm(),
11445 const_cast<Expr *>(Decomp.InnerBinOp)};
11446 for (Expr *PossibleBinOp : PossibleBinOps) {
11447 auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
11448 if (!Op)
11449 continue;
11450 auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
11451 if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
11452 continue;
11453
11454 // Transform the callee in case we built a call to a local extern
11455 // declaration.
11456 NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
11457 E->getOperatorLoc(), Callee->getFoundDecl()));
11458 if (!Found)
11459 return ExprError();
11460 if (Found != Callee->getFoundDecl())
11461 ChangedAnyLookups = true;
11462 UnqualLookups.addDecl(Found);
11463 }
11464
11465 if (!getDerived().AlwaysRebuild() && !ChangedAnyLookups &&
11466 LHS.get() == Decomp.LHS && RHS.get() == Decomp.RHS) {
11467 // Mark all functions used in the rewrite as referenced. Note that when
11468 // a < b is rewritten to (a <=> b) < 0, both the <=> and the < might be
11469 // function calls, and/or there might be a user-defined conversion sequence
11470 // applied to the operands of the <.
11471 // FIXME: this is a bit instantiation-specific.
11472 const Expr *StopAt[] = {Decomp.LHS, Decomp.RHS};
11473 SemaRef.MarkDeclarationsReferencedInExpr(E, false, StopAt);
11474 return E;
11475 }
11476
11477 return getDerived().RebuildCXXRewrittenBinaryOperator(
11478 E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
11479}
11480
11481template<typename Derived>
11482ExprResult
11483TreeTransform<Derived>::TransformCompoundAssignOperator(
11484 CompoundAssignOperator *E) {
11485 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11486 FPOptionsOverride NewOverrides(E->getFPFeatures());
11487 getSema().CurFPFeatures =
11488 NewOverrides.applyOverrides(getSema().getLangOpts());
11489 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11490 return getDerived().TransformBinaryOperator(E);
11491}
11492
11493template<typename Derived>
11494ExprResult TreeTransform<Derived>::
11495TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
11496 // Just rebuild the common and RHS expressions and see whether we
11497 // get any changes.
11498
11499 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
11500 if (commonExpr.isInvalid())
11501 return ExprError();
11502
11503 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
11504 if (rhs.isInvalid())
11505 return ExprError();
11506
11507 if (!getDerived().AlwaysRebuild() &&
11508 commonExpr.get() == e->getCommon() &&
11509 rhs.get() == e->getFalseExpr())
11510 return e;
11511
11512 return getDerived().RebuildConditionalOperator(commonExpr.get(),
11513 e->getQuestionLoc(),
11514 nullptr,
11515 e->getColonLoc(),
11516 rhs.get());
11517}
11518
11519template<typename Derived>
11520ExprResult
11521TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
11522 ExprResult Cond = getDerived().TransformExpr(E->getCond());
11523 if (Cond.isInvalid())
11524 return ExprError();
11525
11526 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11527 if (LHS.isInvalid())
11528 return ExprError();
11529
11530 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11531 if (RHS.isInvalid())
11532 return ExprError();
11533
11534 if (!getDerived().AlwaysRebuild() &&
11535 Cond.get() == E->getCond() &&
11536 LHS.get() == E->getLHS() &&
11537 RHS.get() == E->getRHS())
11538 return E;
11539
11540 return getDerived().RebuildConditionalOperator(Cond.get(),
11541 E->getQuestionLoc(),
11542 LHS.get(),
11543 E->getColonLoc(),
11544 RHS.get());
11545}
11546
11547template<typename Derived>
11548ExprResult
11549TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
11550 // Implicit casts are eliminated during transformation, since they
11551 // will be recomputed by semantic analysis after transformation.
11552 return getDerived().TransformExpr(E->getSubExprAsWritten());
11553}
11554
11555template<typename Derived>
11556ExprResult
11557TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
11558 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11559 if (!Type)
11560 return ExprError();
11561
11562 ExprResult SubExpr
11563 = getDerived().TransformExpr(E->getSubExprAsWritten());
11564 if (SubExpr.isInvalid())
11565 return ExprError();
11566
11567 if (!getDerived().AlwaysRebuild() &&
11568 Type == E->getTypeInfoAsWritten() &&
11569 SubExpr.get() == E->getSubExpr())
11570 return E;
11571
11572 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
11573 Type,
11574 E->getRParenLoc(),
11575 SubExpr.get());
11576}
11577
11578template<typename Derived>
11579ExprResult
11580TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
11581 TypeSourceInfo *OldT = E->getTypeSourceInfo();
11582 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11583 if (!NewT)
11584 return ExprError();
11585
11586 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
11587 if (Init.isInvalid())
11588 return ExprError();
11589
11590 if (!getDerived().AlwaysRebuild() &&
11591 OldT == NewT &&
11592 Init.get() == E->getInitializer())
11593 return SemaRef.MaybeBindToTemporary(E);
11594
11595 // Note: the expression type doesn't necessarily match the
11596 // type-as-written, but that's okay, because it should always be
11597 // derivable from the initializer.
11598
11599 return getDerived().RebuildCompoundLiteralExpr(
11600 E->getLParenLoc(), NewT,
11601 /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
11602}
11603
11604template<typename Derived>
11605ExprResult
11606TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
11607 ExprResult Base = getDerived().TransformExpr(E->getBase());
11608 if (Base.isInvalid())
11609 return ExprError();
11610
11611 if (!getDerived().AlwaysRebuild() &&
11612 Base.get() == E->getBase())
11613 return E;
11614
11615 // FIXME: Bad source location
11616 SourceLocation FakeOperatorLoc =
11617 SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
11618 return getDerived().RebuildExtVectorElementExpr(
11619 Base.get(), FakeOperatorLoc, E->isArrow(), E->getAccessorLoc(),
11620 E->getAccessor());
11621}
11622
11623template<typename Derived>
11624ExprResult
11625TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
11626 if (InitListExpr *Syntactic = E->getSyntacticForm())
11627 E = Syntactic;
11628
11629 bool InitChanged = false;
11630
11631 EnterExpressionEvaluationContext Context(
11632 getSema(), EnterExpressionEvaluationContext::InitList);
11633
11634 SmallVector<Expr*, 4> Inits;
11635 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
11636 Inits, &InitChanged))
11637 return ExprError();
11638
11639 if (!getDerived().AlwaysRebuild() && !InitChanged) {
11640 // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
11641 // in some cases. We can't reuse it in general, because the syntactic and
11642 // semantic forms are linked, and we can't know that semantic form will
11643 // match even if the syntactic form does.
11644 }
11645
11646 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
11647 E->getRBraceLoc());
11648}
11649
11650template<typename Derived>
11651ExprResult
11652TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
11653 Designation Desig;
11654
11655 // transform the initializer value
11656 ExprResult Init = getDerived().TransformExpr(E->getInit());
11657 if (Init.isInvalid())
11658 return ExprError();
11659
11660 // transform the designators.
11661 SmallVector<Expr*, 4> ArrayExprs;
11662 bool ExprChanged = false;
11663 for (const DesignatedInitExpr::Designator &D : E->designators()) {
11664 if (D.isFieldDesignator()) {
11665 Desig.AddDesignator(Designator::CreateFieldDesignator(
11666 D.getFieldName(), D.getDotLoc(), D.getFieldLoc()));
11667 if (D.getFieldDecl()) {
11668 FieldDecl *Field = cast_or_null<FieldDecl>(
11669 getDerived().TransformDecl(D.getFieldLoc(), D.getFieldDecl()));
11670 if (Field != D.getFieldDecl())
11671 // Rebuild the expression when the transformed FieldDecl is
11672 // different to the already assigned FieldDecl.
11673 ExprChanged = true;
11674 } else {
11675 // Ensure that the designator expression is rebuilt when there isn't
11676 // a resolved FieldDecl in the designator as we don't want to assign
11677 // a FieldDecl to a pattern designator that will be instantiated again.
11678 ExprChanged = true;
11679 }
11680 continue;
11681 }
11682
11683 if (D.isArrayDesignator()) {
11684 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
11685 if (Index.isInvalid())
11686 return ExprError();
11687
11688 Desig.AddDesignator(
11689 Designator::CreateArrayDesignator(Index.get(), D.getLBracketLoc()));
11690
11691 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
11692 ArrayExprs.push_back(Index.get());
11693 continue;
11694 }
11695
11696 assert(D.isArrayRangeDesignator() && "New kind of designator?")(static_cast <bool> (D.isArrayRangeDesignator() &&
"New kind of designator?") ? void (0) : __assert_fail ("D.isArrayRangeDesignator() && \"New kind of designator?\""
, "clang/lib/Sema/TreeTransform.h", 11696, __extension__ __PRETTY_FUNCTION__
))
;
11697 ExprResult Start
11698 = getDerived().TransformExpr(E->getArrayRangeStart(D));
11699 if (Start.isInvalid())
11700 return ExprError();
11701
11702 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
11703 if (End.isInvalid())
11704 return ExprError();
11705
11706 Desig.AddDesignator(Designator::CreateArrayRangeDesignator(
11707 Start.get(), End.get(), D.getLBracketLoc(), D.getEllipsisLoc()));
11708
11709 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
11710 End.get() != E->getArrayRangeEnd(D);
11711
11712 ArrayExprs.push_back(Start.get());
11713 ArrayExprs.push_back(End.get());
11714 }
11715
11716 if (!getDerived().AlwaysRebuild() &&
11717 Init.get() == E->getInit() &&
11718 !ExprChanged)
11719 return E;
11720
11721 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
11722 E->getEqualOrColonLoc(),
11723 E->usesGNUSyntax(), Init.get());
11724}
11725
11726// Seems that if TransformInitListExpr() only works on the syntactic form of an
11727// InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
11728template<typename Derived>
11729ExprResult
11730TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
11731 DesignatedInitUpdateExpr *E) {
11732 llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "::llvm::llvm_unreachable_internal("Unexpected DesignatedInitUpdateExpr in syntactic form of "
"initializer", "clang/lib/Sema/TreeTransform.h", 11733)
11733 "initializer")::llvm::llvm_unreachable_internal("Unexpected DesignatedInitUpdateExpr in syntactic form of "
"initializer", "clang/lib/Sema/TreeTransform.h", 11733)
;
11734 return ExprError();
11735}
11736
11737template<typename Derived>
11738ExprResult
11739TreeTransform<Derived>::TransformNoInitExpr(
11740 NoInitExpr *E) {
11741 llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer")::llvm::llvm_unreachable_internal("Unexpected NoInitExpr in syntactic form of initializer"
, "clang/lib/Sema/TreeTransform.h", 11741)
;
11742 return ExprError();
11743}
11744
11745template<typename Derived>
11746ExprResult
11747TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
11748 llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer")::llvm::llvm_unreachable_internal("Unexpected ArrayInitLoopExpr outside of initializer"
, "clang/lib/Sema/TreeTransform.h", 11748)
;
11749 return ExprError();
11750}
11751
11752template<typename Derived>
11753ExprResult
11754TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
11755 llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer")::llvm::llvm_unreachable_internal("Unexpected ArrayInitIndexExpr outside of initializer"
, "clang/lib/Sema/TreeTransform.h", 11755)
;
11756 return ExprError();
11757}
11758
11759template<typename Derived>
11760ExprResult
11761TreeTransform<Derived>::TransformImplicitValueInitExpr(
11762 ImplicitValueInitExpr *E) {
11763 TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
11764
11765 // FIXME: Will we ever have proper type location here? Will we actually
11766 // need to transform the type?
11767 QualType T = getDerived().TransformType(E->getType());
11768 if (T.isNull())
11769 return ExprError();
11770
11771 if (!getDerived().AlwaysRebuild() &&
11772 T == E->getType())
11773 return E;
11774
11775 return getDerived().RebuildImplicitValueInitExpr(T);
11776}
11777
11778template<typename Derived>
11779ExprResult
11780TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
11781 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
11782 if (!TInfo)
11783 return ExprError();
11784
11785 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11786 if (SubExpr.isInvalid())
11787 return ExprError();
11788
11789 if (!getDerived().AlwaysRebuild() &&
11790 TInfo == E->getWrittenTypeInfo() &&
11791 SubExpr.get() == E->getSubExpr())
11792 return E;
11793
11794 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
11795 TInfo, E->getRParenLoc());
11796}
11797
11798template<typename Derived>
11799ExprResult
11800TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
11801 bool ArgumentChanged = false;
11802 SmallVector<Expr*, 4> Inits;
11803 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
11804 &ArgumentChanged))
11805 return ExprError();
11806
11807 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
11808 Inits,
11809 E->getRParenLoc());
11810}
11811
11812/// Transform an address-of-label expression.
11813///
11814/// By default, the transformation of an address-of-label expression always
11815/// rebuilds the expression, so that the label identifier can be resolved to
11816/// the corresponding label statement by semantic analysis.
11817template<typename Derived>
11818ExprResult
11819TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
11820 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
11821 E->getLabel());
11822 if (!LD)
11823 return ExprError();
11824
11825 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
11826 cast<LabelDecl>(LD));
11827}
11828
11829template<typename Derived>
11830ExprResult
11831TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
11832 SemaRef.ActOnStartStmtExpr();
11833 StmtResult SubStmt
11834 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
11835 if (SubStmt.isInvalid()) {
11836 SemaRef.ActOnStmtExprError();
11837 return ExprError();
11838 }
11839
11840 unsigned OldDepth = E->getTemplateDepth();
11841 unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
11842
11843 if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
11844 SubStmt.get() == E->getSubStmt()) {
11845 // Calling this an 'error' is unintuitive, but it does the right thing.
11846 SemaRef.ActOnStmtExprError();
11847 return SemaRef.MaybeBindToTemporary(E);
11848 }
11849
11850 return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
11851 E->getRParenLoc(), NewDepth);
11852}
11853
11854template<typename Derived>
11855ExprResult
11856TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
11857 ExprResult Cond = getDerived().TransformExpr(E->getCond());
11858 if (Cond.isInvalid())
11859 return ExprError();
11860
11861 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11862 if (LHS.isInvalid())
11863 return ExprError();
11864
11865 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11866 if (RHS.isInvalid())
11867 return ExprError();
11868
11869 if (!getDerived().AlwaysRebuild() &&
11870 Cond.get() == E->getCond() &&
11871 LHS.get() == E->getLHS() &&
11872 RHS.get() == E->getRHS())
11873 return E;
11874
11875 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
11876 Cond.get(), LHS.get(), RHS.get(),
11877 E->getRParenLoc());
11878}
11879
11880template<typename Derived>
11881ExprResult
11882TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
11883 return E;
11884}
11885
11886template<typename Derived>
11887ExprResult
11888TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11889 switch (E->getOperator()) {
3
Control jumps to 'case OO_Subscript:' at line 11896
11890 case OO_New:
11891 case OO_Delete:
11892 case OO_Array_New:
11893 case OO_Array_Delete:
11894 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr")::llvm::llvm_unreachable_internal("new and delete operators cannot use CXXOperatorCallExpr"
, "clang/lib/Sema/TreeTransform.h", 11894)
;
11895
11896 case OO_Subscript:
11897 case OO_Call: {
11898 // This is a call to an object's operator().
11899 assert(E->getNumArgs() >= 1 && "Object call is missing arguments")(static_cast <bool> (E->getNumArgs() >= 1 &&
"Object call is missing arguments") ? void (0) : __assert_fail
("E->getNumArgs() >= 1 && \"Object call is missing arguments\""
, "clang/lib/Sema/TreeTransform.h", 11899, __extension__ __PRETTY_FUNCTION__
))
;
4
Assuming the condition is true
5
'?' condition is true
11900
11901 // Transform the object itself.
11902 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
11903 if (Object.isInvalid())
6
Assuming the condition is false
7
Taking false branch
11904 return ExprError();
11905
11906 // FIXME: Poor location information
11907 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
11908 static_cast<Expr *>(Object.get())->getEndLoc());
11909
11910 // Transform the call arguments.
11911 SmallVector<Expr*, 8> Args;
11912 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
8
Taking false branch
11913 Args))
11914 return ExprError();
11915
11916 if (E->getOperator() == OO_Subscript)
9
Taking true branch
11917 return getDerived().RebuildCxxSubscriptExpr(Object.get(), FakeLParenLoc,
10
Calling 'ActionResult::get'
14
Returning from 'ActionResult::get'
15
Passing value via 1st parameter 'Callee'
16
Calling 'TreeTransform::RebuildCxxSubscriptExpr'
11918 Args, E->getEndLoc());
11919
11920 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
11921 E->getEndLoc());
11922 }
11923
11924#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
11925 case OO_##Name: \
11926 break;
11927
11928#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
11929#include "clang/Basic/OperatorKinds.def"
11930
11931 case OO_Conditional:
11932 llvm_unreachable("conditional operator is not actually overloadable")::llvm::llvm_unreachable_internal("conditional operator is not actually overloadable"
, "clang/lib/Sema/TreeTransform.h", 11932)
;
11933
11934 case OO_None:
11935 case NUM_OVERLOADED_OPERATORS:
11936 llvm_unreachable("not an overloaded operator?")::llvm::llvm_unreachable_internal("not an overloaded operator?"
, "clang/lib/Sema/TreeTransform.h", 11936)
;
11937 }
11938
11939 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11940 if (Callee.isInvalid())
11941 return ExprError();
11942
11943 ExprResult First;
11944 if (E->getOperator() == OO_Amp)
11945 First = getDerived().TransformAddressOfOperand(E->getArg(0));
11946 else
11947 First = getDerived().TransformExpr(E->getArg(0));
11948 if (First.isInvalid())
11949 return ExprError();
11950
11951 ExprResult Second;
11952 if (E->getNumArgs() == 2) {
11953 Second = getDerived().TransformExpr(E->getArg(1));
11954 if (Second.isInvalid())
11955 return ExprError();
11956 }
11957
11958 if (!getDerived().AlwaysRebuild() &&
11959 Callee.get() == E->getCallee() &&
11960 First.get() == E->getArg(0) &&
11961 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
11962 return SemaRef.MaybeBindToTemporary(E);
11963
11964 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11965 FPOptionsOverride NewOverrides(E->getFPFeatures());
11966 getSema().CurFPFeatures =
11967 NewOverrides.applyOverrides(getSema().getLangOpts());
11968 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11969
11970 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
11971 E->getOperatorLoc(),
11972 Callee.get(),
11973 First.get(),
11974 Second.get());
11975}
11976
11977template<typename Derived>
11978ExprResult
11979TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
11980 return getDerived().TransformCallExpr(E);
11981}
11982
11983template <typename Derived>
11984ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
11985 bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
11986 getSema().CurContext != E->getParentContext();
11987
11988 if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
11989 return E;
11990
11991 return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
11992 E->getBeginLoc(), E->getEndLoc(),
11993 getSema().CurContext);
11994}
11995
11996template<typename Derived>
11997ExprResult
11998TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
11999 // Transform the callee.
12000 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
12001 if (Callee.isInvalid())
12002 return ExprError();
12003
12004 // Transform exec config.
12005 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
12006 if (EC.isInvalid())
12007 return ExprError();
12008
12009 // Transform arguments.
12010 bool ArgChanged = false;
12011 SmallVector<Expr*, 8> Args;
12012 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12013 &ArgChanged))
12014 return ExprError();
12015
12016 if (!getDerived().AlwaysRebuild() &&
12017 Callee.get() == E->getCallee() &&
12018 !ArgChanged)
12019 return SemaRef.MaybeBindToTemporary(E);
12020
12021 // FIXME: Wrong source location information for the '('.
12022 SourceLocation FakeLParenLoc
12023 = ((Expr *)Callee.get())->getSourceRange().getBegin();
12024 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
12025 Args,
12026 E->getRParenLoc(), EC.get());
12027}
12028
12029template<typename Derived>
12030ExprResult
12031TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
12032 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
12033 if (!Type)
12034 return ExprError();
12035
12036 ExprResult SubExpr
12037 = getDerived().TransformExpr(E->getSubExprAsWritten());
12038 if (SubExpr.isInvalid())
12039 return ExprError();
12040
12041 if (!getDerived().AlwaysRebuild() &&
12042 Type == E->getTypeInfoAsWritten() &&
12043 SubExpr.get() == E->getSubExpr())
12044 return E;
12045 return getDerived().RebuildCXXNamedCastExpr(
12046 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
12047 Type, E->getAngleBrackets().getEnd(),
12048 // FIXME. this should be '(' location
12049 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
12050}
12051
12052template<typename Derived>
12053ExprResult
12054TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
12055 TypeSourceInfo *TSI =
12056 getDerived().TransformType(BCE->getTypeInfoAsWritten());
12057 if (!TSI)
12058 return ExprError();
12059
12060 ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
12061 if (Sub.isInvalid())
12062 return ExprError();
12063
12064 return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
12065 Sub.get(), BCE->getEndLoc());
12066}
12067
12068template<typename Derived>
12069ExprResult
12070TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
12071 return getDerived().TransformCXXNamedCastExpr(E);
12072}
12073
12074template<typename Derived>
12075ExprResult
12076TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
12077 return getDerived().TransformCXXNamedCastExpr(E);
12078}
12079
12080template<typename Derived>
12081ExprResult
12082TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
12083 CXXReinterpretCastExpr *E) {
12084 return getDerived().TransformCXXNamedCastExpr(E);
12085}
12086
12087template<typename Derived>
12088ExprResult
12089TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
12090 return getDerived().TransformCXXNamedCastExpr(E);
12091}
12092
12093template<typename Derived>
12094ExprResult
12095TreeTransform<Derived>::TransformCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
12096 return getDerived().TransformCXXNamedCastExpr(E);
12097}
12098
12099template<typename Derived>
12100ExprResult
12101TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
12102 CXXFunctionalCastExpr *E) {
12103 TypeSourceInfo *Type =
12104 getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
12105 if (!Type)
12106 return ExprError();
12107
12108 ExprResult SubExpr
12109 = getDerived().TransformExpr(E->getSubExprAsWritten());
12110 if (SubExpr.isInvalid())
12111 return ExprError();
12112
12113 if (!getDerived().AlwaysRebuild() &&
12114 Type == E->getTypeInfoAsWritten() &&
12115 SubExpr.get() == E->getSubExpr())
12116 return E;
12117
12118 return getDerived().RebuildCXXFunctionalCastExpr(Type,
12119 E->getLParenLoc(),
12120 SubExpr.get(),
12121 E->getRParenLoc(),
12122 E->isListInitialization());
12123}
12124
12125template<typename Derived>
12126ExprResult
12127TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
12128 if (E->isTypeOperand()) {
12129 TypeSourceInfo *TInfo
12130 = getDerived().TransformType(E->getTypeOperandSourceInfo());
12131 if (!TInfo)
12132 return ExprError();
12133
12134 if (!getDerived().AlwaysRebuild() &&
12135 TInfo == E->getTypeOperandSourceInfo())
12136 return E;
12137
12138 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12139 TInfo, E->getEndLoc());
12140 }
12141
12142 // Typeid's operand is an unevaluated context, unless it's a polymorphic
12143 // type. We must not unilaterally enter unevaluated context here, as then
12144 // semantic processing can re-transform an already transformed operand.
12145 Expr *Op = E->getExprOperand();
12146 auto EvalCtx = Sema::ExpressionEvaluationContext::Unevaluated;
12147 if (E->isGLValue())
12148 if (auto *RecordT = Op->getType()->getAs<RecordType>())
12149 if (cast<CXXRecordDecl>(RecordT->getDecl())->isPolymorphic())
12150 EvalCtx = SemaRef.ExprEvalContexts.back().Context;
12151
12152 EnterExpressionEvaluationContext Unevaluated(SemaRef, EvalCtx,
12153 Sema::ReuseLambdaContextDecl);
12154
12155 ExprResult SubExpr = getDerived().TransformExpr(Op);
12156 if (SubExpr.isInvalid())
12157 return ExprError();
12158
12159 if (!getDerived().AlwaysRebuild() &&
12160 SubExpr.get() == E->getExprOperand())
12161 return E;
12162
12163 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12164 SubExpr.get(), E->getEndLoc());
12165}
12166
12167template<typename Derived>
12168ExprResult
12169TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
12170 if (E->isTypeOperand()) {
12171 TypeSourceInfo *TInfo
12172 = getDerived().TransformType(E->getTypeOperandSourceInfo());
12173 if (!TInfo)
12174 return ExprError();
12175
12176 if (!getDerived().AlwaysRebuild() &&
12177 TInfo == E->getTypeOperandSourceInfo())
12178 return E;
12179
12180 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12181 TInfo, E->getEndLoc());
12182 }
12183
12184 EnterExpressionEvaluationContext Unevaluated(
12185 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12186
12187 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
12188 if (SubExpr.isInvalid())
12189 return ExprError();
12190
12191 if (!getDerived().AlwaysRebuild() &&
12192 SubExpr.get() == E->getExprOperand())
12193 return E;
12194
12195 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12196 SubExpr.get(), E->getEndLoc());
12197}
12198
12199template<typename Derived>
12200ExprResult
12201TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
12202 return E;
12203}
12204
12205template<typename Derived>
12206ExprResult
12207TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
12208 CXXNullPtrLiteralExpr *E) {
12209 return E;
12210}
12211
12212template<typename Derived>
12213ExprResult
12214TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
12215 QualType T = getSema().getCurrentThisType();
12216
12217 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
12218 // Mark it referenced in the new context regardless.
12219 // FIXME: this is a bit instantiation-specific.
12220 getSema().MarkThisReferenced(E);
12221 return E;
12222 }
12223
12224 return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
12225}
12226
12227template<typename Derived>
12228ExprResult
12229TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
12230 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12231 if (SubExpr.isInvalid())
12232 return ExprError();
12233
12234 if (!getDerived().AlwaysRebuild() &&
12235 SubExpr.get() == E->getSubExpr())
12236 return E;
12237
12238 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
12239 E->isThrownVariableInScope());
12240}
12241
12242template<typename Derived>
12243ExprResult
12244TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12245 ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
12246 getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
12247 if (!Param)
12248 return ExprError();
12249
12250 ExprResult InitRes;
12251 if (E->hasRewrittenInit()) {
12252 InitRes = getDerived().TransformExpr(E->getRewrittenExpr());
12253 if (InitRes.isInvalid())
12254 return ExprError();
12255 }
12256
12257 if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
12258 E->getUsedContext() == SemaRef.CurContext &&
12259 InitRes.get() == E->getRewrittenExpr())
12260 return E;
12261
12262 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param,
12263 InitRes.get());
12264}
12265
12266template<typename Derived>
12267ExprResult
12268TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
12269 FieldDecl *Field = cast_or_null<FieldDecl>(
12270 getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
12271 if (!Field)
12272 return ExprError();
12273
12274 if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
12275 E->getUsedContext() == SemaRef.CurContext)
12276 return E;
12277
12278 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
12279}
12280
12281template<typename Derived>
12282ExprResult
12283TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
12284 CXXScalarValueInitExpr *E) {
12285 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
12286 if (!T)
12287 return ExprError();
12288
12289 if (!getDerived().AlwaysRebuild() &&
12290 T == E->getTypeSourceInfo())
12291 return E;
12292
12293 return getDerived().RebuildCXXScalarValueInitExpr(T,
12294 /*FIXME:*/T->getTypeLoc().getEndLoc(),
12295 E->getRParenLoc());
12296}
12297
12298template<typename Derived>
12299ExprResult
12300TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
12301 // Transform the type that we're allocating
12302 TypeSourceInfo *AllocTypeInfo =
12303 getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
12304 if (!AllocTypeInfo)
12305 return ExprError();
12306
12307 // Transform the size of the array we're allocating (if any).
12308 std::optional<Expr *> ArraySize;
12309 if (E->isArray()) {
12310 ExprResult NewArraySize;
12311 if (std::optional<Expr *> OldArraySize = E->getArraySize()) {
12312 NewArraySize = getDerived().TransformExpr(*OldArraySize);
12313 if (NewArraySize.isInvalid())
12314 return ExprError();
12315 }
12316 ArraySize = NewArraySize.get();
12317 }
12318
12319 // Transform the placement arguments (if any).
12320 bool ArgumentChanged = false;
12321 SmallVector<Expr*, 8> PlacementArgs;
12322 if (getDerived().TransformExprs(E->getPlacementArgs(),
12323 E->getNumPlacementArgs(), true,
12324 PlacementArgs, &ArgumentChanged))
12325 return ExprError();
12326
12327 // Transform the initializer (if any).
12328 Expr *OldInit = E->getInitializer();
12329 ExprResult NewInit;
12330 if (OldInit)
12331 NewInit = getDerived().TransformInitializer(OldInit, true);
12332 if (NewInit.isInvalid())
12333 return ExprError();
12334
12335 // Transform new operator and delete operator.
12336 FunctionDecl *OperatorNew = nullptr;
12337 if (E->getOperatorNew()) {
12338 OperatorNew = cast_or_null<FunctionDecl>(
12339 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
12340 if (!OperatorNew)
12341 return ExprError();
12342 }
12343
12344 FunctionDecl *OperatorDelete = nullptr;
12345 if (E->getOperatorDelete()) {
12346 OperatorDelete = cast_or_null<FunctionDecl>(
12347 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12348 if (!OperatorDelete)
12349 return ExprError();
12350 }
12351
12352 if (!getDerived().AlwaysRebuild() &&
12353 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
12354 ArraySize == E->getArraySize() &&
12355 NewInit.get() == OldInit &&
12356 OperatorNew == E->getOperatorNew() &&
12357 OperatorDelete == E->getOperatorDelete() &&
12358 !ArgumentChanged) {
12359 // Mark any declarations we need as referenced.
12360 // FIXME: instantiation-specific.
12361 if (OperatorNew)
12362 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
12363 if (OperatorDelete)
12364 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12365
12366 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
12367 QualType ElementType
12368 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
12369 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
12370 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
12371 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
12372 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
12373 }
12374 }
12375 }
12376
12377 return E;
12378 }
12379
12380 QualType AllocType = AllocTypeInfo->getType();
12381 if (!ArraySize) {
12382 // If no array size was specified, but the new expression was
12383 // instantiated with an array type (e.g., "new T" where T is
12384 // instantiated with "int[4]"), extract the outer bound from the
12385 // array type as our array size. We do this with constant and
12386 // dependently-sized array types.
12387 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
12388 if (!ArrayT) {
12389 // Do nothing
12390 } else if (const ConstantArrayType *ConsArrayT
12391 = dyn_cast<ConstantArrayType>(ArrayT)) {
12392 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
12393 SemaRef.Context.getSizeType(),
12394 /*FIXME:*/ E->getBeginLoc());
12395 AllocType = ConsArrayT->getElementType();
12396 } else if (const DependentSizedArrayType *DepArrayT
12397 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
12398 if (DepArrayT->getSizeExpr()) {
12399 ArraySize = DepArrayT->getSizeExpr();
12400 AllocType = DepArrayT->getElementType();
12401 }
12402 }
12403 }
12404
12405 return getDerived().RebuildCXXNewExpr(
12406 E->getBeginLoc(), E->isGlobalNew(),
12407 /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
12408 /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
12409 AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
12410}
12411
12412template<typename Derived>
12413ExprResult
12414TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
12415 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
12416 if (Operand.isInvalid())
12417 return ExprError();
12418
12419 // Transform the delete operator, if known.
12420 FunctionDecl *OperatorDelete = nullptr;
12421 if (E->getOperatorDelete()) {
12422 OperatorDelete = cast_or_null<FunctionDecl>(
12423 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12424 if (!OperatorDelete)
12425 return ExprError();
12426 }
12427
12428 if (!getDerived().AlwaysRebuild() &&
12429 Operand.get() == E->getArgument() &&
12430 OperatorDelete == E->getOperatorDelete()) {
12431 // Mark any declarations we need as referenced.
12432 // FIXME: instantiation-specific.
12433 if (OperatorDelete)
12434 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12435
12436 if (!E->getArgument()->isTypeDependent()) {
12437 QualType Destroyed = SemaRef.Context.getBaseElementType(
12438 E->getDestroyedType());
12439 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12440 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12441 SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
12442 SemaRef.LookupDestructor(Record));
12443 }
12444 }
12445
12446 return E;
12447 }
12448
12449 return getDerived().RebuildCXXDeleteExpr(
12450 E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
12451}
12452
12453template<typename Derived>
12454ExprResult
12455TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
12456 CXXPseudoDestructorExpr *E) {
12457 ExprResult Base = getDerived().TransformExpr(E->getBase());
12458 if (Base.isInvalid())
12459 return ExprError();
12460
12461 ParsedType ObjectTypePtr;
12462 bool MayBePseudoDestructor = false;
12463 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
12464 E->getOperatorLoc(),
12465 E->isArrow()? tok::arrow : tok::period,
12466 ObjectTypePtr,
12467 MayBePseudoDestructor);
12468 if (Base.isInvalid())
12469 return ExprError();
12470
12471 QualType ObjectType = ObjectTypePtr.get();
12472 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
12473 if (QualifierLoc) {
12474 QualifierLoc
12475 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
12476 if (!QualifierLoc)
12477 return ExprError();
12478 }
12479 CXXScopeSpec SS;
12480 SS.Adopt(QualifierLoc);
12481
12482 PseudoDestructorTypeStorage Destroyed;
12483 if (E->getDestroyedTypeInfo()) {
12484 TypeSourceInfo *DestroyedTypeInfo
12485 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
12486 ObjectType, nullptr, SS);
12487 if (!DestroyedTypeInfo)
12488 return ExprError();
12489 Destroyed = DestroyedTypeInfo;
12490 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
12491 // We aren't likely to be able to resolve the identifier down to a type
12492 // now anyway, so just retain the identifier.
12493 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
12494 E->getDestroyedTypeLoc());
12495 } else {
12496 // Look for a destructor known with the given name.
12497 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
12498 *E->getDestroyedTypeIdentifier(),
12499 E->getDestroyedTypeLoc(),
12500 /*Scope=*/nullptr,
12501 SS, ObjectTypePtr,
12502 false);
12503 if (!T)
12504 return ExprError();
12505
12506 Destroyed
12507 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
12508 E->getDestroyedTypeLoc());
12509 }
12510
12511 TypeSourceInfo *ScopeTypeInfo = nullptr;
12512 if (E->getScopeTypeInfo()) {
12513 CXXScopeSpec EmptySS;
12514 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
12515 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
12516 if (!ScopeTypeInfo)
12517 return ExprError();
12518 }
12519
12520 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
12521 E->getOperatorLoc(),
12522 E->isArrow(),
12523 SS,
12524 ScopeTypeInfo,
12525 E->getColonColonLoc(),
12526 E->getTildeLoc(),
12527 Destroyed);
12528}
12529
12530template <typename Derived>
12531bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
12532 bool RequiresADL,
12533 LookupResult &R) {
12534 // Transform all the decls.
12535 bool AllEmptyPacks = true;
12536 for (auto *OldD : Old->decls()) {
12537 Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
12538 if (!InstD) {
12539 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
12540 // This can happen because of dependent hiding.
12541 if (isa<UsingShadowDecl>(OldD))
12542 continue;
12543 else {
12544 R.clear();
12545 return true;
12546 }
12547 }
12548
12549 // Expand using pack declarations.
12550 NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
12551 ArrayRef<NamedDecl*> Decls = SingleDecl;
12552 if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
12553 Decls = UPD->expansions();
12554
12555 // Expand using declarations.
12556 for (auto *D : Decls) {
12557 if (auto *UD = dyn_cast<UsingDecl>(D)) {
12558 for (auto *SD : UD->shadows())
12559 R.addDecl(SD);
12560 } else {
12561 R.addDecl(D);
12562 }
12563 }
12564
12565 AllEmptyPacks &= Decls.empty();
12566 };
12567
12568 // C++ [temp.res]/8.4.2:
12569 // The program is ill-formed, no diagnostic required, if [...] lookup for
12570 // a name in the template definition found a using-declaration, but the
12571 // lookup in the corresponding scope in the instantiation odoes not find
12572 // any declarations because the using-declaration was a pack expansion and
12573 // the corresponding pack is empty
12574 if (AllEmptyPacks && !RequiresADL) {
12575 getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
12576 << isa<UnresolvedMemberExpr>(Old) << Old->getName();
12577 return true;
12578 }
12579
12580 // Resolve a kind, but don't do any further analysis. If it's
12581 // ambiguous, the callee needs to deal with it.
12582 R.resolveKind();
12583 return false;
12584}
12585
12586template<typename Derived>
12587ExprResult
12588TreeTransform<Derived>::TransformUnresolvedLookupExpr(
12589 UnresolvedLookupExpr *Old) {
12590 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
12591 Sema::LookupOrdinaryName);
12592
12593 // Transform the declaration set.
12594 if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
12595 return ExprError();
12596
12597 // Rebuild the nested-name qualifier, if present.
12598 CXXScopeSpec SS;
12599 if (Old->getQualifierLoc()) {
12600 NestedNameSpecifierLoc QualifierLoc
12601 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12602 if (!QualifierLoc)
12603 return ExprError();
12604
12605 SS.Adopt(QualifierLoc);
12606 }
12607
12608 if (Old->getNamingClass()) {
12609 CXXRecordDecl *NamingClass
12610 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12611 Old->getNameLoc(),
12612 Old->getNamingClass()));
12613 if (!NamingClass) {
12614 R.clear();
12615 return ExprError();
12616 }
12617
12618 R.setNamingClass(NamingClass);
12619 }
12620
12621 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12622
12623 // If we have neither explicit template arguments, nor the template keyword,
12624 // it's a normal declaration name or member reference.
12625 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
12626 NamedDecl *D = R.getAsSingle<NamedDecl>();
12627 // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
12628 // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
12629 // give a good diagnostic.
12630 if (D && D->isCXXInstanceMember()) {
12631 return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12632 /*TemplateArgs=*/nullptr,
12633 /*Scope=*/nullptr);
12634 }
12635
12636 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
12637 }
12638
12639 // If we have template arguments, rebuild them, then rebuild the
12640 // templateid expression.
12641 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
12642 if (Old->hasExplicitTemplateArgs() &&
12643 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12644 Old->getNumTemplateArgs(),
12645 TransArgs)) {
12646 R.clear();
12647 return ExprError();
12648 }
12649
12650 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
12651 Old->requiresADL(), &TransArgs);
12652}
12653
12654template<typename Derived>
12655ExprResult
12656TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
12657 bool ArgChanged = false;
12658 SmallVector<TypeSourceInfo *, 4> Args;
12659 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
12660 TypeSourceInfo *From = E->getArg(I);
12661 TypeLoc FromTL = From->getTypeLoc();
12662 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
12663 TypeLocBuilder TLB;
12664 TLB.reserve(FromTL.getFullDataSize());
12665 QualType To = getDerived().TransformType(TLB, FromTL);
12666 if (To.isNull())
12667 return ExprError();
12668
12669 if (To == From->getType())
12670 Args.push_back(From);
12671 else {
12672 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12673 ArgChanged = true;
12674 }
12675 continue;
12676 }
12677
12678 ArgChanged = true;
12679
12680 // We have a pack expansion. Instantiate it.
12681 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
12682 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
12683 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12684 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
12685
12686 // Determine whether the set of unexpanded parameter packs can and should
12687 // be expanded.
12688 bool Expand = true;
12689 bool RetainExpansion = false;
12690 std::optional<unsigned> OrigNumExpansions =
12691 ExpansionTL.getTypePtr()->getNumExpansions();
12692 std::optional<unsigned> NumExpansions = OrigNumExpansions;
12693 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
12694 PatternTL.getSourceRange(),
12695 Unexpanded,
12696 Expand, RetainExpansion,
12697 NumExpansions))
12698 return ExprError();
12699
12700 if (!Expand) {
12701 // The transform has determined that we should perform a simple
12702 // transformation on the pack expansion, producing another pack
12703 // expansion.
12704 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12705
12706 TypeLocBuilder TLB;
12707 TLB.reserve(From->getTypeLoc().getFullDataSize());
12708
12709 QualType To = getDerived().TransformType(TLB, PatternTL);
12710 if (To.isNull())
12711 return ExprError();
12712
12713 To = getDerived().RebuildPackExpansionType(To,
12714 PatternTL.getSourceRange(),
12715 ExpansionTL.getEllipsisLoc(),
12716 NumExpansions);
12717 if (To.isNull())
12718 return ExprError();
12719
12720 PackExpansionTypeLoc ToExpansionTL
12721 = TLB.push<PackExpansionTypeLoc>(To);
12722 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12723 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12724 continue;
12725 }
12726
12727 // Expand the pack expansion by substituting for each argument in the
12728 // pack(s).
12729 for (unsigned I = 0; I != *NumExpansions; ++I) {
12730 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
12731 TypeLocBuilder TLB;
12732 TLB.reserve(PatternTL.getFullDataSize());
12733 QualType To = getDerived().TransformType(TLB, PatternTL);
12734 if (To.isNull())
12735 return ExprError();
12736
12737 if (To->containsUnexpandedParameterPack()) {
12738 To = getDerived().RebuildPackExpansionType(To,
12739 PatternTL.getSourceRange(),
12740 ExpansionTL.getEllipsisLoc(),
12741 NumExpansions);
12742 if (To.isNull())
12743 return ExprError();
12744
12745 PackExpansionTypeLoc ToExpansionTL
12746 = TLB.push<PackExpansionTypeLoc>(To);
12747 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12748 }
12749
12750 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12751 }
12752
12753 if (!RetainExpansion)
12754 continue;
12755
12756 // If we're supposed to retain a pack expansion, do so by temporarily
12757 // forgetting the partially-substituted parameter pack.
12758 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12759
12760 TypeLocBuilder TLB;
12761 TLB.reserve(From->getTypeLoc().getFullDataSize());
12762
12763 QualType To = getDerived().TransformType(TLB, PatternTL);
12764 if (To.isNull())
12765 return ExprError();
12766
12767 To = getDerived().RebuildPackExpansionType(To,
12768 PatternTL.getSourceRange(),
12769 ExpansionTL.getEllipsisLoc(),
12770 NumExpansions);
12771 if (To.isNull())
12772 return ExprError();
12773
12774 PackExpansionTypeLoc ToExpansionTL
12775 = TLB.push<PackExpansionTypeLoc>(To);
12776 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12777 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12778 }
12779
12780 if (!getDerived().AlwaysRebuild() && !ArgChanged)
12781 return E;
12782
12783 return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
12784 E->getEndLoc());
12785}
12786
12787template<typename Derived>
12788ExprResult
12789TreeTransform<Derived>::TransformConceptSpecializationExpr(
12790 ConceptSpecializationExpr *E) {
12791 const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
12792 TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
12793 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12794 Old->NumTemplateArgs, TransArgs))
12795 return ExprError();
12796
12797 return getDerived().RebuildConceptSpecializationExpr(
12798 E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
12799 E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
12800 &TransArgs);
12801}
12802
12803template<typename Derived>
12804ExprResult
12805TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
12806 SmallVector<ParmVarDecl*, 4> TransParams;
12807 SmallVector<QualType, 4> TransParamTypes;
12808 Sema::ExtParameterInfoBuilder ExtParamInfos;
12809
12810 // C++2a [expr.prim.req]p2
12811 // Expressions appearing within a requirement-body are unevaluated operands.
12812 EnterExpressionEvaluationContext Ctx(
12813 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
12814 Sema::ReuseLambdaContextDecl);
12815
12816 RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
12817 getSema().Context, getSema().CurContext,
12818 E->getBody()->getBeginLoc());
12819
12820 Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
12821
12822 ExprResult TypeParamResult = getDerived().TransformRequiresTypeParams(
12823 E->getRequiresKWLoc(), E->getRBraceLoc(), E, Body,
12824 E->getLocalParameters(), TransParamTypes, TransParams, ExtParamInfos);
12825
12826 for (ParmVarDecl *Param : TransParams)
12827 if (Param)
12828 Param->setDeclContext(Body);
12829
12830 // On failure to transform, TransformRequiresTypeParams returns an expression
12831 // in the event that the transformation of the type params failed in some way.
12832 // It is expected that this will result in a 'not satisfied' Requires clause
12833 // when instantiating.
12834 if (!TypeParamResult.isUnset())
12835 return TypeParamResult;
12836
12837 SmallVector<concepts::Requirement *, 4> TransReqs;
12838 if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
12839 TransReqs))
12840 return ExprError();
12841
12842 for (concepts::Requirement *Req : TransReqs) {
12843 if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
12844 if (ER->getReturnTypeRequirement().isTypeConstraint()) {
12845 ER->getReturnTypeRequirement()
12846 .getTypeConstraintTemplateParameterList()->getParam(0)
12847 ->setDeclContext(Body);
12848 }
12849 }
12850 }
12851
12852 return getDerived().RebuildRequiresExpr(E->getRequiresKWLoc(), Body,
12853 TransParams, TransReqs,
12854 E->getRBraceLoc());
12855}
12856
12857template<typename Derived>
12858bool TreeTransform<Derived>::TransformRequiresExprRequirements(
12859 ArrayRef<concepts::Requirement *> Reqs,
12860 SmallVectorImpl<concepts::Requirement *> &Transformed) {
12861 for (concepts::Requirement *Req : Reqs) {
12862 concepts::Requirement *TransReq = nullptr;
12863 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
12864 TransReq = getDerived().TransformTypeRequirement(TypeReq);
12865 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
12866 TransReq = getDerived().TransformExprRequirement(ExprReq);
12867 else
12868 TransReq = getDerived().TransformNestedRequirement(
12869 cast<concepts::NestedRequirement>(Req));
12870 if (!TransReq)
12871 return true;
12872 Transformed.push_back(TransReq);
12873 }
12874 return false;
12875}
12876
12877template<typename Derived>
12878concepts::TypeRequirement *
12879TreeTransform<Derived>::TransformTypeRequirement(
12880 concepts::TypeRequirement *Req) {
12881 if (Req->isSubstitutionFailure()) {
12882 if (getDerived().AlwaysRebuild())
12883 return getDerived().RebuildTypeRequirement(
12884 Req->getSubstitutionDiagnostic());
12885 return Req;
12886 }
12887 TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
12888 if (!TransType)
12889 return nullptr;
12890 return getDerived().RebuildTypeRequirement(TransType);
12891}
12892
12893template<typename Derived>
12894concepts::ExprRequirement *
12895TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
12896 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
12897 if (Req->isExprSubstitutionFailure())
12898 TransExpr = Req->getExprSubstitutionDiagnostic();
12899 else {
12900 ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
12901 if (TransExprRes.isUsable() && TransExprRes.get()->hasPlaceholderType())
12902 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
12903 if (TransExprRes.isInvalid())
12904 return nullptr;
12905 TransExpr = TransExprRes.get();
12906 }
12907
12908 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
12909 const auto &RetReq = Req->getReturnTypeRequirement();
12910 if (RetReq.isEmpty())
12911 TransRetReq.emplace();
12912 else if (RetReq.isSubstitutionFailure())
12913 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
12914 else if (RetReq.isTypeConstraint()) {
12915 TemplateParameterList *OrigTPL =
12916 RetReq.getTypeConstraintTemplateParameterList();
12917 TemplateParameterList *TPL =
12918 getDerived().TransformTemplateParameterList(OrigTPL);
12919 if (!TPL)
12920 return nullptr;
12921 TransRetReq.emplace(TPL);
12922 }
12923 assert(TransRetReq && "All code paths leading here must set TransRetReq")(static_cast <bool> (TransRetReq && "All code paths leading here must set TransRetReq"
) ? void (0) : __assert_fail ("TransRetReq && \"All code paths leading here must set TransRetReq\""
, "clang/lib/Sema/TreeTransform.h", 12923, __extension__ __PRETTY_FUNCTION__
))
;
12924 if (Expr *E = TransExpr.dyn_cast<Expr *>())
12925 return getDerived().RebuildExprRequirement(E, Req->isSimple(),
12926 Req->getNoexceptLoc(),
12927 std::move(*TransRetReq));
12928 return getDerived().RebuildExprRequirement(
12929 TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
12930 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
12931}
12932
12933template<typename Derived>
12934concepts::NestedRequirement *
12935TreeTransform<Derived>::TransformNestedRequirement(
12936 concepts::NestedRequirement *Req) {
12937 if (Req->hasInvalidConstraint()) {
12938 if (getDerived().AlwaysRebuild())
12939 return getDerived().RebuildNestedRequirement(
12940 Req->getInvalidConstraintEntity(), Req->getConstraintSatisfaction());
12941 return Req;
12942 }
12943 ExprResult TransConstraint =
12944 getDerived().TransformExpr(Req->getConstraintExpr());
12945 if (TransConstraint.isInvalid())
12946 return nullptr;
12947 return getDerived().RebuildNestedRequirement(TransConstraint.get());
12948}
12949
12950template<typename Derived>
12951ExprResult
12952TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
12953 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
12954 if (!T)
12955 return ExprError();
12956
12957 if (!getDerived().AlwaysRebuild() &&
12958 T == E->getQueriedTypeSourceInfo())
12959 return E;
12960
12961 ExprResult SubExpr;
12962 {
12963 EnterExpressionEvaluationContext Unevaluated(
12964 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12965 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
12966 if (SubExpr.isInvalid())
12967 return ExprError();
12968
12969 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
12970 return E;
12971 }
12972
12973 return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
12974 SubExpr.get(), E->getEndLoc());
12975}
12976
12977template<typename Derived>
12978ExprResult
12979TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
12980 ExprResult SubExpr;
12981 {
12982 EnterExpressionEvaluationContext Unevaluated(
12983 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12984 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
12985 if (SubExpr.isInvalid())
12986 return ExprError();
12987
12988 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
12989 return E;
12990 }
12991
12992 return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
12993 SubExpr.get(), E->getEndLoc());
12994}
12995
12996template <typename Derived>
12997ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
12998 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
12999 TypeSourceInfo **RecoveryTSI) {
13000 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
13001 DRE, AddrTaken, RecoveryTSI);
13002
13003 // Propagate both errors and recovered types, which return ExprEmpty.
13004 if (!NewDRE.isUsable())
13005 return NewDRE;
13006
13007 // We got an expr, wrap it up in parens.
13008 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
13009 return PE;
13010 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
13011 PE->getRParen());
13012}
13013
13014template <typename Derived>
13015ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
13016 DependentScopeDeclRefExpr *E) {
13017 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
13018 nullptr);
13019}
13020
13021template <typename Derived>
13022ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
13023 DependentScopeDeclRefExpr *E, bool IsAddressOfOperand,
13024 TypeSourceInfo **RecoveryTSI) {
13025 assert(E->getQualifierLoc())(static_cast <bool> (E->getQualifierLoc()) ? void (0
) : __assert_fail ("E->getQualifierLoc()", "clang/lib/Sema/TreeTransform.h"
, 13025, __extension__ __PRETTY_FUNCTION__))
;
13026 NestedNameSpecifierLoc QualifierLoc =
13027 getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
13028 if (!QualifierLoc)
13029 return ExprError();
13030 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13031
13032 // TODO: If this is a conversion-function-id, verify that the
13033 // destination type name (if present) resolves the same way after
13034 // instantiation as it did in the local scope.
13035
13036 DeclarationNameInfo NameInfo =
13037 getDerived().TransformDeclarationNameInfo(E->getNameInfo());
13038 if (!NameInfo.getName())
13039 return ExprError();
13040
13041 if (!E->hasExplicitTemplateArgs()) {
13042 if (!getDerived().AlwaysRebuild() && QualifierLoc == E->getQualifierLoc() &&
13043 // Note: it is sufficient to compare the Name component of NameInfo:
13044 // if name has not changed, DNLoc has not changed either.
13045 NameInfo.getName() == E->getDeclName())
13046 return E;
13047
13048 return getDerived().RebuildDependentScopeDeclRefExpr(
13049 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
13050 IsAddressOfOperand, RecoveryTSI);
13051 }
13052
13053 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13054 if (getDerived().TransformTemplateArguments(
13055 E->getTemplateArgs(), E->getNumTemplateArgs(), TransArgs))
13056 return ExprError();
13057
13058 return getDerived().RebuildDependentScopeDeclRefExpr(
13059 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
13060 RecoveryTSI);
13061}
13062
13063template<typename Derived>
13064ExprResult
13065TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
13066 // CXXConstructExprs other than for list-initialization and
13067 // CXXTemporaryObjectExpr are always implicit, so when we have
13068 // a 1-argument construction we just transform that argument.
13069 if (getDerived().AllowSkippingCXXConstructExpr() &&
13070 ((E->getNumArgs() == 1 ||
13071 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
13072 (!getDerived().DropCallArgument(E->getArg(0))) &&
13073 !E->isListInitialization()))
13074 return getDerived().TransformInitializer(E->getArg(0),
13075 /*DirectInit*/ false);
13076
13077 TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
13078
13079 QualType T = getDerived().TransformType(E->getType());
13080 if (T.isNull())
13081 return ExprError();
13082
13083 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13084 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13085 if (!Constructor)
13086 return ExprError();
13087
13088 bool ArgumentChanged = false;
13089 SmallVector<Expr*, 8> Args;
13090 {
13091 EnterExpressionEvaluationContext Context(
13092 getSema(), EnterExpressionEvaluationContext::InitList,
13093 E->isListInitialization());
13094 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13095 &ArgumentChanged))
13096 return ExprError();
13097 }
13098
13099 if (!getDerived().AlwaysRebuild() &&
13100 T == E->getType() &&
13101 Constructor == E->getConstructor() &&
13102 !ArgumentChanged) {
13103 // Mark the constructor as referenced.
13104 // FIXME: Instantiation-specific
13105 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13106 return E;
13107 }
13108
13109 return getDerived().RebuildCXXConstructExpr(
13110 T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
13111 E->hadMultipleCandidates(), E->isListInitialization(),
13112 E->isStdInitListInitialization(), E->requiresZeroInitialization(),
13113 E->getConstructionKind(), E->getParenOrBraceRange());
13114}
13115
13116template<typename Derived>
13117ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
13118 CXXInheritedCtorInitExpr *E) {
13119 QualType T = getDerived().TransformType(E->getType());
13120 if (T.isNull())
13121 return ExprError();
13122
13123 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13124 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13125 if (!Constructor)
13126 return ExprError();
13127
13128 if (!getDerived().AlwaysRebuild() &&
13129 T == E->getType() &&
13130 Constructor == E->getConstructor()) {
13131 // Mark the constructor as referenced.
13132 // FIXME: Instantiation-specific
13133 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13134 return E;
13135 }
13136
13137 return getDerived().RebuildCXXInheritedCtorInitExpr(
13138 T, E->getLocation(), Constructor,
13139 E->constructsVBase(), E->inheritedFromVBase());
13140}
13141
13142/// Transform a C++ temporary-binding expression.
13143///
13144/// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
13145/// transform the subexpression and return that.
13146template<typename Derived>
13147ExprResult
13148TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13149 if (auto *Dtor = E->getTemporary()->getDestructor())
13150 SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
13151 const_cast<CXXDestructorDecl *>(Dtor));
13152 return getDerived().TransformExpr(E->getSubExpr());
13153}
13154
13155/// Transform a C++ expression that contains cleanups that should
13156/// be run after the expression is evaluated.
13157///
13158/// Since ExprWithCleanups nodes are implicitly generated, we
13159/// just transform the subexpression and return that.
13160template<typename Derived>
13161ExprResult
13162TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
13163 return getDerived().TransformExpr(E->getSubExpr());
13164}
13165
13166template<typename Derived>
13167ExprResult
13168TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
13169 CXXTemporaryObjectExpr *E) {
13170 TypeSourceInfo *T =
13171 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13172 if (!T)
13173 return ExprError();
13174
13175 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13176 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13177 if (!Constructor)
13178 return ExprError();
13179
13180 bool ArgumentChanged = false;
13181 SmallVector<Expr*, 8> Args;
13182 Args.reserve(E->getNumArgs());
13183 {
13184 EnterExpressionEvaluationContext Context(
13185 getSema(), EnterExpressionEvaluationContext::InitList,
13186 E->isListInitialization());
13187 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13188 &ArgumentChanged))
13189 return ExprError();
13190 }
13191
13192 if (!getDerived().AlwaysRebuild() &&
13193 T == E->getTypeSourceInfo() &&
13194 Constructor == E->getConstructor() &&
13195 !ArgumentChanged) {
13196 // FIXME: Instantiation-specific
13197 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13198 return SemaRef.MaybeBindToTemporary(E);
13199 }
13200
13201 // FIXME: We should just pass E->isListInitialization(), but we're not
13202 // prepared to handle list-initialization without a child InitListExpr.
13203 SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
13204 return getDerived().RebuildCXXTemporaryObjectExpr(
13205 T, LParenLoc, Args, E->getEndLoc(),
13206 /*ListInitialization=*/LParenLoc.isInvalid());
13207}
13208
13209template<typename Derived>
13210ExprResult
13211TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
13212 // Transform any init-capture expressions before entering the scope of the
13213 // lambda body, because they are not semantically within that scope.
13214 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
13215 struct TransformedInitCapture {
13216 // The location of the ... if the result is retaining a pack expansion.
13217 SourceLocation EllipsisLoc;
13218 // Zero or more expansions of the init-capture.
13219 SmallVector<InitCaptureInfoTy, 4> Expansions;
13220 };
13221 SmallVector<TransformedInitCapture, 4> InitCaptures;
13222 InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
13223 for (LambdaExpr::capture_iterator C = E->capture_begin(),
13224 CEnd = E->capture_end();
13225 C != CEnd; ++C) {
13226 if (!E->isInitCapture(C))
13227 continue;
13228
13229 TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
13230 auto *OldVD = cast<VarDecl>(C->getCapturedVar());
13231
13232 auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
13233 std::optional<unsigned> NumExpansions) {
13234 ExprResult NewExprInitResult = getDerived().TransformInitializer(
13235 OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
13236
13237 if (NewExprInitResult.isInvalid()) {
13238 Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
13239 return;
13240 }
13241 Expr *NewExprInit = NewExprInitResult.get();
13242
13243 QualType NewInitCaptureType =
13244 getSema().buildLambdaInitCaptureInitialization(
13245 C->getLocation(), C->getCaptureKind() == LCK_ByRef,
13246 EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
13247 cast<VarDecl>(C->getCapturedVar())->getInitStyle() !=
13248 VarDecl::CInit,
13249 NewExprInit);
13250 Result.Expansions.push_back(
13251 InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
13252 };
13253
13254 // If this is an init-capture pack, consider expanding the pack now.
13255 if (OldVD->isParameterPack()) {
13256 PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
13257 ->getTypeLoc()
13258 .castAs<PackExpansionTypeLoc>();
13259 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13260 SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
13261
13262 // Determine whether the set of unexpanded parameter packs can and should
13263 // be expanded.
13264 bool Expand = true;
13265 bool RetainExpansion = false;
13266 std::optional<unsigned> OrigNumExpansions =
13267 ExpansionTL.getTypePtr()->getNumExpansions();
13268 std::optional<unsigned> NumExpansions = OrigNumExpansions;
13269 if (getDerived().TryExpandParameterPacks(
13270 ExpansionTL.getEllipsisLoc(),
13271 OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
13272 RetainExpansion, NumExpansions))
13273 return ExprError();
13274 if (Expand) {
13275 for (unsigned I = 0; I != *NumExpansions; ++I) {
13276 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13277 SubstInitCapture(SourceLocation(), std::nullopt);
13278 }
13279 }
13280 if (!Expand || RetainExpansion) {
13281 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13282 SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
13283 Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
13284 }
13285 } else {
13286 SubstInitCapture(SourceLocation(), std::nullopt);
13287 }
13288 }
13289
13290 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
13291 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
13292
13293 // Create the local class that will describe the lambda.
13294
13295 // FIXME: DependencyKind below is wrong when substituting inside a templated
13296 // context that isn't a DeclContext (such as a variable template), or when
13297 // substituting an unevaluated lambda inside of a function's parameter's type
13298 // - as parameter types are not instantiated from within a function's DC. We
13299 // use evaluation contexts to distinguish the function parameter case.
13300 CXXRecordDecl::LambdaDependencyKind DependencyKind =
13301 CXXRecordDecl::LDK_Unknown;
13302 if ((getSema().isUnevaluatedContext() ||
13303 getSema().isConstantEvaluatedContext()) &&
13304 (getSema().CurContext->isFileContext() ||
13305 !getSema().CurContext->getParent()->isDependentContext()))
13306 DependencyKind = CXXRecordDecl::LDK_NeverDependent;
13307
13308 CXXRecordDecl *OldClass = E->getLambdaClass();
13309 CXXRecordDecl *Class = getSema().createLambdaClosureType(
13310 E->getIntroducerRange(), /*Info=*/nullptr, DependencyKind,
13311 E->getCaptureDefault());
13312 getDerived().transformedLocalDecl(OldClass, {Class});
13313
13314 CXXMethodDecl *NewCallOperator =
13315 getSema().CreateLambdaCallOperator(E->getIntroducerRange(), Class);
13316 NewCallOperator->setLexicalDeclContext(getSema().CurContext);
13317
13318 // Enter the scope of the lambda.
13319 getSema().buildLambdaScope(LSI, NewCallOperator, E->getIntroducerRange(),
13320 E->getCaptureDefault(), E->getCaptureDefaultLoc(),
13321 E->hasExplicitParameters(), E->isMutable());
13322
13323 // Introduce the context of the call operator.
13324 Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
13325 /*NewThisContext*/false);
13326
13327 bool Invalid = false;
13328
13329 // Transform captures.
13330 for (LambdaExpr::capture_iterator C = E->capture_begin(),
13331 CEnd = E->capture_end();
13332 C != CEnd; ++C) {
13333 // When we hit the first implicit capture, tell Sema that we've finished
13334 // the list of explicit captures.
13335 if (C->isImplicit())
13336 break;
13337
13338 // Capturing 'this' is trivial.
13339 if (C->capturesThis()) {
13340 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13341 /*BuildAndDiagnose*/ true, nullptr,
13342 C->getCaptureKind() == LCK_StarThis);
13343 continue;
13344 }
13345 // Captured expression will be recaptured during captured variables
13346 // rebuilding.
13347 if (C->capturesVLAType())
13348 continue;
13349
13350 // Rebuild init-captures, including the implied field declaration.
13351 if (E->isInitCapture(C)) {
13352 TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
13353
13354 auto *OldVD = cast<VarDecl>(C->getCapturedVar());
13355 llvm::SmallVector<Decl*, 4> NewVDs;
13356
13357 for (InitCaptureInfoTy &Info : NewC.Expansions) {
13358 ExprResult Init = Info.first;
13359 QualType InitQualType = Info.second;
13360 if (Init.isInvalid() || InitQualType.isNull()) {
13361 Invalid = true;
13362 break;
13363 }
13364 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
13365 OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
13366 OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get(),
13367 getSema().CurContext);
13368 if (!NewVD) {
13369 Invalid = true;
13370 break;
13371 }
13372 NewVDs.push_back(NewVD);
13373 getSema().addInitCapture(LSI, NewVD, C->getCaptureKind() == LCK_ByRef);
13374 }
13375
13376 if (Invalid)
13377 break;
13378
13379 getDerived().transformedLocalDecl(OldVD, NewVDs);
13380 continue;
13381 }
13382
13383 assert(C->capturesVariable() && "unexpected kind of lambda capture")(static_cast <bool> (C->capturesVariable() &&
"unexpected kind of lambda capture") ? void (0) : __assert_fail
("C->capturesVariable() && \"unexpected kind of lambda capture\""
, "clang/lib/Sema/TreeTransform.h", 13383, __extension__ __PRETTY_FUNCTION__
))
;
13384
13385 // Determine the capture kind for Sema.
13386 Sema::TryCaptureKind Kind
13387 = C->isImplicit()? Sema::TryCapture_Implicit
13388 : C->getCaptureKind() == LCK_ByCopy
13389 ? Sema::TryCapture_ExplicitByVal
13390 : Sema::TryCapture_ExplicitByRef;
13391 SourceLocation EllipsisLoc;
13392 if (C->isPackExpansion()) {
13393 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
13394 bool ShouldExpand = false;
13395 bool RetainExpansion = false;
13396 std::optional<unsigned> NumExpansions;
13397 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
13398 C->getLocation(),
13399 Unexpanded,
13400 ShouldExpand, RetainExpansion,
13401 NumExpansions)) {
13402 Invalid = true;
13403 continue;
13404 }
13405
13406 if (ShouldExpand) {
13407 // The transform has determined that we should perform an expansion;
13408 // transform and capture each of the arguments.
13409 // expansion of the pattern. Do so.
13410 auto *Pack = cast<VarDecl>(C->getCapturedVar());
13411 for (unsigned I = 0; I != *NumExpansions; ++I) {
13412 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13413 VarDecl *CapturedVar
13414 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
13415 Pack));
13416 if (!CapturedVar) {
13417 Invalid = true;
13418 continue;
13419 }
13420
13421 // Capture the transformed variable.
13422 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
13423 }
13424
13425 // FIXME: Retain a pack expansion if RetainExpansion is true.
13426
13427 continue;
13428 }
13429
13430 EllipsisLoc = C->getEllipsisLoc();
13431 }
13432
13433 // Transform the captured variable.
13434 auto *CapturedVar = cast_or_null<ValueDecl>(
13435 getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13436 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
13437 Invalid = true;
13438 continue;
13439 }
13440
13441 // Capture the transformed variable.
13442 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
13443 EllipsisLoc);
13444 }
13445 getSema().finishLambdaExplicitCaptures(LSI);
13446
13447 // Transform the template parameters, and add them to the current
13448 // instantiation scope. The null case is handled correctly.
13449 auto TPL = getDerived().TransformTemplateParameterList(
13450 E->getTemplateParameterList());
13451 LSI->GLTemplateParameterList = TPL;
13452
13453 // Transform the type of the original lambda's call operator.
13454 // The transformation MUST be done in the CurrentInstantiationScope since
13455 // it introduces a mapping of the original to the newly created
13456 // transformed parameters.
13457 TypeSourceInfo *NewCallOpTSI = nullptr;
13458 {
13459 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
13460 auto OldCallOpFPTL =
13461 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
13462
13463 TypeLocBuilder NewCallOpTLBuilder;
13464 SmallVector<QualType, 4> ExceptionStorage;
13465 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
13466 QualType NewCallOpType = TransformFunctionProtoType(
13467 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
13468 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
13469 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
13470 ExceptionStorage, Changed);
13471 });
13472 if (NewCallOpType.isNull())
13473 return ExprError();
13474 NewCallOpTSI =
13475 NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context, NewCallOpType);
13476 }
13477
13478 getSema().CompleteLambdaCallOperator(
13479 NewCallOperator, E->getCallOperator()->getLocation(),
13480 E->getCallOperator()->getInnerLocStart(),
13481 E->getCallOperator()->getTrailingRequiresClause(), NewCallOpTSI,
13482 E->getCallOperator()->getConstexprKind(),
13483 E->getCallOperator()->getStorageClass(),
13484 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
13485 E->hasExplicitResultType());
13486
13487 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
13488 getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
13489
13490 {
13491 // Number the lambda for linkage purposes if necessary.
13492 Sema::ContextRAII ManglingContext(getSema(), Class->getDeclContext());
13493
13494 std::optional<CXXRecordDecl::LambdaNumbering> Numbering;
13495 if (getDerived().ReplacingOriginal()) {
13496 Numbering = OldClass->getLambdaNumbering();
13497 }
13498
13499 getSema().handleLambdaNumbering(Class, NewCallOperator, Numbering);
13500 }
13501
13502 // FIXME: Sema's lambda-building mechanism expects us to push an expression
13503 // evaluation context even if we're not transforming the function body.
13504 getSema().PushExpressionEvaluationContext(
13505 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13506
13507 // Instantiate the body of the lambda expression.
13508 StmtResult Body =
13509 Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
13510
13511 // ActOnLambda* will pop the function scope for us.
13512 FuncScopeCleanup.disable();
13513
13514 if (Body.isInvalid()) {
13515 SavedContext.pop();
13516 getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
13517 /*IsInstantiation=*/true);
13518 return ExprError();
13519 }
13520
13521 // Copy the LSI before ActOnFinishFunctionBody removes it.
13522 // FIXME: This is dumb. Store the lambda information somewhere that outlives
13523 // the call operator.
13524 auto LSICopy = *LSI;
13525 getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
13526 /*IsInstantiation*/ true);
13527 SavedContext.pop();
13528
13529 return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
13530 &LSICopy);
13531}
13532
13533template<typename Derived>
13534StmtResult
13535TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
13536 return TransformStmt(S);
13537}
13538
13539template<typename Derived>
13540StmtResult
13541TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
13542 // Transform captures.
13543 for (LambdaExpr::capture_iterator C = E->capture_begin(),
13544 CEnd = E->capture_end();
13545 C != CEnd; ++C) {
13546 // When we hit the first implicit capture, tell Sema that we've finished
13547 // the list of explicit captures.
13548 if (!C->isImplicit())
13549 continue;
13550
13551 // Capturing 'this' is trivial.
13552 if (C->capturesThis()) {
13553 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13554 /*BuildAndDiagnose*/ true, nullptr,
13555 C->getCaptureKind() == LCK_StarThis);
13556 continue;
13557 }
13558 // Captured expression will be recaptured during captured variables
13559 // rebuilding.
13560 if (C->capturesVLAType())
13561 continue;
13562
13563 assert(C->capturesVariable() && "unexpected kind of lambda capture")(static_cast <bool> (C->capturesVariable() &&
"unexpected kind of lambda capture") ? void (0) : __assert_fail
("C->capturesVariable() && \"unexpected kind of lambda capture\""
, "clang/lib/Sema/TreeTransform.h", 13563, __extension__ __PRETTY_FUNCTION__
))
;
13564 assert(!E->isInitCapture(C) && "implicit init-capture?")(static_cast <bool> (!E->isInitCapture(C) &&
"implicit init-capture?") ? void (0) : __assert_fail ("!E->isInitCapture(C) && \"implicit init-capture?\""
, "clang/lib/Sema/TreeTransform.h", 13564, __extension__ __PRETTY_FUNCTION__
))
;
13565
13566 // Transform the captured variable.
13567 VarDecl *CapturedVar = cast_or_null<VarDecl>(
13568 getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13569 if (!CapturedVar || CapturedVar->isInvalidDecl())
13570 return StmtError();
13571
13572 // Capture the transformed variable.
13573 getSema().tryCaptureVariable(CapturedVar, C->getLocation());
13574 }
13575
13576 return S;
13577}
13578
13579template<typename Derived>
13580ExprResult
13581TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
13582 CXXUnresolvedConstructExpr *E) {
13583 TypeSourceInfo *T =
13584 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13585 if (!T)
13586 return ExprError();
13587
13588 bool ArgumentChanged = false;
13589 SmallVector<Expr*, 8> Args;
13590 Args.reserve(E->getNumArgs());
13591 {
13592 EnterExpressionEvaluationContext Context(
13593 getSema(), EnterExpressionEvaluationContext::InitList,
13594 E->isListInitialization());
13595 if (getDerived().TransformExprs(E->arg_begin(), E->getNumArgs(), true, Args,
13596 &ArgumentChanged))
13597 return ExprError();
13598 }
13599
13600 if (!getDerived().AlwaysRebuild() &&
13601 T == E->getTypeSourceInfo() &&
13602 !ArgumentChanged)
13603 return E;
13604
13605 // FIXME: we're faking the locations of the commas
13606 return getDerived().RebuildCXXUnresolvedConstructExpr(
13607 T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
13608}
13609
13610template<typename Derived>
13611ExprResult
13612TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
13613 CXXDependentScopeMemberExpr *E) {
13614 // Transform the base of the expression.
13615 ExprResult Base((Expr*) nullptr);
13616 Expr *OldBase;
13617 QualType BaseType;
13618 QualType ObjectType;
13619 if (!E->isImplicitAccess()) {
13620 OldBase = E->getBase();
13621 Base = getDerived().TransformExpr(OldBase);
13622 if (Base.isInvalid())
13623 return ExprError();
13624
13625 // Start the member reference and compute the object's type.
13626 ParsedType ObjectTy;
13627 bool MayBePseudoDestructor = false;
13628 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
13629 E->getOperatorLoc(),
13630 E->isArrow()? tok::arrow : tok::period,
13631 ObjectTy,
13632 MayBePseudoDestructor);
13633 if (Base.isInvalid())
13634 return ExprError();
13635
13636 ObjectType = ObjectTy.get();
13637 BaseType = ((Expr*) Base.get())->getType();
13638 } else {
13639 OldBase = nullptr;
13640 BaseType = getDerived().TransformType(E->getBaseType());
13641 ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
13642 }
13643
13644 // Transform the first part of the nested-name-specifier that qualifies
13645 // the member name.
13646 NamedDecl *FirstQualifierInScope
13647 = getDerived().TransformFirstQualifierInScope(
13648 E->getFirstQualifierFoundInScope(),
13649 E->getQualifierLoc().getBeginLoc());
13650
13651 NestedNameSpecifierLoc QualifierLoc;
13652 if (E->getQualifier()) {
13653 QualifierLoc
13654 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
13655 ObjectType,
13656 FirstQualifierInScope);
13657 if (!QualifierLoc)
13658 return ExprError();
13659 }
13660
13661 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13662
13663 // TODO: If this is a conversion-function-id, verify that the
13664 // destination type name (if present) resolves the same way after
13665 // instantiation as it did in the local scope.
13666
13667 DeclarationNameInfo NameInfo
13668 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
13669 if (!NameInfo.getName())
13670 return ExprError();
13671
13672 if (!E->hasExplicitTemplateArgs()) {
13673 // This is a reference to a member without an explicitly-specified
13674 // template argument list. Optimize for this common case.
13675 if (!getDerived().AlwaysRebuild() &&
13676 Base.get() == OldBase &&
13677 BaseType == E->getBaseType() &&
13678 QualifierLoc == E->getQualifierLoc() &&
13679 NameInfo.getName() == E->getMember() &&
13680 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
13681 return E;
13682
13683 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13684 BaseType,
13685 E->isArrow(),
13686 E->getOperatorLoc(),
13687 QualifierLoc,
13688 TemplateKWLoc,
13689 FirstQualifierInScope,
13690 NameInfo,
13691 /*TemplateArgs*/nullptr);
13692 }
13693
13694 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13695 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
13696 E->getNumTemplateArgs(),
13697 TransArgs))
13698 return ExprError();
13699
13700 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13701 BaseType,
13702 E->isArrow(),
13703 E->getOperatorLoc(),
13704 QualifierLoc,
13705 TemplateKWLoc,
13706 FirstQualifierInScope,
13707 NameInfo,
13708 &TransArgs);
13709}
13710
13711template <typename Derived>
13712ExprResult TreeTransform<Derived>::TransformUnresolvedMemberExpr(
13713 UnresolvedMemberExpr *Old) {
13714 // Transform the base of the expression.
13715 ExprResult Base((Expr *)nullptr);
13716 QualType BaseType;
13717 if (!Old->isImplicitAccess()) {
13718 Base = getDerived().TransformExpr(Old->getBase());
13719 if (Base.isInvalid())
13720 return ExprError();
13721 Base =
13722 getSema().PerformMemberExprBaseConversion(Base.get(), Old->isArrow());
13723 if (Base.isInvalid())
13724 return ExprError();
13725 BaseType = Base.get()->getType();
13726 } else {
13727 BaseType = getDerived().TransformType(Old->getBaseType());
13728 }
13729
13730 NestedNameSpecifierLoc QualifierLoc;
13731 if (Old->getQualifierLoc()) {
13732 QualifierLoc =
13733 getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
13734 if (!QualifierLoc)
13735 return ExprError();
13736 }
13737
13738 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
13739
13740 LookupResult R(SemaRef, Old->getMemberNameInfo(), Sema::LookupOrdinaryName);
13741
13742 // Transform the declaration set.
13743 if (TransformOverloadExprDecls(Old, /*RequiresADL*/ false, R))
13744 return ExprError();
13745
13746 // Determine the naming class.
13747 if (Old->getNamingClass()) {
13748 CXXRecordDecl *NamingClass = cast_or_null<CXXRecordDecl>(
13749 getDerived().TransformDecl(Old->getMemberLoc(), Old->getNamingClass()));
13750 if (!NamingClass)
13751 return ExprError();
13752
13753 R.setNamingClass(NamingClass);
13754 }
13755
13756 TemplateArgumentListInfo TransArgs;
13757 if (Old->hasExplicitTemplateArgs()) {
13758 TransArgs.setLAngleLoc(Old->getLAngleLoc());
13759 TransArgs.setRAngleLoc(Old->getRAngleLoc());
13760 if (getDerived().TransformTemplateArguments(
13761 Old->getTemplateArgs(), Old->getNumTemplateArgs(), TransArgs))
13762 return ExprError();
13763 }
13764
13765 // FIXME: to do this check properly, we will need to preserve the
13766 // first-qualifier-in-scope here, just in case we had a dependent
13767 // base (and therefore couldn't do the check) and a
13768 // nested-name-qualifier (and therefore could do the lookup).
13769 NamedDecl *FirstQualifierInScope = nullptr;
13770
13771 return getDerived().RebuildUnresolvedMemberExpr(
13772 Base.get(), BaseType, Old->getOperatorLoc(), Old->isArrow(), QualifierLoc,
13773 TemplateKWLoc, FirstQualifierInScope, R,
13774 (Old->hasExplicitTemplateArgs() ? &TransArgs : nullptr));
13775}
13776
13777template<typename Derived>
13778ExprResult
13779TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
13780 EnterExpressionEvaluationContext Unevaluated(
13781 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13782 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
13783 if (SubExpr.isInvalid())
13784 return ExprError();
13785
13786 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
13787 return E;
13788
13789 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
13790}
13791
13792template<typename Derived>
13793ExprResult
13794TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
13795 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
13796 if (Pattern.isInvalid())
13797 return ExprError();
13798
13799 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
13800 return E;
13801
13802 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
13803 E->getNumExpansions());
13804}
13805
13806template<typename Derived>
13807ExprResult
13808TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
13809 // If E is not value-dependent, then nothing will change when we transform it.
13810 // Note: This is an instantiation-centric view.
13811 if (!E->isValueDependent())
13812 return E;
13813
13814 EnterExpressionEvaluationContext Unevaluated(
13815 getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
13816
13817 ArrayRef<TemplateArgument> PackArgs;
13818 TemplateArgument ArgStorage;
13819
13820 // Find the argument list to transform.
13821 if (E->isPartiallySubstituted()) {
13822 PackArgs = E->getPartialArguments();
13823 } else if (E->isValueDependent()) {
13824 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
13825 bool ShouldExpand = false;
13826 bool RetainExpansion = false;
13827 std::optional<unsigned> NumExpansions;
13828 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
13829 Unexpanded,
13830 ShouldExpand, RetainExpansion,
13831 NumExpansions))
13832 return ExprError();
13833
13834 // If we need to expand the pack, build a template argument from it and
13835 // expand that.
13836 if (ShouldExpand) {
13837 auto *Pack = E->getPack();
13838 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
13839 ArgStorage = getSema().Context.getPackExpansionType(
13840 getSema().Context.getTypeDeclType(TTPD), std::nullopt);
13841 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
13842 ArgStorage = TemplateArgument(TemplateName(TTPD), std::nullopt);
13843 } else {
13844 auto *VD = cast<ValueDecl>(Pack);
13845 ExprResult DRE = getSema().BuildDeclRefExpr(
13846 VD, VD->getType().getNonLValueExprType(getSema().Context),
13847 VD->getType()->isReferenceType() ? VK_LValue : VK_PRValue,
13848 E->getPackLoc());
13849 if (DRE.isInvalid())
13850 return ExprError();
13851 ArgStorage = new (getSema().Context)
13852 PackExpansionExpr(getSema().Context.DependentTy, DRE.get(),
13853 E->getPackLoc(), std::nullopt);
13854 }
13855 PackArgs = ArgStorage;
13856 }
13857 }
13858
13859 // If we're not expanding the pack, just transform the decl.
13860 if (!PackArgs.size()) {
13861 auto *Pack = cast_or_null<NamedDecl>(
13862 getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
13863 if (!Pack)
13864 return ExprError();
13865 return getDerived().RebuildSizeOfPackExpr(
13866 E->getOperatorLoc(), Pack, E->getPackLoc(), E->getRParenLoc(),
13867 std::nullopt, std::nullopt);
13868 }
13869
13870 // Try to compute the result without performing a partial substitution.
13871 std::optional<unsigned> Result = 0;
13872 for (const TemplateArgument &Arg : PackArgs) {
13873 if (!Arg.isPackExpansion()) {
13874 Result = *Result + 1;
13875 continue;
13876 }
13877
13878 TemplateArgumentLoc ArgLoc;
13879 InventTemplateArgumentLoc(Arg, ArgLoc);
13880
13881 // Find the pattern of the pack expansion.
13882 SourceLocation Ellipsis;
13883 std::optional<unsigned> OrigNumExpansions;
13884 TemplateArgumentLoc Pattern =
13885 getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
13886 OrigNumExpansions);
13887
13888 // Substitute under the pack expansion. Do not expand the pack (yet).
13889 TemplateArgumentLoc OutPattern;
13890 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13891 if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
13892 /*Uneval*/ true))
13893 return true;
13894
13895 // See if we can determine the number of arguments from the result.
13896 std::optional<unsigned> NumExpansions =
13897 getSema().getFullyPackExpandedSize(OutPattern.getArgument());
13898 if (!NumExpansions) {
13899 // No: we must be in an alias template expansion, and we're going to need
13900 // to actually expand the packs.
13901 Result = std::nullopt;
13902 break;
13903 }
13904
13905 Result = *Result + *NumExpansions;
13906 }
13907
13908 // Common case: we could determine the number of expansions without
13909 // substituting.
13910 if (Result)
13911 return getDerived().RebuildSizeOfPackExpr(
13912 E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
13913 *Result, std::nullopt);
13914
13915 TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
13916 E->getPackLoc());
13917 {
13918 TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
13919 typedef TemplateArgumentLocInventIterator<
13920 Derived, const TemplateArgument*> PackLocIterator;
13921 if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
13922 PackLocIterator(*this, PackArgs.end()),
13923 TransformedPackArgs, /*Uneval*/true))
13924 return ExprError();
13925 }
13926
13927 // Check whether we managed to fully-expand the pack.
13928 // FIXME: Is it possible for us to do so and not hit the early exit path?
13929 SmallVector<TemplateArgument, 8> Args;
13930 bool PartialSubstitution = false;
13931 for (auto &Loc : TransformedPackArgs.arguments()) {
13932 Args.push_back(Loc.getArgument());
13933 if (Loc.getArgument().isPackExpansion())
13934 PartialSubstitution = true;
13935 }
13936
13937 if (PartialSubstitution)
13938 return getDerived().RebuildSizeOfPackExpr(
13939 E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
13940 std::nullopt, Args);
13941
13942 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13943 E->getPackLoc(), E->getRParenLoc(),
13944 Args.size(), std::nullopt);
13945}
13946
13947template<typename Derived>
13948ExprResult
13949TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
13950 SubstNonTypeTemplateParmPackExpr *E) {
13951 // Default behavior is to do nothing with this transformation.
13952 return E;
13953}
13954
13955template<typename Derived>
13956ExprResult
13957TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
13958 SubstNonTypeTemplateParmExpr *E) {
13959 // Default behavior is to do nothing with this transformation.
13960 return E;
13961}
13962
13963template<typename Derived>
13964ExprResult
13965TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
13966 // Default behavior is to do nothing with this transformation.
13967 return E;
13968}
13969
13970template<typename Derived>
13971ExprResult
13972TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
13973 MaterializeTemporaryExpr *E) {
13974 return getDerived().TransformExpr(E->getSubExpr());
13975}
13976
13977template<typename Derived>
13978ExprResult
13979TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
13980 UnresolvedLookupExpr *Callee = nullptr;
13981 if (Expr *OldCallee = E->getCallee()) {
13982 ExprResult CalleeResult = getDerived().TransformExpr(OldCallee);
13983 if (CalleeResult.isInvalid())
13984 return ExprError();
13985 Callee = cast<UnresolvedLookupExpr>(CalleeResult.get());
13986 }
13987
13988 Expr *Pattern = E->getPattern();
13989
13990 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13991 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
13992 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 13992, __extension__ __PRETTY_FUNCTION__
))
;
13993
13994 // Determine whether the set of unexpanded parameter packs can and should
13995 // be expanded.
13996 bool Expand = true;
13997 bool RetainExpansion = false;
13998 std::optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
13999 NumExpansions = OrigNumExpansions;
14000 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
14001 Pattern->getSourceRange(),
14002 Unexpanded,
14003 Expand, RetainExpansion,
14004 NumExpansions))
14005 return true;
14006
14007 if (!Expand) {
14008 // Do not expand any packs here, just transform and rebuild a fold
14009 // expression.
14010 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14011
14012 ExprResult LHS =
14013 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
14014 if (LHS.isInvalid())
14015 return true;
14016
14017 ExprResult RHS =
14018 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
14019 if (RHS.isInvalid())
14020 return true;
14021
14022 if (!getDerived().AlwaysRebuild() &&
14023 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
14024 return E;
14025
14026 return getDerived().RebuildCXXFoldExpr(
14027 Callee, E->getBeginLoc(), LHS.get(), E->getOperator(),
14028 E->getEllipsisLoc(), RHS.get(), E->getEndLoc(), NumExpansions);
14029 }
14030
14031 // Formally a fold expression expands to nested parenthesized expressions.
14032 // Enforce this limit to avoid creating trees so deep we can't safely traverse
14033 // them.
14034 if (NumExpansions && SemaRef.getLangOpts().BracketDepth < NumExpansions) {
14035 SemaRef.Diag(E->getEllipsisLoc(),
14036 clang::diag::err_fold_expression_limit_exceeded)
14037 << *NumExpansions << SemaRef.getLangOpts().BracketDepth
14038 << E->getSourceRange();
14039 SemaRef.Diag(E->getEllipsisLoc(), diag::note_bracket_depth);
14040 return ExprError();
14041 }
14042
14043 // The transform has determined that we should perform an elementwise
14044 // expansion of the pattern. Do so.
14045 ExprResult Result = getDerived().TransformExpr(E->getInit());
14046 if (Result.isInvalid())
14047 return true;
14048 bool LeftFold = E->isLeftFold();
14049
14050 // If we're retaining an expansion for a right fold, it is the innermost
14051 // component and takes the init (if any).
14052 if (!LeftFold && RetainExpansion) {
14053 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
14054
14055 ExprResult Out = getDerived().TransformExpr(Pattern);
14056 if (Out.isInvalid())
14057 return true;
14058
14059 Result = getDerived().RebuildCXXFoldExpr(
14060 Callee, E->getBeginLoc(), Out.get(), E->getOperator(),
14061 E->getEllipsisLoc(), Result.get(), E->getEndLoc(), OrigNumExpansions);
14062 if (Result.isInvalid())
14063 return true;
14064 }
14065
14066 for (unsigned I = 0; I != *NumExpansions; ++I) {
14067 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
14068 getSema(), LeftFold ? I : *NumExpansions - I - 1);
14069 ExprResult Out = getDerived().TransformExpr(Pattern);
14070 if (Out.isInvalid())
14071 return true;
14072
14073 if (Out.get()->containsUnexpandedParameterPack()) {
14074 // We still have a pack; retain a pack expansion for this slice.
14075 Result = getDerived().RebuildCXXFoldExpr(
14076 Callee, E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
14077 E->getOperator(), E->getEllipsisLoc(),
14078 LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
14079 OrigNumExpansions);
14080 } else if (Result.isUsable()) {
14081 // We've got down to a single element; build a binary operator.
14082 Expr *LHS = LeftFold ? Result.get() : Out.get();
14083 Expr *RHS = LeftFold ? Out.get() : Result.get();
14084 if (Callee)
14085 Result = getDerived().RebuildCXXOperatorCallExpr(
14086 BinaryOperator::getOverloadedOperator(E->getOperator()),
14087 E->getEllipsisLoc(), Callee, LHS, RHS);
14088 else
14089 Result = getDerived().RebuildBinaryOperator(E->getEllipsisLoc(),
14090 E->getOperator(), LHS, RHS);
14091 } else
14092 Result = Out;
14093
14094 if (Result.isInvalid())
14095 return true;
14096 }
14097
14098 // If we're retaining an expansion for a left fold, it is the outermost
14099 // component and takes the complete expansion so far as its init (if any).
14100 if (LeftFold && RetainExpansion) {
14101 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
14102
14103 ExprResult Out = getDerived().TransformExpr(Pattern);
14104 if (Out.isInvalid())
14105 return true;
14106
14107 Result = getDerived().RebuildCXXFoldExpr(
14108 Callee, E->getBeginLoc(), Result.get(), E->getOperator(),
14109 E->getEllipsisLoc(), Out.get(), E->getEndLoc(), OrigNumExpansions);
14110 if (Result.isInvalid())
14111 return true;
14112 }
14113
14114 // If we had no init and an empty pack, and we're not retaining an expansion,
14115 // then produce a fallback value or error.
14116 if (Result.isUnset())
14117 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
14118 E->getOperator());
14119
14120 return Result;
14121}
14122
14123template <typename Derived>
14124ExprResult
14125TreeTransform<Derived>::TransformCXXParenListInitExpr(CXXParenListInitExpr *E) {
14126 SmallVector<Expr *, 4> TransformedInits;
14127 ArrayRef<Expr *> InitExprs = E->getInitExprs();
14128 if (TransformExprs(InitExprs.data(), InitExprs.size(), true,
14129 TransformedInits))
14130 return ExprError();
14131
14132 return getDerived().RebuildParenListExpr(E->getBeginLoc(), TransformedInits,
14133 E->getEndLoc());
14134}
14135
14136template<typename Derived>
14137ExprResult
14138TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
14139 CXXStdInitializerListExpr *E) {
14140 return getDerived().TransformExpr(E->getSubExpr());
14141}
14142
14143template<typename Derived>
14144ExprResult
14145TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
14146 return SemaRef.MaybeBindToTemporary(E);
14147}
14148
14149template<typename Derived>
14150ExprResult
14151TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
14152 return E;
14153}
14154
14155template<typename Derived>
14156ExprResult
14157TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
14158 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
14159 if (SubExpr.isInvalid())
14160 return ExprError();
14161
14162 if (!getDerived().AlwaysRebuild() &&
14163 SubExpr.get() == E->getSubExpr())
14164 return E;
14165
14166 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
14167}
14168
14169template<typename Derived>
14170ExprResult
14171TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
14172 // Transform each of the elements.
14173 SmallVector<Expr *, 8> Elements;
14174 bool ArgChanged = false;
14175 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
14176 /*IsCall=*/false, Elements, &ArgChanged))
14177 return ExprError();
14178
14179 if (!getDerived().AlwaysRebuild() && !ArgChanged)
14180 return SemaRef.MaybeBindToTemporary(E);
14181
14182 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
14183 Elements.data(),
14184 Elements.size());
14185}
14186
14187template<typename Derived>
14188ExprResult
14189TreeTransform<Derived>::TransformObjCDictionaryLiteral(
14190 ObjCDictionaryLiteral *E) {
14191 // Transform each of the elements.
14192 SmallVector<ObjCDictionaryElement, 8> Elements;
14193 bool ArgChanged = false;
14194 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
14195 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
14196
14197 if (OrigElement.isPackExpansion()) {
14198 // This key/value element is a pack expansion.
14199 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14200 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
14201 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
14202 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 14202, __extension__ __PRETTY_FUNCTION__
))
;
14203
14204 // Determine whether the set of unexpanded parameter packs can
14205 // and should be expanded.
14206 bool Expand = true;
14207 bool RetainExpansion = false;
14208 std::optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
14209 std::optional<unsigned> NumExpansions = OrigNumExpansions;
14210 SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
14211 OrigElement.Value->getEndLoc());
14212 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
14213 PatternRange, Unexpanded, Expand,
14214 RetainExpansion, NumExpansions))
14215 return ExprError();
14216
14217 if (!Expand) {
14218 // The transform has determined that we should perform a simple
14219 // transformation on the pack expansion, producing another pack
14220 // expansion.
14221 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14222 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14223 if (Key.isInvalid())
14224 return ExprError();
14225
14226 if (Key.get() != OrigElement.Key)
14227 ArgChanged = true;
14228
14229 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14230 if (Value.isInvalid())
14231 return ExprError();
14232
14233 if (Value.get() != OrigElement.Value)
14234 ArgChanged = true;
14235
14236 ObjCDictionaryElement Expansion = {
14237 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
14238 };
14239 Elements.push_back(Expansion);
14240 continue;
14241 }
14242
14243 // Record right away that the argument was changed. This needs
14244 // to happen even if the array expands to nothing.
14245 ArgChanged = true;
14246
14247 // The transform has determined that we should perform an elementwise
14248 // expansion of the pattern. Do so.
14249 for (unsigned I = 0; I != *NumExpansions; ++I) {
14250 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
14251 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14252 if (Key.isInvalid())
14253 return ExprError();
14254
14255 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14256 if (Value.isInvalid())
14257 return ExprError();
14258
14259 ObjCDictionaryElement Element = {
14260 Key.get(), Value.get(), SourceLocation(), NumExpansions
14261 };
14262
14263 // If any unexpanded parameter packs remain, we still have a
14264 // pack expansion.
14265 // FIXME: Can this really happen?
14266 if (Key.get()->containsUnexpandedParameterPack() ||
14267 Value.get()->containsUnexpandedParameterPack())
14268 Element.EllipsisLoc = OrigElement.EllipsisLoc;
14269
14270 Elements.push_back(Element);
14271 }
14272
14273 // FIXME: Retain a pack expansion if RetainExpansion is true.
14274
14275 // We've finished with this pack expansion.
14276 continue;
14277 }
14278
14279 // Transform and check key.
14280 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14281 if (Key.isInvalid())
14282 return ExprError();
14283
14284 if (Key.get() != OrigElement.Key)
14285 ArgChanged = true;
14286
14287 // Transform and check value.
14288 ExprResult Value
14289 = getDerived().TransformExpr(OrigElement.Value);
14290 if (Value.isInvalid())
14291 return ExprError();
14292
14293 if (Value.get() != OrigElement.Value)
14294 ArgChanged = true;
14295
14296 ObjCDictionaryElement Element = {Key.get(), Value.get(), SourceLocation(),
14297 std::nullopt};
14298 Elements.push_back(Element);
14299 }
14300
14301 if (!getDerived().AlwaysRebuild() && !ArgChanged)
14302 return SemaRef.MaybeBindToTemporary(E);
14303
14304 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
14305 Elements);
14306}
14307
14308template<typename Derived>
14309ExprResult
14310TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
14311 TypeSourceInfo *EncodedTypeInfo
14312 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
14313 if (!EncodedTypeInfo)
14314 return ExprError();
14315
14316 if (!getDerived().AlwaysRebuild() &&
14317 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
14318 return E;
14319
14320 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
14321 EncodedTypeInfo,
14322 E->getRParenLoc());
14323}
14324
14325template<typename Derived>
14326ExprResult TreeTransform<Derived>::
14327TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
14328 // This is a kind of implicit conversion, and it needs to get dropped
14329 // and recomputed for the same general reasons that ImplicitCastExprs
14330 // do, as well a more specific one: this expression is only valid when
14331 // it appears *immediately* as an argument expression.
14332 return getDerived().TransformExpr(E->getSubExpr());
14333}
14334
14335template<typename Derived>
14336ExprResult TreeTransform<Derived>::
14337TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
14338 TypeSourceInfo *TSInfo
14339 = getDerived().TransformType(E->getTypeInfoAsWritten());
14340 if (!TSInfo)
14341 return ExprError();
14342
14343 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
14344 if (Result.isInvalid())
14345 return ExprError();
14346
14347 if (!getDerived().AlwaysRebuild() &&
14348 TSInfo == E->getTypeInfoAsWritten() &&
14349 Result.get() == E->getSubExpr())
14350 return E;
14351
14352 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
14353 E->getBridgeKeywordLoc(), TSInfo,
14354 Result.get());
14355}
14356
14357template <typename Derived>
14358ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
14359 ObjCAvailabilityCheckExpr *E) {
14360 return E;
14361}
14362
14363template<typename Derived>
14364ExprResult
14365TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
14366 // Transform arguments.
14367 bool ArgChanged = false;
14368 SmallVector<Expr*, 8> Args;
14369 Args.reserve(E->getNumArgs());
14370 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
14371 &ArgChanged))
14372 return ExprError();
14373
14374 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
14375 // Class message: transform the receiver type.
14376 TypeSourceInfo *ReceiverTypeInfo
14377 = getDerived().TransformType(E->getClassReceiverTypeInfo());
14378 if (!ReceiverTypeInfo)
14379 return ExprError();
14380
14381 // If nothing changed, just retain the existing message send.
14382 if (!getDerived().AlwaysRebuild() &&
14383 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
14384 return SemaRef.MaybeBindToTemporary(E);
14385
14386 // Build a new class message send.
14387 SmallVector<SourceLocation, 16> SelLocs;
14388 E->getSelectorLocs(SelLocs);
14389 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
14390 E->getSelector(),
14391 SelLocs,
14392 E->getMethodDecl(),
14393 E->getLeftLoc(),
14394 Args,
14395 E->getRightLoc());
14396 }
14397 else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
14398 E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14399 if (!E->getMethodDecl())
14400 return ExprError();
14401
14402 // Build a new class message send to 'super'.
14403 SmallVector<SourceLocation, 16> SelLocs;
14404 E->getSelectorLocs(SelLocs);
14405 return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
14406 E->getSelector(),
14407 SelLocs,
14408 E->getReceiverType(),
14409 E->getMethodDecl(),
14410 E->getLeftLoc(),
14411 Args,
14412 E->getRightLoc());
14413 }
14414
14415 // Instance message: transform the receiver
14416 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&(static_cast <bool> (E->getReceiverKind() == ObjCMessageExpr
::Instance && "Only class and instance messages may be instantiated"
) ? void (0) : __assert_fail ("E->getReceiverKind() == ObjCMessageExpr::Instance && \"Only class and instance messages may be instantiated\""
, "clang/lib/Sema/TreeTransform.h", 14417, __extension__ __PRETTY_FUNCTION__
))
14417 "Only class and instance messages may be instantiated")(static_cast <bool> (E->getReceiverKind() == ObjCMessageExpr
::Instance && "Only class and instance messages may be instantiated"
) ? void (0) : __assert_fail ("E->getReceiverKind() == ObjCMessageExpr::Instance && \"Only class and instance messages may be instantiated\""
, "clang/lib/Sema/TreeTransform.h", 14417, __extension__ __PRETTY_FUNCTION__
))
;
14418 ExprResult Receiver
14419 = getDerived().TransformExpr(E->getInstanceReceiver());
14420 if (Receiver.isInvalid())
14421 return ExprError();
14422
14423 // If nothing changed, just retain the existing message send.
14424 if (!getDerived().AlwaysRebuild() &&
14425 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
14426 return SemaRef.MaybeBindToTemporary(E);
14427
14428 // Build a new instance message send.
14429 SmallVector<SourceLocation, 16> SelLocs;
14430 E->getSelectorLocs(SelLocs);
14431 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
14432 E->getSelector(),
14433 SelLocs,
14434 E->getMethodDecl(),
14435 E->getLeftLoc(),
14436 Args,
14437 E->getRightLoc());
14438}
14439
14440template<typename Derived>
14441ExprResult
14442TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
14443 return E;
14444}
14445
14446template<typename Derived>
14447ExprResult
14448TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
14449 return E;
14450}
14451
14452template<typename Derived>
14453ExprResult
14454TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
14455 // Transform the base expression.
14456 ExprResult Base = getDerived().TransformExpr(E->getBase());
14457 if (Base.isInvalid())
14458 return ExprError();
14459
14460 // We don't need to transform the ivar; it will never change.
14461
14462 // If nothing changed, just retain the existing expression.
14463 if (!getDerived().AlwaysRebuild() &&
14464 Base.get() == E->getBase())
14465 return E;
14466
14467 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
14468 E->getLocation(),
14469 E->isArrow(), E->isFreeIvar());
14470}
14471
14472template<typename Derived>
14473ExprResult
14474TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
14475 // 'super' and types never change. Property never changes. Just
14476 // retain the existing expression.
14477 if (!E->isObjectReceiver())
14478 return E;
14479
14480 // Transform the base expression.
14481 ExprResult Base = getDerived().TransformExpr(E->getBase());
14482 if (Base.isInvalid())
14483 return ExprError();
14484
14485 // We don't need to transform the property; it will never change.
14486
14487 // If nothing changed, just retain the existing expression.
14488 if (!getDerived().AlwaysRebuild() &&
14489 Base.get() == E->getBase())
14490 return E;
14491
14492 if (E->isExplicitProperty())
14493 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14494 E->getExplicitProperty(),
14495 E->getLocation());
14496
14497 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14498 SemaRef.Context.PseudoObjectTy,
14499 E->getImplicitPropertyGetter(),
14500 E->getImplicitPropertySetter(),
14501 E->getLocation());
14502}
14503
14504template<typename Derived>
14505ExprResult
14506TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
14507 // Transform the base expression.
14508 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
14509 if (Base.isInvalid())
14510 return ExprError();
14511
14512 // Transform the key expression.
14513 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
14514 if (Key.isInvalid())
14515 return ExprError();
14516
14517 // If nothing changed, just retain the existing expression.
14518 if (!getDerived().AlwaysRebuild() &&
14519 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
14520 return E;
14521
14522 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
14523 Base.get(), Key.get(),
14524 E->getAtIndexMethodDecl(),
14525 E->setAtIndexMethodDecl());
14526}
14527
14528template<typename Derived>
14529ExprResult
14530TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
14531 // Transform the base expression.
14532 ExprResult Base = getDerived().TransformExpr(E->getBase());
14533 if (Base.isInvalid())
14534 return ExprError();
14535
14536 // If nothing changed, just retain the existing expression.
14537 if (!getDerived().AlwaysRebuild() &&
14538 Base.get() == E->getBase())
14539 return E;
14540
14541 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
14542 E->getOpLoc(),
14543 E->isArrow());
14544}
14545
14546template<typename Derived>
14547ExprResult
14548TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
14549 bool ArgumentChanged = false;
14550 SmallVector<Expr*, 8> SubExprs;
14551 SubExprs.reserve(E->getNumSubExprs());
14552 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14553 SubExprs, &ArgumentChanged))
14554 return ExprError();
14555
14556 if (!getDerived().AlwaysRebuild() &&
14557 !ArgumentChanged)
14558 return E;
14559
14560 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
14561 SubExprs,
14562 E->getRParenLoc());
14563}
14564
14565template<typename Derived>
14566ExprResult
14567TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
14568 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14569 if (SrcExpr.isInvalid())
14570 return ExprError();
14571
14572 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
14573 if (!Type)
14574 return ExprError();
14575
14576 if (!getDerived().AlwaysRebuild() &&
14577 Type == E->getTypeSourceInfo() &&
14578 SrcExpr.get() == E->getSrcExpr())
14579 return E;
14580
14581 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
14582 SrcExpr.get(), Type,
14583 E->getRParenLoc());
14584}
14585
14586template<typename Derived>
14587ExprResult
14588TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
14589 BlockDecl *oldBlock = E->getBlockDecl();
14590
14591 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
14592 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
14593
14594 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
14595 blockScope->TheDecl->setBlockMissingReturnType(
14596 oldBlock->blockMissingReturnType());
14597
14598 SmallVector<ParmVarDecl*, 4> params;
14599 SmallVector<QualType, 4> paramTypes;
14600
14601 const FunctionProtoType *exprFunctionType = E->getFunctionType();
14602
14603 // Parameter substitution.
14604 Sema::ExtParameterInfoBuilder extParamInfos;
14605 if (getDerived().TransformFunctionTypeParams(
14606 E->getCaretLocation(), oldBlock->parameters(), nullptr,
14607 exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
14608 extParamInfos)) {
14609 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14610 return ExprError();
14611 }
14612
14613 QualType exprResultType =
14614 getDerived().TransformType(exprFunctionType->getReturnType());
14615
14616 auto epi = exprFunctionType->getExtProtoInfo();
14617 epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
14618
14619 QualType functionType =
14620 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
14621 blockScope->FunctionType = functionType;
14622
14623 // Set the parameters on the block decl.
14624 if (!params.empty())
14625 blockScope->TheDecl->setParams(params);
14626
14627 if (!oldBlock->blockMissingReturnType()) {
14628 blockScope->HasImplicitReturnType = false;
14629 blockScope->ReturnType = exprResultType;
14630 }
14631
14632 // Transform the body
14633 StmtResult body = getDerived().TransformStmt(E->getBody());
14634 if (body.isInvalid()) {
14635 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14636 return ExprError();
14637 }
14638
14639#ifndef NDEBUG
14640 // In builds with assertions, make sure that we captured everything we
14641 // captured before.
14642 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
14643 for (const auto &I : oldBlock->captures()) {
14644 VarDecl *oldCapture = I.getVariable();
14645
14646 // Ignore parameter packs.
14647 if (oldCapture->isParameterPack())
14648 continue;
14649
14650 VarDecl *newCapture =
14651 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
14652 oldCapture));
14653 assert(blockScope->CaptureMap.count(newCapture))(static_cast <bool> (blockScope->CaptureMap.count(newCapture
)) ? void (0) : __assert_fail ("blockScope->CaptureMap.count(newCapture)"
, "clang/lib/Sema/TreeTransform.h", 14653, __extension__ __PRETTY_FUNCTION__
))
;
14654 }
14655
14656 // The this pointer may not be captured by the instantiated block, even when
14657 // it's captured by the original block, if the expression causing the
14658 // capture is in the discarded branch of a constexpr if statement.
14659 assert((!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) &&(static_cast <bool> ((!blockScope->isCXXThisCaptured
() || oldBlock->capturesCXXThis()) && "this pointer isn't captured in the old block"
) ? void (0) : __assert_fail ("(!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) && \"this pointer isn't captured in the old block\""
, "clang/lib/Sema/TreeTransform.h", 14660, __extension__ __PRETTY_FUNCTION__
))
14660 "this pointer isn't captured in the old block")(static_cast <bool> ((!blockScope->isCXXThisCaptured
() || oldBlock->capturesCXXThis()) && "this pointer isn't captured in the old block"
) ? void (0) : __assert_fail ("(!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) && \"this pointer isn't captured in the old block\""
, "clang/lib/Sema/TreeTransform.h", 14660, __extension__ __PRETTY_FUNCTION__
))
;
14661 }
14662#endif
14663
14664 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
14665 /*Scope=*/nullptr);
14666}
14667
14668template<typename Derived>
14669ExprResult
14670TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
14671 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14672 if (SrcExpr.isInvalid())
14673 return ExprError();
14674
14675 QualType Type = getDerived().TransformType(E->getType());
14676
14677 return SemaRef.BuildAsTypeExpr(SrcExpr.get(), Type, E->getBuiltinLoc(),
14678 E->getRParenLoc());
14679}
14680
14681template<typename Derived>
14682ExprResult
14683TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
14684 bool ArgumentChanged = false;
14685 SmallVector<Expr*, 8> SubExprs;
14686 SubExprs.reserve(E->getNumSubExprs());
14687 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14688 SubExprs, &ArgumentChanged))
14689 return ExprError();
14690
14691 if (!getDerived().AlwaysRebuild() &&
14692 !ArgumentChanged)
14693 return E;
14694
14695 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
14696 E->getOp(), E->getRParenLoc());
14697}
14698
14699//===----------------------------------------------------------------------===//
14700// Type reconstruction
14701//===----------------------------------------------------------------------===//
14702
14703template<typename Derived>
14704QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
14705 SourceLocation Star) {
14706 return SemaRef.BuildPointerType(PointeeType, Star,
14707 getDerived().getBaseEntity());
14708}
14709
14710template<typename Derived>
14711QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
14712 SourceLocation Star) {
14713 return SemaRef.BuildBlockPointerType(PointeeType, Star,
14714 getDerived().getBaseEntity());
14715}
14716
14717template<typename Derived>
14718QualType
14719TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
14720 bool WrittenAsLValue,
14721 SourceLocation Sigil) {
14722 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
14723 Sigil, getDerived().getBaseEntity());
14724}
14725
14726template<typename Derived>
14727QualType
14728TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
14729 QualType ClassType,
14730 SourceLocation Sigil) {
14731 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
14732 getDerived().getBaseEntity());
14733}
14734
14735template<typename Derived>
14736QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
14737 const ObjCTypeParamDecl *Decl,
14738 SourceLocation ProtocolLAngleLoc,
14739 ArrayRef<ObjCProtocolDecl *> Protocols,
14740 ArrayRef<SourceLocation> ProtocolLocs,
14741 SourceLocation ProtocolRAngleLoc) {
14742 return SemaRef.BuildObjCTypeParamType(Decl,
14743 ProtocolLAngleLoc, Protocols,
14744 ProtocolLocs, ProtocolRAngleLoc,
14745 /*FailOnError=*/true);
14746}
14747
14748template<typename Derived>
14749QualType TreeTransform<Derived>::RebuildObjCObjectType(
14750 QualType BaseType,
14751 SourceLocation Loc,
14752 SourceLocation TypeArgsLAngleLoc,
14753 ArrayRef<TypeSourceInfo *> TypeArgs,
14754 SourceLocation TypeArgsRAngleLoc,
14755 SourceLocation ProtocolLAngleLoc,
14756 ArrayRef<ObjCProtocolDecl *> Protocols,
14757 ArrayRef<SourceLocation> ProtocolLocs,
14758 SourceLocation ProtocolRAngleLoc) {
14759 return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc, TypeArgs,
14760 TypeArgsRAngleLoc, ProtocolLAngleLoc,
14761 Protocols, ProtocolLocs, ProtocolRAngleLoc,
14762 /*FailOnError=*/true,
14763 /*Rebuilding=*/true);
14764}
14765
14766template<typename Derived>
14767QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
14768 QualType PointeeType,
14769 SourceLocation Star) {
14770 return SemaRef.Context.getObjCObjectPointerType(PointeeType);
14771}
14772
14773template<typename Derived>
14774QualType
14775TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
14776 ArrayType::ArraySizeModifier SizeMod,
14777 const llvm::APInt *Size,
14778 Expr *SizeExpr,
14779 unsigned IndexTypeQuals,
14780 SourceRange BracketsRange) {
14781 if (SizeExpr || !Size)
14782 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
14783 IndexTypeQuals, BracketsRange,
14784 getDerived().getBaseEntity());
14785
14786 QualType Types[] = {
14787 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
14788 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
14789 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
14790 };
14791 QualType SizeType;
14792 for (const auto &T : Types)
14793 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(T)) {
14794 SizeType = T;
14795 break;
14796 }
14797
14798 // Note that we can return a VariableArrayType here in the case where
14799 // the element type was a dependent VariableArrayType.
14800 IntegerLiteral *ArraySize
14801 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
14802 /*FIXME*/BracketsRange.getBegin());
14803 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
14804 IndexTypeQuals, BracketsRange,
14805 getDerived().getBaseEntity());
14806}
14807
14808template<typename Derived>
14809QualType
14810TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
14811 ArrayType::ArraySizeModifier SizeMod,
14812 const llvm::APInt &Size,
14813 Expr *SizeExpr,
14814 unsigned IndexTypeQuals,
14815 SourceRange BracketsRange) {
14816 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
14817 IndexTypeQuals, BracketsRange);
14818}
14819
14820template<typename Derived>
14821QualType
14822TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
14823 ArrayType::ArraySizeModifier SizeMod,
14824 unsigned IndexTypeQuals,
14825 SourceRange BracketsRange) {
14826 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
14827 IndexTypeQuals, BracketsRange);
14828}
14829
14830template<typename Derived>
14831QualType
14832TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
14833 ArrayType::ArraySizeModifier SizeMod,
14834 Expr *SizeExpr,
14835 unsigned IndexTypeQuals,
14836 SourceRange BracketsRange) {
14837 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14838 SizeExpr,
14839 IndexTypeQuals, BracketsRange);
14840}
14841
14842template<typename Derived>
14843QualType
14844TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
14845 ArrayType::ArraySizeModifier SizeMod,
14846 Expr *SizeExpr,
14847 unsigned IndexTypeQuals,
14848 SourceRange BracketsRange) {
14849 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14850 SizeExpr,
14851 IndexTypeQuals, BracketsRange);
14852}
14853
14854template <typename Derived>
14855QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
14856 QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
14857 return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
14858 AttributeLoc);
14859}
14860
14861template <typename Derived>
14862QualType
14863TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
14864 unsigned NumElements,
14865 VectorType::VectorKind VecKind) {
14866 // FIXME: semantic checking!
14867 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
14868}
14869
14870template <typename Derived>
14871QualType TreeTransform<Derived>::RebuildDependentVectorType(
14872 QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
14873 VectorType::VectorKind VecKind) {
14874 return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
14875}
14876
14877template<typename Derived>
14878QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
14879 unsigned NumElements,
14880 SourceLocation AttributeLoc) {
14881 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14882 NumElements, true);
14883 IntegerLiteral *VectorSize
14884 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
14885 AttributeLoc);
14886 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
14887}
14888
14889template<typename Derived>
14890QualType
14891TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
14892 Expr *SizeExpr,
14893 SourceLocation AttributeLoc) {
14894 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
14895}
14896
14897template <typename Derived>
14898QualType TreeTransform<Derived>::RebuildConstantMatrixType(
14899 QualType ElementType, unsigned NumRows, unsigned NumColumns) {
14900 return SemaRef.Context.getConstantMatrixType(ElementType, NumRows,
14901 NumColumns);
14902}
14903
14904template <typename Derived>
14905QualType TreeTransform<Derived>::RebuildDependentSizedMatrixType(
14906 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr,
14907 SourceLocation AttributeLoc) {
14908 return SemaRef.BuildMatrixType(ElementType, RowExpr, ColumnExpr,
14909 AttributeLoc);
14910}
14911
14912template<typename Derived>
14913QualType TreeTransform<Derived>::RebuildFunctionProtoType(
14914 QualType T,
14915 MutableArrayRef<QualType> ParamTypes,
14916 const FunctionProtoType::ExtProtoInfo &EPI) {
14917 return SemaRef.BuildFunctionType(T, ParamTypes,
14918 getDerived().getBaseLocation(),
14919 getDerived().getBaseEntity(),
14920 EPI);
14921}
14922
14923template<typename Derived>
14924QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
14925 return SemaRef.Context.getFunctionNoProtoType(T);
14926}
14927
14928template<typename Derived>
14929QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
14930 Decl *D) {
14931 assert(D && "no decl found")(static_cast <bool> (D && "no decl found") ? void
(0) : __assert_fail ("D && \"no decl found\"", "clang/lib/Sema/TreeTransform.h"
, 14931, __extension__ __PRETTY_FUNCTION__))
;
14932 if (D->isInvalidDecl()) return QualType();
14933
14934 // FIXME: Doesn't account for ObjCInterfaceDecl!
14935 if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
14936 // A valid resolved using typename pack expansion decl can have multiple
14937 // UsingDecls, but they must each have exactly one type, and it must be
14938 // the same type in every case. But we must have at least one expansion!
14939 if (UPD->expansions().empty()) {
14940 getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
14941 << UPD->isCXXClassMember() << UPD;
14942 return QualType();
14943 }
14944
14945 // We might still have some unresolved types. Try to pick a resolved type
14946 // if we can. The final instantiation will check that the remaining
14947 // unresolved types instantiate to the type we pick.
14948 QualType FallbackT;
14949 QualType T;
14950 for (auto *E : UPD->expansions()) {
14951 QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
14952 if (ThisT.isNull())
14953 continue;
14954 else if (ThisT->getAs<UnresolvedUsingType>())
14955 FallbackT = ThisT;
14956 else if (T.isNull())
14957 T = ThisT;
14958 else
14959 assert(getSema().Context.hasSameType(ThisT, T) &&(static_cast <bool> (getSema().Context.hasSameType(ThisT
, T) && "mismatched resolved types in using pack expansion"
) ? void (0) : __assert_fail ("getSema().Context.hasSameType(ThisT, T) && \"mismatched resolved types in using pack expansion\""
, "clang/lib/Sema/TreeTransform.h", 14960, __extension__ __PRETTY_FUNCTION__
))
14960 "mismatched resolved types in using pack expansion")(static_cast <bool> (getSema().Context.hasSameType(ThisT
, T) && "mismatched resolved types in using pack expansion"
) ? void (0) : __assert_fail ("getSema().Context.hasSameType(ThisT, T) && \"mismatched resolved types in using pack expansion\""
, "clang/lib/Sema/TreeTransform.h", 14960, __extension__ __PRETTY_FUNCTION__
))
;
14961 }
14962 return T.isNull() ? FallbackT : T;
14963 } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
14964 assert(Using->hasTypename() &&(static_cast <bool> (Using->hasTypename() &&
"UnresolvedUsingTypenameDecl transformed to non-typename using"
) ? void (0) : __assert_fail ("Using->hasTypename() && \"UnresolvedUsingTypenameDecl transformed to non-typename using\""
, "clang/lib/Sema/TreeTransform.h", 14965, __extension__ __PRETTY_FUNCTION__
))
14965 "UnresolvedUsingTypenameDecl transformed to non-typename using")(static_cast <bool> (Using->hasTypename() &&
"UnresolvedUsingTypenameDecl transformed to non-typename using"
) ? void (0) : __assert_fail ("Using->hasTypename() && \"UnresolvedUsingTypenameDecl transformed to non-typename using\""
, "clang/lib/Sema/TreeTransform.h", 14965, __extension__ __PRETTY_FUNCTION__
))
;
14966
14967 // A valid resolved using typename decl points to exactly one type decl.
14968 assert(++Using->shadow_begin() == Using->shadow_end())(static_cast <bool> (++Using->shadow_begin() == Using
->shadow_end()) ? void (0) : __assert_fail ("++Using->shadow_begin() == Using->shadow_end()"
, "clang/lib/Sema/TreeTransform.h", 14968, __extension__ __PRETTY_FUNCTION__
))
;
14969
14970 UsingShadowDecl *Shadow = *Using->shadow_begin();
14971 if (SemaRef.DiagnoseUseOfDecl(Shadow->getTargetDecl(), Loc))
14972 return QualType();
14973 return SemaRef.Context.getUsingType(
14974 Shadow, SemaRef.Context.getTypeDeclType(
14975 cast<TypeDecl>(Shadow->getTargetDecl())));
14976 } else {
14977 assert(isa<UnresolvedUsingTypenameDecl>(D) &&(static_cast <bool> (isa<UnresolvedUsingTypenameDecl
>(D) && "UnresolvedUsingTypenameDecl transformed to non-using decl"
) ? void (0) : __assert_fail ("isa<UnresolvedUsingTypenameDecl>(D) && \"UnresolvedUsingTypenameDecl transformed to non-using decl\""
, "clang/lib/Sema/TreeTransform.h", 14978, __extension__ __PRETTY_FUNCTION__
))
14978 "UnresolvedUsingTypenameDecl transformed to non-using decl")(static_cast <bool> (isa<UnresolvedUsingTypenameDecl
>(D) && "UnresolvedUsingTypenameDecl transformed to non-using decl"
) ? void (0) : __assert_fail ("isa<UnresolvedUsingTypenameDecl>(D) && \"UnresolvedUsingTypenameDecl transformed to non-using decl\""
, "clang/lib/Sema/TreeTransform.h", 14978, __extension__ __PRETTY_FUNCTION__
))
;
14979 return SemaRef.Context.getTypeDeclType(
14980 cast<UnresolvedUsingTypenameDecl>(D));
14981 }
14982}
14983
14984template <typename Derived>
14985QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E, SourceLocation,
14986 TypeOfKind Kind) {
14987 return SemaRef.BuildTypeofExprType(E, Kind);
14988}
14989
14990template<typename Derived>
14991QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying,
14992 TypeOfKind Kind) {
14993 return SemaRef.Context.getTypeOfType(Underlying, Kind);
14994}
14995
14996template <typename Derived>
14997QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E, SourceLocation) {
14998 return SemaRef.BuildDecltypeType(E);
14999}
15000
15001template<typename Derived>
15002QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
15003 UnaryTransformType::UTTKind UKind,
15004 SourceLocation Loc) {
15005 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
15006}
15007
15008template<typename Derived>
15009QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
15010 TemplateName Template,
15011 SourceLocation TemplateNameLoc,
15012 TemplateArgumentListInfo &TemplateArgs) {
15013 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
15014}
15015
15016template<typename Derived>
15017QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
15018 SourceLocation KWLoc) {
15019 return SemaRef.BuildAtomicType(ValueType, KWLoc);
15020}
15021
15022template<typename Derived>
15023QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
15024 SourceLocation KWLoc,
15025 bool isReadPipe) {
15026 return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
15027 : SemaRef.BuildWritePipeType(ValueType, KWLoc);
15028}
15029
15030template <typename Derived>
15031QualType TreeTransform<Derived>::RebuildBitIntType(bool IsUnsigned,
15032 unsigned NumBits,
15033 SourceLocation Loc) {
15034 llvm::APInt NumBitsAP(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
15035 NumBits, true);
15036 IntegerLiteral *Bits = IntegerLiteral::Create(SemaRef.Context, NumBitsAP,
15037 SemaRef.Context.IntTy, Loc);
15038 return SemaRef.BuildBitIntType(IsUnsigned, Bits, Loc);
15039}
15040
15041template <typename Derived>
15042QualType TreeTransform<Derived>::RebuildDependentBitIntType(
15043 bool IsUnsigned, Expr *NumBitsExpr, SourceLocation Loc) {
15044 return SemaRef.BuildBitIntType(IsUnsigned, NumBitsExpr, Loc);
15045}
15046
15047template<typename Derived>
15048TemplateName
15049TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15050 bool TemplateKW,
15051 TemplateDecl *Template) {
15052 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
15053 TemplateName(Template));
15054}
15055
15056template<typename Derived>
15057TemplateName
15058TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15059 SourceLocation TemplateKWLoc,
15060 const IdentifierInfo &Name,
15061 SourceLocation NameLoc,
15062 QualType ObjectType,
15063 NamedDecl *FirstQualifierInScope,
15064 bool AllowInjectedClassName) {
15065 UnqualifiedId TemplateName;
15066 TemplateName.setIdentifier(&Name, NameLoc);
15067 Sema::TemplateTy Template;
15068 getSema().ActOnTemplateName(/*Scope=*/nullptr, SS, TemplateKWLoc,
15069 TemplateName, ParsedType::make(ObjectType),
15070 /*EnteringContext=*/false, Template,
15071 AllowInjectedClassName);
15072 return Template.get();
15073}
15074
15075template<typename Derived>
15076TemplateName
15077TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15078 SourceLocation TemplateKWLoc,
15079 OverloadedOperatorKind Operator,
15080 SourceLocation NameLoc,
15081 QualType ObjectType,
15082 bool AllowInjectedClassName) {
15083 UnqualifiedId Name;
15084 // FIXME: Bogus location information.
15085 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
15086 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
15087 Sema::TemplateTy Template;
15088 getSema().ActOnTemplateName(
15089 /*Scope=*/nullptr, SS, TemplateKWLoc, Name, ParsedType::make(ObjectType),
15090 /*EnteringContext=*/false, Template, AllowInjectedClassName);
15091 return Template.get();
15092}
15093
15094template<typename Derived>
15095ExprResult
15096TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
15097 SourceLocation OpLoc,
15098 Expr *OrigCallee,
15099 Expr *First,
15100 Expr *Second) {
15101 Expr *Callee = OrigCallee->IgnoreParenCasts();
15102 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
15103
15104 if (First->getObjectKind() == OK_ObjCProperty) {
15105 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15106 if (BinaryOperator::isAssignmentOp(Opc))
15107 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
15108 First, Second);
15109 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
15110 if (Result.isInvalid())
15111 return ExprError();
15112 First = Result.get();
15113 }
15114
15115 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
15116 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
15117 if (Result.isInvalid())
15118 return ExprError();
15119 Second = Result.get();
15120 }
15121
15122 // Determine whether this should be a builtin operation.
15123 if (Op == OO_Subscript) {
15124 if (!First->getType()->isOverloadableType() &&
15125 !Second->getType()->isOverloadableType())
15126 return getSema().CreateBuiltinArraySubscriptExpr(
15127 First, Callee->getBeginLoc(), Second, OpLoc);
15128 } else if (Op == OO_Arrow) {
15129 // It is possible that the type refers to a RecoveryExpr created earlier
15130 // in the tree transformation.
15131 if (First->getType()->isDependentType())
15132 return ExprError();
15133 // -> is never a builtin operation.
15134 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
15135 } else if (Second == nullptr || isPostIncDec) {
15136 if (!First->getType()->isOverloadableType() ||
15137 (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
15138 // The argument is not of overloadable type, or this is an expression
15139 // of the form &Class::member, so try to create a built-in unary
15140 // operation.
15141 UnaryOperatorKind Opc
15142 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15143
15144 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
15145 }
15146 } else {
15147 if (!First->getType()->isOverloadableType() &&
15148 !Second->getType()->isOverloadableType()) {
15149 // Neither of the arguments is an overloadable type, so try to
15150 // create a built-in binary operation.
15151 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15152 ExprResult Result
15153 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
15154 if (Result.isInvalid())
15155 return ExprError();
15156
15157 return Result;
15158 }
15159 }
15160
15161 // Compute the transformed set of functions (and function templates) to be
15162 // used during overload resolution.
15163 UnresolvedSet<16> Functions;
15164 bool RequiresADL;
15165
15166 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
15167 Functions.append(ULE->decls_begin(), ULE->decls_end());
15168 // If the overload could not be resolved in the template definition
15169 // (because we had a dependent argument), ADL is performed as part of
15170 // template instantiation.
15171 RequiresADL = ULE->requiresADL();
15172 } else {
15173 // If we've resolved this to a particular non-member function, just call
15174 // that function. If we resolved it to a member function,
15175 // CreateOverloaded* will find that function for us.
15176 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
15177 if (!isa<CXXMethodDecl>(ND))
15178 Functions.addDecl(ND);
15179 RequiresADL = false;
15180 }
15181
15182 // Add any functions found via argument-dependent lookup.
15183 Expr *Args[2] = { First, Second };
15184 unsigned NumArgs = 1 + (Second != nullptr);
15185
15186 // Create the overloaded operator invocation for unary operators.
15187 if (NumArgs == 1 || isPostIncDec) {
15188 UnaryOperatorKind Opc
15189 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15190 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
15191 RequiresADL);
15192 }
15193
15194 if (Op == OO_Subscript) {
15195 SourceLocation LBrace;
15196 SourceLocation RBrace;
15197
15198 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
15199 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
15200 LBrace = NameLoc.getCXXOperatorNameBeginLoc();
15201 RBrace = NameLoc.getCXXOperatorNameEndLoc();
15202 } else {
15203 LBrace = Callee->getBeginLoc();
15204 RBrace = OpLoc;
15205 }
15206
15207 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
15208 First, Second);
15209 }
15210
15211 // Create the overloaded operator invocation for binary operators.
15212 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15213 ExprResult Result = SemaRef.CreateOverloadedBinOp(
15214 OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
15215 if (Result.isInvalid())
15216 return ExprError();
15217
15218 return Result;
15219}
15220
15221template<typename Derived>
15222ExprResult
15223TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
15224 SourceLocation OperatorLoc,
15225 bool isArrow,
15226 CXXScopeSpec &SS,
15227 TypeSourceInfo *ScopeType,
15228 SourceLocation CCLoc,
15229 SourceLocation TildeLoc,
15230 PseudoDestructorTypeStorage Destroyed) {
15231 QualType BaseType = Base->getType();
15232 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
15233 (!isArrow && !BaseType->getAs<RecordType>()) ||
15234 (isArrow && BaseType->getAs<PointerType>() &&
15235 !BaseType->castAs<PointerType>()->getPointeeType()
15236 ->template getAs<RecordType>())){
15237 // This pseudo-destructor expression is still a pseudo-destructor.
15238 return SemaRef.BuildPseudoDestructorExpr(
15239 Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
15240 CCLoc, TildeLoc, Destroyed);
15241 }
15242
15243 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
15244 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
15245 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
15246 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
15247 NameInfo.setNamedTypeInfo(DestroyedType);
15248
15249 // The scope type is now known to be a valid nested name specifier
15250 // component. Tack it on to the end of the nested name specifier.
15251 if (ScopeType) {
15252 if (!ScopeType->getType()->getAs<TagType>()) {
15253 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
15254 diag::err_expected_class_or_namespace)
15255 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
15256 return ExprError();
15257 }
15258 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
15259 CCLoc);
15260 }
15261
15262 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
15263 return getSema().BuildMemberReferenceExpr(Base, BaseType,
15264 OperatorLoc, isArrow,
15265 SS, TemplateKWLoc,
15266 /*FIXME: FirstQualifier*/ nullptr,
15267 NameInfo,
15268 /*TemplateArgs*/ nullptr,
15269 /*S*/nullptr);
15270}
15271
15272template<typename Derived>
15273StmtResult
15274TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
15275 SourceLocation Loc = S->getBeginLoc();
15276 CapturedDecl *CD = S->getCapturedDecl();
15277 unsigned NumParams = CD->getNumParams();
15278 unsigned ContextParamPos = CD->getContextParamPosition();
15279 SmallVector<Sema::CapturedParamNameType, 4> Params;
15280 for (unsigned I = 0; I < NumParams; ++I) {
15281 if (I != ContextParamPos) {
15282 Params.push_back(
15283 std::make_pair(
15284 CD->getParam(I)->getName(),
15285 getDerived().TransformType(CD->getParam(I)->getType())));
15286 } else {
15287 Params.push_back(std::make_pair(StringRef(), QualType()));
15288 }
15289 }
15290 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
15291 S->getCapturedRegionKind(), Params);
15292 StmtResult Body;
15293 {
15294 Sema::CompoundScopeRAII CompoundScope(getSema());
15295 Body = getDerived().TransformStmt(S->getCapturedStmt());
15296 }
15297
15298 if (Body.isInvalid()) {
15299 getSema().ActOnCapturedRegionError();
15300 return StmtError();
15301 }
15302
15303 return getSema().ActOnCapturedRegionEnd(Body.get());
15304}
15305
15306} // end namespace clang
15307
15308#endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H

/build/source/clang/include/clang/Sema/Ownership.h

1//===- Ownership.h - Parser ownership helpers -------------------*- C++ -*-===//
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 contains classes for managing ownership of Stmt and Expr nodes.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_SEMA_OWNERSHIP_H
14#define LLVM_CLANG_SEMA_OWNERSHIP_H
15
16#include "clang/AST/Expr.h"
17#include "clang/Basic/LLVM.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/Support/PointerLikeTypeTraits.h"
20#include "llvm/Support/type_traits.h"
21#include <cassert>
22#include <cstddef>
23#include <cstdint>
24
25//===----------------------------------------------------------------------===//
26// OpaquePtr
27//===----------------------------------------------------------------------===//
28
29namespace clang {
30
31class CXXBaseSpecifier;
32class CXXCtorInitializer;
33class Decl;
34class Expr;
35class ParsedTemplateArgument;
36class QualType;
37class Stmt;
38class TemplateName;
39class TemplateParameterList;
40
41 /// Wrapper for void* pointer.
42 /// \tparam PtrTy Either a pointer type like 'T*' or a type that behaves like
43 /// a pointer.
44 ///
45 /// This is a very simple POD type that wraps a pointer that the Parser
46 /// doesn't know about but that Sema or another client does. The PtrTy
47 /// template argument is used to make sure that "Decl" pointers are not
48 /// compatible with "Type" pointers for example.
49 template <class PtrTy>
50 class OpaquePtr {
51 void *Ptr = nullptr;
52
53 explicit OpaquePtr(void *Ptr) : Ptr(Ptr) {}
54
55 using Traits = llvm::PointerLikeTypeTraits<PtrTy>;
56
57 public:
58 OpaquePtr(std::nullptr_t = nullptr) {}
59
60 static OpaquePtr make(PtrTy P) { OpaquePtr OP; OP.set(P); return OP; }
61
62 /// Returns plain pointer to the entity pointed by this wrapper.
63 /// \tparam PointeeT Type of pointed entity.
64 ///
65 /// It is identical to getPtrAs<PointeeT*>.
66 template <typename PointeeT> PointeeT* getPtrTo() const {
67 return get();
68 }
69
70 /// Returns pointer converted to the specified type.
71 /// \tparam PtrT Result pointer type. There must be implicit conversion
72 /// from PtrTy to PtrT.
73 ///
74 /// In contrast to getPtrTo, this method allows the return type to be
75 /// a smart pointer.
76 template <typename PtrT> PtrT getPtrAs() const {
77 return get();
78 }
79
80 PtrTy get() const {
81 return Traits::getFromVoidPointer(Ptr);
82 }
83
84 void set(PtrTy P) {
85 Ptr = Traits::getAsVoidPointer(P);
86 }
87
88 explicit operator bool() const { return Ptr != nullptr; }
89
90 void *getAsOpaquePtr() const { return Ptr; }
91 static OpaquePtr getFromOpaquePtr(void *P) { return OpaquePtr(P); }
92 };
93
94 /// UnionOpaquePtr - A version of OpaquePtr suitable for membership
95 /// in a union.
96 template <class T> struct UnionOpaquePtr {
97 void *Ptr;
98
99 static UnionOpaquePtr make(OpaquePtr<T> P) {
100 UnionOpaquePtr OP = { P.getAsOpaquePtr() };
101 return OP;
102 }
103
104 OpaquePtr<T> get() const { return OpaquePtr<T>::getFromOpaquePtr(Ptr); }
105 operator OpaquePtr<T>() const { return get(); }
106
107 UnionOpaquePtr &operator=(OpaquePtr<T> P) {
108 Ptr = P.getAsOpaquePtr();
109 return *this;
110 }
111 };
112
113} // namespace clang
114
115namespace llvm {
116
117 template <class T>
118 struct PointerLikeTypeTraits<clang::OpaquePtr<T>> {
119 static constexpr int NumLowBitsAvailable = 0;
120
121 static inline void *getAsVoidPointer(clang::OpaquePtr<T> P) {
122 // FIXME: Doesn't work? return P.getAs< void >();
123 return P.getAsOpaquePtr();
124 }
125
126 static inline clang::OpaquePtr<T> getFromVoidPointer(void *P) {
127 return clang::OpaquePtr<T>::getFromOpaquePtr(P);
128 }
129 };
130
131} // namespace llvm
132
133namespace clang {
134
135 // Basic
136class StreamingDiagnostic;
137
138// Determines whether the low bit of the result pointer for the
139// given UID is always zero. If so, ActionResult will use that bit
140// for it's "invalid" flag.
141template <class Ptr> struct IsResultPtrLowBitFree {
142 static const bool value = false;
143 };
144
145 /// ActionResult - This structure is used while parsing/acting on
146 /// expressions, stmts, etc. It encapsulates both the object returned by
147 /// the action, plus a sense of whether or not it is valid.
148 /// When CompressInvalid is true, the "invalid" flag will be
149 /// stored in the low bit of the Val pointer.
150 template<class PtrTy,
151 bool CompressInvalid = IsResultPtrLowBitFree<PtrTy>::value>
152 class ActionResult {
153 PtrTy Val;
154 bool Invalid;
155
156 public:
157 ActionResult(bool Invalid = false) : Val(PtrTy()), Invalid(Invalid) {}
158 ActionResult(PtrTy val) : Val(val), Invalid(false) {}
159 ActionResult(const DiagnosticBuilder &) : Val(PtrTy()), Invalid(true) {}
160
161 // These two overloads prevent void* -> bool conversions.
162 ActionResult(const void *) = delete;
163 ActionResult(volatile void *) = delete;
164
165 bool isInvalid() const { return Invalid; }
166 bool isUsable() const { return !Invalid && Val; }
167 bool isUnset() const { return !Invalid && !Val; }
168
169 PtrTy get() const { return Val; }
170 template <typename T> T *getAs() { return static_cast<T*>(get()); }
171
172 void set(PtrTy V) { Val = V; }
173
174 const ActionResult &operator=(PtrTy RHS) {
175 Val = RHS;
176 Invalid = false;
177 return *this;
178 }
179 };
180
181 // This ActionResult partial specialization places the "invalid"
182 // flag into the low bit of the pointer.
183 template<typename PtrTy>
184 class ActionResult<PtrTy, true> {
185 // A pointer whose low bit is 1 if this result is invalid, 0
186 // otherwise.
187 uintptr_t PtrWithInvalid;
188
189 using PtrTraits = llvm::PointerLikeTypeTraits<PtrTy>;
190
191 public:
192 ActionResult(bool Invalid = false)
193 : PtrWithInvalid(static_cast<uintptr_t>(Invalid)) {}
194
195 ActionResult(PtrTy V) {
196 void *VP = PtrTraits::getAsVoidPointer(V);
197 PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
198 assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer")(static_cast <bool> ((PtrWithInvalid & 0x01) == 0 &&
"Badly aligned pointer") ? void (0) : __assert_fail ("(PtrWithInvalid & 0x01) == 0 && \"Badly aligned pointer\""
, "clang/include/clang/Sema/Ownership.h", 198, __extension__ __PRETTY_FUNCTION__
))
;
199 }
200
201 ActionResult(const DiagnosticBuilder &) : PtrWithInvalid(0x01) {}
202
203 // These two overloads prevent void* -> bool conversions.
204 ActionResult(const void *) = delete;
205 ActionResult(volatile void *) = delete;
206
207 bool isInvalid() const { return PtrWithInvalid & 0x01; }
208 bool isUsable() const { return PtrWithInvalid > 0x01; }
209 bool isUnset() const { return PtrWithInvalid == 0; }
210
211 PtrTy get() const {
212 void *VP = reinterpret_cast<void *>(PtrWithInvalid & ~0x01);
11
'VP' initialized here
213 return PtrTraits::getFromVoidPointer(VP);
12
Passing value via 1st parameter 'P'
13
Returning pointer
214 }
215
216 template <typename T> T *getAs() { return static_cast<T*>(get()); }
217
218 void set(PtrTy V) {
219 void *VP = PtrTraits::getAsVoidPointer(V);
220 PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
221 assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer")(static_cast <bool> ((PtrWithInvalid & 0x01) == 0 &&
"Badly aligned pointer") ? void (0) : __assert_fail ("(PtrWithInvalid & 0x01) == 0 && \"Badly aligned pointer\""
, "clang/include/clang/Sema/Ownership.h", 221, __extension__ __PRETTY_FUNCTION__
))
;
222 }
223
224 const ActionResult &operator=(PtrTy RHS) {
225 void *VP = PtrTraits::getAsVoidPointer(RHS);
226 PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
227 assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer")(static_cast <bool> ((PtrWithInvalid & 0x01) == 0 &&
"Badly aligned pointer") ? void (0) : __assert_fail ("(PtrWithInvalid & 0x01) == 0 && \"Badly aligned pointer\""
, "clang/include/clang/Sema/Ownership.h", 227, __extension__ __PRETTY_FUNCTION__
))
;
228 return *this;
229 }
230
231 // For types where we can fit a flag in with the pointer, provide
232 // conversions to/from pointer type.
233 static ActionResult getFromOpaquePointer(void *P) {
234 ActionResult Result;
235 Result.PtrWithInvalid = (uintptr_t)P;
236 return Result;
237 }
238 void *getAsOpaquePointer() const { return (void*)PtrWithInvalid; }
239 };
240
241 /// An opaque type for threading parsed type information through the
242 /// parser.
243 using ParsedType = OpaquePtr<QualType>;
244 using UnionParsedType = UnionOpaquePtr<QualType>;
245
246 // We can re-use the low bit of expression, statement, base, and
247 // member-initializer pointers for the "invalid" flag of
248 // ActionResult.
249 template<> struct IsResultPtrLowBitFree<Expr*> {
250 static const bool value = true;
251 };
252 template<> struct IsResultPtrLowBitFree<Stmt*> {
253 static const bool value = true;
254 };
255 template<> struct IsResultPtrLowBitFree<CXXBaseSpecifier*> {
256 static const bool value = true;
257 };
258 template<> struct IsResultPtrLowBitFree<CXXCtorInitializer*> {
259 static const bool value = true;
260 };
261
262 using ExprResult = ActionResult<Expr *>;
263 using StmtResult = ActionResult<Stmt *>;
264 using TypeResult = ActionResult<ParsedType>;
265 using BaseResult = ActionResult<CXXBaseSpecifier *>;
266 using MemInitResult = ActionResult<CXXCtorInitializer *>;
267
268 using DeclResult = ActionResult<Decl *>;
269 using ParsedTemplateTy = OpaquePtr<TemplateName>;
270 using UnionParsedTemplateTy = UnionOpaquePtr<TemplateName>;
271
272 using MultiExprArg = MutableArrayRef<Expr *>;
273 using MultiStmtArg = MutableArrayRef<Stmt *>;
274 using ASTTemplateArgsPtr = MutableArrayRef<ParsedTemplateArgument>;
275 using MultiTypeArg = MutableArrayRef<ParsedType>;
276 using MultiTemplateParamsArg = MutableArrayRef<TemplateParameterList *>;
277
278 inline ExprResult ExprError() { return ExprResult(true); }
279 inline StmtResult StmtError() { return StmtResult(true); }
280 inline TypeResult TypeError() { return TypeResult(true); }
281
282 inline ExprResult ExprError(const StreamingDiagnostic &) {
283 return ExprError();
284 }
285 inline StmtResult StmtError(const StreamingDiagnostic &) {
286 return StmtError();
287 }
288
289 inline ExprResult ExprEmpty() { return ExprResult(false); }
290 inline StmtResult StmtEmpty() { return StmtResult(false); }
291
292 inline Expr *AssertSuccess(ExprResult R) {
293 assert(!R.isInvalid() && "operation was asserted to never fail!")(static_cast <bool> (!R.isInvalid() && "operation was asserted to never fail!"
) ? void (0) : __assert_fail ("!R.isInvalid() && \"operation was asserted to never fail!\""
, "clang/include/clang/Sema/Ownership.h", 293, __extension__ __PRETTY_FUNCTION__
))
;
294 return R.get();
295 }
296
297 inline Stmt *AssertSuccess(StmtResult R) {
298 assert(!R.isInvalid() && "operation was asserted to never fail!")(static_cast <bool> (!R.isInvalid() && "operation was asserted to never fail!"
) ? void (0) : __assert_fail ("!R.isInvalid() && \"operation was asserted to never fail!\""
, "clang/include/clang/Sema/Ownership.h", 298, __extension__ __PRETTY_FUNCTION__
))
;
299 return R.get();
300 }
301
302} // namespace clang
303
304#endif // LLVM_CLANG_SEMA_OWNERSHIP_H