Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaExpr.cpp
Warning:line 5008, column 33
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/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/Initialization.h"
45#include "clang/Sema/Lookup.h"
46#include "clang/Sema/Overload.h"
47#include "clang/Sema/ParsedTemplate.h"
48#include "clang/Sema/Scope.h"
49#include "clang/Sema/ScopeInfo.h"
50#include "clang/Sema/SemaFixItUtils.h"
51#include "clang/Sema/SemaInternal.h"
52#include "clang/Sema/Template.h"
53#include "llvm/ADT/STLExtras.h"
54#include "llvm/ADT/StringExtras.h"
55#include "llvm/Support/Casting.h"
56#include "llvm/Support/ConvertUTF.h"
57#include "llvm/Support/SaveAndRestore.h"
58#include "llvm/Support/TypeSize.h"
59
60using namespace clang;
61using namespace sema;
62
63/// Determine whether the use of this declaration is valid, without
64/// emitting diagnostics.
65bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
66 // See if this is an auto-typed variable whose initializer we are parsing.
67 if (ParsingInitForAutoVars.count(D))
68 return false;
69
70 // See if this is a deleted function.
71 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
72 if (FD->isDeleted())
73 return false;
74
75 // If the function has a deduced return type, and we can't deduce it,
76 // then we can't use it either.
77 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
78 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
79 return false;
80
81 // See if this is an aligned allocation/deallocation function that is
82 // unavailable.
83 if (TreatUnavailableAsInvalid &&
84 isUnavailableAlignedAllocationFunction(*FD))
85 return false;
86 }
87
88 // See if this function is unavailable.
89 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
90 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
91 return false;
92
93 if (isa<UnresolvedUsingIfExistsDecl>(D))
94 return false;
95
96 return true;
97}
98
99static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
100 // Warn if this is used but marked unused.
101 if (const auto *A = D->getAttr<UnusedAttr>()) {
102 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
103 // should diagnose them.
104 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
105 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
106 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
107 if (DC && !DC->hasAttr<UnusedAttr>())
108 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
109 }
110 }
111}
112
113/// Emit a note explaining that this function is deleted.
114void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
115 assert(Decl && Decl->isDeleted())(static_cast <bool> (Decl && Decl->isDeleted
()) ? void (0) : __assert_fail ("Decl && Decl->isDeleted()"
, "clang/lib/Sema/SemaExpr.cpp", 115, __extension__ __PRETTY_FUNCTION__
))
;
116
117 if (Decl->isDefaulted()) {
118 // If the method was explicitly defaulted, point at that declaration.
119 if (!Decl->isImplicit())
120 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
121
122 // Try to diagnose why this special member function was implicitly
123 // deleted. This might fail, if that reason no longer applies.
124 DiagnoseDeletedDefaultedFunction(Decl);
125 return;
126 }
127
128 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
129 if (Ctor && Ctor->isInheritingConstructor())
130 return NoteDeletedInheritingConstructor(Ctor);
131
132 Diag(Decl->getLocation(), diag::note_availability_specified_here)
133 << Decl << 1;
134}
135
136/// Determine whether a FunctionDecl was ever declared with an
137/// explicit storage class.
138static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
139 for (auto I : D->redecls()) {
140 if (I->getStorageClass() != SC_None)
141 return true;
142 }
143 return false;
144}
145
146/// Check whether we're in an extern inline function and referring to a
147/// variable or function with internal linkage (C11 6.7.4p3).
148///
149/// This is only a warning because we used to silently accept this code, but
150/// in many cases it will not behave correctly. This is not enabled in C++ mode
151/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
152/// and so while there may still be user mistakes, most of the time we can't
153/// prove that there are errors.
154static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
155 const NamedDecl *D,
156 SourceLocation Loc) {
157 // This is disabled under C++; there are too many ways for this to fire in
158 // contexts where the warning is a false positive, or where it is technically
159 // correct but benign.
160 if (S.getLangOpts().CPlusPlus)
161 return;
162
163 // Check if this is an inlined function or method.
164 FunctionDecl *Current = S.getCurFunctionDecl();
165 if (!Current)
166 return;
167 if (!Current->isInlined())
168 return;
169 if (!Current->isExternallyVisible())
170 return;
171
172 // Check if the decl has internal linkage.
173 if (D->getFormalLinkage() != InternalLinkage)
174 return;
175
176 // Downgrade from ExtWarn to Extension if
177 // (1) the supposedly external inline function is in the main file,
178 // and probably won't be included anywhere else.
179 // (2) the thing we're referencing is a pure function.
180 // (3) the thing we're referencing is another inline function.
181 // This last can give us false negatives, but it's better than warning on
182 // wrappers for simple C library functions.
183 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
184 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
185 if (!DowngradeWarning && UsedFn)
186 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
187
188 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
189 : diag::ext_internal_in_extern_inline)
190 << /*IsVar=*/!UsedFn << D;
191
192 S.MaybeSuggestAddingStaticToDecl(Current);
193
194 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
195 << D;
196}
197
198void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
199 const FunctionDecl *First = Cur->getFirstDecl();
200
201 // Suggest "static" on the function, if possible.
202 if (!hasAnyExplicitStorageClass(First)) {
203 SourceLocation DeclBegin = First->getSourceRange().getBegin();
204 Diag(DeclBegin, diag::note_convert_inline_to_static)
205 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
206 }
207}
208
209/// Determine whether the use of this declaration is valid, and
210/// emit any corresponding diagnostics.
211///
212/// This routine diagnoses various problems with referencing
213/// declarations that can occur when using a declaration. For example,
214/// it might warn if a deprecated or unavailable declaration is being
215/// used, or produce an error (and return true) if a C++0x deleted
216/// function is being used.
217///
218/// \returns true if there was an error (this declaration cannot be
219/// referenced), false otherwise.
220///
221bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
222 const ObjCInterfaceDecl *UnknownObjCClass,
223 bool ObjCPropertyAccess,
224 bool AvoidPartialAvailabilityChecks,
225 ObjCInterfaceDecl *ClassReceiver) {
226 SourceLocation Loc = Locs.front();
227 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
228 // If there were any diagnostics suppressed by template argument deduction,
229 // emit them now.
230 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
231 if (Pos != SuppressedDiagnostics.end()) {
232 for (const PartialDiagnosticAt &Suppressed : Pos->second)
233 Diag(Suppressed.first, Suppressed.second);
234
235 // Clear out the list of suppressed diagnostics, so that we don't emit
236 // them again for this specialization. However, we don't obsolete this
237 // entry from the table, because we want to avoid ever emitting these
238 // diagnostics again.
239 Pos->second.clear();
240 }
241
242 // C++ [basic.start.main]p3:
243 // The function 'main' shall not be used within a program.
244 if (cast<FunctionDecl>(D)->isMain())
245 Diag(Loc, diag::ext_main_used);
246
247 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
248 }
249
250 // See if this is an auto-typed variable whose initializer we are parsing.
251 if (ParsingInitForAutoVars.count(D)) {
252 if (isa<BindingDecl>(D)) {
253 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
254 << D->getDeclName();
255 } else {
256 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
257 << D->getDeclName() << cast<VarDecl>(D)->getType();
258 }
259 return true;
260 }
261
262 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
263 // See if this is a deleted function.
264 if (FD->isDeleted()) {
265 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
266 if (Ctor && Ctor->isInheritingConstructor())
267 Diag(Loc, diag::err_deleted_inherited_ctor_use)
268 << Ctor->getParent()
269 << Ctor->getInheritedConstructor().getConstructor()->getParent();
270 else
271 Diag(Loc, diag::err_deleted_function_use);
272 NoteDeletedFunction(FD);
273 return true;
274 }
275
276 // [expr.prim.id]p4
277 // A program that refers explicitly or implicitly to a function with a
278 // trailing requires-clause whose constraint-expression is not satisfied,
279 // other than to declare it, is ill-formed. [...]
280 //
281 // See if this is a function with constraints that need to be satisfied.
282 // Check this before deducing the return type, as it might instantiate the
283 // definition.
284 if (FD->getTrailingRequiresClause()) {
285 ConstraintSatisfaction Satisfaction;
286 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
287 // A diagnostic will have already been generated (non-constant
288 // constraint expression, for example)
289 return true;
290 if (!Satisfaction.IsSatisfied) {
291 Diag(Loc,
292 diag::err_reference_to_function_with_unsatisfied_constraints)
293 << D;
294 DiagnoseUnsatisfiedConstraint(Satisfaction);
295 return true;
296 }
297 }
298
299 // If the function has a deduced return type, and we can't deduce it,
300 // then we can't use it either.
301 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
302 DeduceReturnType(FD, Loc))
303 return true;
304
305 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
306 return true;
307
308 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
309 return true;
310 }
311
312 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
313 // Lambdas are only default-constructible or assignable in C++2a onwards.
314 if (MD->getParent()->isLambda() &&
315 ((isa<CXXConstructorDecl>(MD) &&
316 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
317 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
318 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
319 << !isa<CXXConstructorDecl>(MD);
320 }
321 }
322
323 auto getReferencedObjCProp = [](const NamedDecl *D) ->
324 const ObjCPropertyDecl * {
325 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
326 return MD->findPropertyDecl();
327 return nullptr;
328 };
329 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
330 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
331 return true;
332 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
333 return true;
334 }
335
336 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
337 // Only the variables omp_in and omp_out are allowed in the combiner.
338 // Only the variables omp_priv and omp_orig are allowed in the
339 // initializer-clause.
340 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
341 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
342 isa<VarDecl>(D)) {
343 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
344 << getCurFunction()->HasOMPDeclareReductionCombiner;
345 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
346 return true;
347 }
348
349 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
350 // List-items in map clauses on this construct may only refer to the declared
351 // variable var and entities that could be referenced by a procedure defined
352 // at the same location
353 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
354 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
355 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
356 << getOpenMPDeclareMapperVarName();
357 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
358 return true;
359 }
360
361 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
362 Diag(Loc, diag::err_use_of_empty_using_if_exists);
363 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
364 return true;
365 }
366
367 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
368 AvoidPartialAvailabilityChecks, ClassReceiver);
369
370 DiagnoseUnusedOfDecl(*this, D, Loc);
371
372 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
373
374 if (auto *VD = dyn_cast<ValueDecl>(D))
375 checkTypeSupport(VD->getType(), Loc, VD);
376
377 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
378 if (!Context.getTargetInfo().isTLSSupported())
379 if (const auto *VD = dyn_cast<VarDecl>(D))
380 if (VD->getTLSKind() != VarDecl::TLS_None)
381 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
382 }
383
384 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
385 !isUnevaluatedContext()) {
386 // C++ [expr.prim.req.nested] p3
387 // A local parameter shall only appear as an unevaluated operand
388 // (Clause 8) within the constraint-expression.
389 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
390 << D;
391 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
392 return true;
393 }
394
395 return false;
396}
397
398/// DiagnoseSentinelCalls - This routine checks whether a call or
399/// message-send is to a declaration with the sentinel attribute, and
400/// if so, it checks that the requirements of the sentinel are
401/// satisfied.
402void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
403 ArrayRef<Expr *> Args) {
404 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
405 if (!attr)
406 return;
407
408 // The number of formal parameters of the declaration.
409 unsigned numFormalParams;
410
411 // The kind of declaration. This is also an index into a %select in
412 // the diagnostic.
413 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
414
415 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
416 numFormalParams = MD->param_size();
417 calleeType = CT_Method;
418 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
419 numFormalParams = FD->param_size();
420 calleeType = CT_Function;
421 } else if (isa<VarDecl>(D)) {
422 QualType type = cast<ValueDecl>(D)->getType();
423 const FunctionType *fn = nullptr;
424 if (const PointerType *ptr = type->getAs<PointerType>()) {
425 fn = ptr->getPointeeType()->getAs<FunctionType>();
426 if (!fn) return;
427 calleeType = CT_Function;
428 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
429 fn = ptr->getPointeeType()->castAs<FunctionType>();
430 calleeType = CT_Block;
431 } else {
432 return;
433 }
434
435 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
436 numFormalParams = proto->getNumParams();
437 } else {
438 numFormalParams = 0;
439 }
440 } else {
441 return;
442 }
443
444 // "nullPos" is the number of formal parameters at the end which
445 // effectively count as part of the variadic arguments. This is
446 // useful if you would prefer to not have *any* formal parameters,
447 // but the language forces you to have at least one.
448 unsigned nullPos = attr->getNullPos();
449 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", 449, __extension__ __PRETTY_FUNCTION__
))
;
450 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
451
452 // The number of arguments which should follow the sentinel.
453 unsigned numArgsAfterSentinel = attr->getSentinel();
454
455 // If there aren't enough arguments for all the formal parameters,
456 // the sentinel, and the args after the sentinel, complain.
457 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
458 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
459 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
460 return;
461 }
462
463 // Otherwise, find the sentinel expression.
464 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
465 if (!sentinelExpr) return;
466 if (sentinelExpr->isValueDependent()) return;
467 if (Context.isSentinelNullExpr(sentinelExpr)) return;
468
469 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
470 // or 'NULL' if those are actually defined in the context. Only use
471 // 'nil' for ObjC methods, where it's much more likely that the
472 // variadic arguments form a list of object pointers.
473 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
474 std::string NullValue;
475 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
476 NullValue = "nil";
477 else if (getLangOpts().CPlusPlus11)
478 NullValue = "nullptr";
479 else if (PP.isMacroDefined("NULL"))
480 NullValue = "NULL";
481 else
482 NullValue = "(void*) 0";
483
484 if (MissingNilLoc.isInvalid())
485 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
486 else
487 Diag(MissingNilLoc, diag::warn_missing_sentinel)
488 << int(calleeType)
489 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
490 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
491}
492
493SourceRange Sema::getExprRange(Expr *E) const {
494 return E ? E->getSourceRange() : SourceRange();
495}
496
497//===----------------------------------------------------------------------===//
498// Standard Promotions and Conversions
499//===----------------------------------------------------------------------===//
500
501/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
502ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
503 // Handle any placeholder expressions which made it here.
504 if (E->hasPlaceholderType()) {
505 ExprResult result = CheckPlaceholderExpr(E);
506 if (result.isInvalid()) return ExprError();
507 E = result.get();
508 }
509
510 QualType Ty = E->getType();
511 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", 511, __extension__ __PRETTY_FUNCTION__
))
;
512
513 if (Ty->isFunctionType()) {
514 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
515 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
516 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
517 return ExprError();
518
519 E = ImpCastExprToType(E, Context.getPointerType(Ty),
520 CK_FunctionToPointerDecay).get();
521 } else if (Ty->isArrayType()) {
522 // In C90 mode, arrays only promote to pointers if the array expression is
523 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
524 // type 'array of type' is converted to an expression that has type 'pointer
525 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
526 // that has type 'array of type' ...". The relevant change is "an lvalue"
527 // (C90) to "an expression" (C99).
528 //
529 // C++ 4.2p1:
530 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
531 // T" can be converted to an rvalue of type "pointer to T".
532 //
533 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
534 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
535 CK_ArrayToPointerDecay);
536 if (Res.isInvalid())
537 return ExprError();
538 E = Res.get();
539 }
540 }
541 return E;
542}
543
544static void CheckForNullPointerDereference(Sema &S, Expr *E) {
545 // Check to see if we are dereferencing a null pointer. If so,
546 // and if not volatile-qualified, this is undefined behavior that the
547 // optimizer will delete, so warn about it. People sometimes try to use this
548 // to get a deterministic trap and are surprised by clang's behavior. This
549 // only handles the pattern "*null", which is a very syntactic check.
550 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
551 if (UO && UO->getOpcode() == UO_Deref &&
552 UO->getSubExpr()->getType()->isPointerType()) {
553 const LangAS AS =
554 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
555 if ((!isTargetAddressSpace(AS) ||
556 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
557 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
558 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
559 !UO->getType().isVolatileQualified()) {
560 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
561 S.PDiag(diag::warn_indirection_through_null)
562 << UO->getSubExpr()->getSourceRange());
563 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564 S.PDiag(diag::note_indirection_through_null));
565 }
566 }
567}
568
569static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
570 SourceLocation AssignLoc,
571 const Expr* RHS) {
572 const ObjCIvarDecl *IV = OIRE->getDecl();
573 if (!IV)
574 return;
575
576 DeclarationName MemberName = IV->getDeclName();
577 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
578 if (!Member || !Member->isStr("isa"))
579 return;
580
581 const Expr *Base = OIRE->getBase();
582 QualType BaseType = Base->getType();
583 if (OIRE->isArrow())
584 BaseType = BaseType->getPointeeType();
585 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
586 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
587 ObjCInterfaceDecl *ClassDeclared = nullptr;
588 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
589 if (!ClassDeclared->getSuperClass()
590 && (*ClassDeclared->ivar_begin()) == IV) {
591 if (RHS) {
592 NamedDecl *ObjectSetClass =
593 S.LookupSingleName(S.TUScope,
594 &S.Context.Idents.get("object_setClass"),
595 SourceLocation(), S.LookupOrdinaryName);
596 if (ObjectSetClass) {
597 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
598 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
599 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
600 "object_setClass(")
601 << FixItHint::CreateReplacement(
602 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
603 << FixItHint::CreateInsertion(RHSLocEnd, ")");
604 }
605 else
606 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
607 } else {
608 NamedDecl *ObjectGetClass =
609 S.LookupSingleName(S.TUScope,
610 &S.Context.Idents.get("object_getClass"),
611 SourceLocation(), S.LookupOrdinaryName);
612 if (ObjectGetClass)
613 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
614 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
615 "object_getClass(")
616 << FixItHint::CreateReplacement(
617 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
618 else
619 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
620 }
621 S.Diag(IV->getLocation(), diag::note_ivar_decl);
622 }
623 }
624}
625
626ExprResult Sema::DefaultLvalueConversion(Expr *E) {
627 // Handle any placeholder expressions which made it here.
628 if (E->hasPlaceholderType()) {
629 ExprResult result = CheckPlaceholderExpr(E);
630 if (result.isInvalid()) return ExprError();
631 E = result.get();
632 }
633
634 // C++ [conv.lval]p1:
635 // A glvalue of a non-function, non-array type T can be
636 // converted to a prvalue.
637 if (!E->isGLValue()) return E;
638
639 QualType T = E->getType();
640 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", 640, __extension__ __PRETTY_FUNCTION__
))
;
641
642 // lvalue-to-rvalue conversion cannot be applied to function or array types.
643 if (T->isFunctionType() || T->isArrayType())
644 return E;
645
646 // We don't want to throw lvalue-to-rvalue casts on top of
647 // expressions of certain types in C++.
648 if (getLangOpts().CPlusPlus &&
649 (E->getType() == Context.OverloadTy ||
650 T->isDependentType() ||
651 T->isRecordType()))
652 return E;
653
654 // The C standard is actually really unclear on this point, and
655 // DR106 tells us what the result should be but not why. It's
656 // generally best to say that void types just doesn't undergo
657 // lvalue-to-rvalue at all. Note that expressions of unqualified
658 // 'void' type are never l-values, but qualified void can be.
659 if (T->isVoidType())
660 return E;
661
662 // OpenCL usually rejects direct accesses to values of 'half' type.
663 if (getLangOpts().OpenCL &&
664 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
665 T->isHalfType()) {
666 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
667 << 0 << T;
668 return ExprError();
669 }
670
671 CheckForNullPointerDereference(*this, E);
672 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
673 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
674 &Context.Idents.get("object_getClass"),
675 SourceLocation(), LookupOrdinaryName);
676 if (ObjectGetClass)
677 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
678 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
679 << FixItHint::CreateReplacement(
680 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
681 else
682 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
683 }
684 else if (const ObjCIvarRefExpr *OIRE =
685 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
686 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
687
688 // C++ [conv.lval]p1:
689 // [...] If T is a non-class type, the type of the prvalue is the
690 // cv-unqualified version of T. Otherwise, the type of the
691 // rvalue is T.
692 //
693 // C99 6.3.2.1p2:
694 // If the lvalue has qualified type, the value has the unqualified
695 // version of the type of the lvalue; otherwise, the value has the
696 // type of the lvalue.
697 if (T.hasQualifiers())
698 T = T.getUnqualifiedType();
699
700 // Under the MS ABI, lock down the inheritance model now.
701 if (T->isMemberPointerType() &&
702 Context.getTargetInfo().getCXXABI().isMicrosoft())
703 (void)isCompleteType(E->getExprLoc(), T);
704
705 ExprResult Res = CheckLValueToRValueConversionOperand(E);
706 if (Res.isInvalid())
707 return Res;
708 E = Res.get();
709
710 // Loading a __weak object implicitly retains the value, so we need a cleanup to
711 // balance that.
712 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
713 Cleanup.setExprNeedsCleanups(true);
714
715 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
716 Cleanup.setExprNeedsCleanups(true);
717
718 // C++ [conv.lval]p3:
719 // If T is cv std::nullptr_t, the result is a null pointer constant.
720 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
721 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
722 CurFPFeatureOverrides());
723
724 // C11 6.3.2.1p2:
725 // ... if the lvalue has atomic type, the value has the non-atomic version
726 // of the type of the lvalue ...
727 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
728 T = Atomic->getValueType().getUnqualifiedType();
729 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
730 nullptr, VK_PRValue, FPOptionsOverride());
731 }
732
733 return Res;
734}
735
736ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
737 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
738 if (Res.isInvalid())
739 return ExprError();
740 Res = DefaultLvalueConversion(Res.get());
741 if (Res.isInvalid())
742 return ExprError();
743 return Res;
744}
745
746/// CallExprUnaryConversions - a special case of an unary conversion
747/// performed on a function designator of a call expression.
748ExprResult Sema::CallExprUnaryConversions(Expr *E) {
749 QualType Ty = E->getType();
750 ExprResult Res = E;
751 // Only do implicit cast for a function type, but not for a pointer
752 // to function type.
753 if (Ty->isFunctionType()) {
754 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
755 CK_FunctionToPointerDecay);
756 if (Res.isInvalid())
757 return ExprError();
758 }
759 Res = DefaultLvalueConversion(Res.get());
760 if (Res.isInvalid())
761 return ExprError();
762 return Res.get();
763}
764
765/// UsualUnaryConversions - Performs various conversions that are common to most
766/// operators (C99 6.3). The conversions of array and function types are
767/// sometimes suppressed. For example, the array->pointer conversion doesn't
768/// apply if the array is an argument to the sizeof or address (&) operators.
769/// In these instances, this routine should *not* be called.
770ExprResult Sema::UsualUnaryConversions(Expr *E) {
771 // First, convert to an r-value.
772 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
773 if (Res.isInvalid())
774 return ExprError();
775 E = Res.get();
776
777 QualType Ty = E->getType();
778 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", 778, __extension__ __PRETTY_FUNCTION__
))
;
779
780 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
781 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
782 (getLangOpts().getFPEvalMethod() !=
783 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
784 PP.getLastFPEvalPragmaLocation().isValid())) {
785 switch (EvalMethod) {
786 default:
787 llvm_unreachable("Unrecognized float evaluation method")::llvm::llvm_unreachable_internal("Unrecognized float evaluation method"
, "clang/lib/Sema/SemaExpr.cpp", 787)
;
788 break;
789 case LangOptions::FEM_UnsetOnCommandLine:
790 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", 790)
;
791 break;
792 case LangOptions::FEM_Double:
793 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
794 // Widen the expression to double.
795 return Ty->isComplexType()
796 ? ImpCastExprToType(E,
797 Context.getComplexType(Context.DoubleTy),
798 CK_FloatingComplexCast)
799 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
800 break;
801 case LangOptions::FEM_Extended:
802 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
803 // Widen the expression to long double.
804 return Ty->isComplexType()
805 ? ImpCastExprToType(
806 E, Context.getComplexType(Context.LongDoubleTy),
807 CK_FloatingComplexCast)
808 : ImpCastExprToType(E, Context.LongDoubleTy,
809 CK_FloatingCast);
810 break;
811 }
812 }
813
814 // Half FP have to be promoted to float unless it is natively supported
815 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
816 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
817
818 // Try to perform integral promotions if the object has a theoretically
819 // promotable type.
820 if (Ty->isIntegralOrUnscopedEnumerationType()) {
821 // C99 6.3.1.1p2:
822 //
823 // The following may be used in an expression wherever an int or
824 // unsigned int may be used:
825 // - an object or expression with an integer type whose integer
826 // conversion rank is less than or equal to the rank of int
827 // and unsigned int.
828 // - A bit-field of type _Bool, int, signed int, or unsigned int.
829 //
830 // If an int can represent all values of the original type, the
831 // value is converted to an int; otherwise, it is converted to an
832 // unsigned int. These are called the integer promotions. All
833 // other types are unchanged by the integer promotions.
834
835 QualType PTy = Context.isPromotableBitField(E);
836 if (!PTy.isNull()) {
837 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
838 return E;
839 }
840 if (Ty->isPromotableIntegerType()) {
841 QualType PT = Context.getPromotedIntegerType(Ty);
842 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
843 return E;
844 }
845 }
846 return E;
847}
848
849/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
850/// do not have a prototype. Arguments that have type float or __fp16
851/// are promoted to double. All other argument types are converted by
852/// UsualUnaryConversions().
853ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
854 QualType Ty = E->getType();
855 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", 855, __extension__ __PRETTY_FUNCTION__
))
;
856
857 ExprResult Res = UsualUnaryConversions(E);
858 if (Res.isInvalid())
859 return ExprError();
860 E = Res.get();
861
862 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
863 // promote to double.
864 // Note that default argument promotion applies only to float (and
865 // half/fp16); it does not apply to _Float16.
866 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
867 if (BTy && (BTy->getKind() == BuiltinType::Half ||
868 BTy->getKind() == BuiltinType::Float)) {
869 if (getLangOpts().OpenCL &&
870 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
871 if (BTy->getKind() == BuiltinType::Half) {
872 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
873 }
874 } else {
875 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
876 }
877 }
878 if (BTy &&
879 getLangOpts().getExtendIntArgs() ==
880 LangOptions::ExtendArgsKind::ExtendTo64 &&
881 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
882 Context.getTypeSizeInChars(BTy) <
883 Context.getTypeSizeInChars(Context.LongLongTy)) {
884 E = (Ty->isUnsignedIntegerType())
885 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
886 .get()
887 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
888 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", 889, __extension__ __PRETTY_FUNCTION__
))
889 "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", 889, __extension__ __PRETTY_FUNCTION__
))
;
890 }
891
892 // C++ performs lvalue-to-rvalue conversion as a default argument
893 // promotion, even on class types, but note:
894 // C++11 [conv.lval]p2:
895 // When an lvalue-to-rvalue conversion occurs in an unevaluated
896 // operand or a subexpression thereof the value contained in the
897 // referenced object is not accessed. Otherwise, if the glvalue
898 // has a class type, the conversion copy-initializes a temporary
899 // of type T from the glvalue and the result of the conversion
900 // is a prvalue for the temporary.
901 // FIXME: add some way to gate this entire thing for correctness in
902 // potentially potentially evaluated contexts.
903 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
904 ExprResult Temp = PerformCopyInitialization(
905 InitializedEntity::InitializeTemporary(E->getType()),
906 E->getExprLoc(), E);
907 if (Temp.isInvalid())
908 return ExprError();
909 E = Temp.get();
910 }
911
912 return E;
913}
914
915/// Determine the degree of POD-ness for an expression.
916/// Incomplete types are considered POD, since this check can be performed
917/// when we're in an unevaluated context.
918Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
919 if (Ty->isIncompleteType()) {
920 // C++11 [expr.call]p7:
921 // After these conversions, if the argument does not have arithmetic,
922 // enumeration, pointer, pointer to member, or class type, the program
923 // is ill-formed.
924 //
925 // Since we've already performed array-to-pointer and function-to-pointer
926 // decay, the only such type in C++ is cv void. This also handles
927 // initializer lists as variadic arguments.
928 if (Ty->isVoidType())
929 return VAK_Invalid;
930
931 if (Ty->isObjCObjectType())
932 return VAK_Invalid;
933 return VAK_Valid;
934 }
935
936 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
937 return VAK_Invalid;
938
939 if (Ty.isCXX98PODType(Context))
940 return VAK_Valid;
941
942 // C++11 [expr.call]p7:
943 // Passing a potentially-evaluated argument of class type (Clause 9)
944 // having a non-trivial copy constructor, a non-trivial move constructor,
945 // or a non-trivial destructor, with no corresponding parameter,
946 // is conditionally-supported with implementation-defined semantics.
947 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
948 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
949 if (!Record->hasNonTrivialCopyConstructor() &&
950 !Record->hasNonTrivialMoveConstructor() &&
951 !Record->hasNonTrivialDestructor())
952 return VAK_ValidInCXX11;
953
954 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
955 return VAK_Valid;
956
957 if (Ty->isObjCObjectType())
958 return VAK_Invalid;
959
960 if (getLangOpts().MSVCCompat)
961 return VAK_MSVCUndefined;
962
963 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
964 // permitted to reject them. We should consider doing so.
965 return VAK_Undefined;
966}
967
968void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
969 // Don't allow one to pass an Objective-C interface to a vararg.
970 const QualType &Ty = E->getType();
971 VarArgKind VAK = isValidVarArgType(Ty);
972
973 // Complain about passing non-POD types through varargs.
974 switch (VAK) {
975 case VAK_ValidInCXX11:
976 DiagRuntimeBehavior(
977 E->getBeginLoc(), nullptr,
978 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
979 LLVM_FALLTHROUGH[[gnu::fallthrough]];
980 case VAK_Valid:
981 if (Ty->isRecordType()) {
982 // This is unlikely to be what the user intended. If the class has a
983 // 'c_str' member function, the user probably meant to call that.
984 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
985 PDiag(diag::warn_pass_class_arg_to_vararg)
986 << Ty << CT << hasCStrMethod(E) << ".c_str()");
987 }
988 break;
989
990 case VAK_Undefined:
991 case VAK_MSVCUndefined:
992 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
993 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
994 << getLangOpts().CPlusPlus11 << Ty << CT);
995 break;
996
997 case VAK_Invalid:
998 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
999 Diag(E->getBeginLoc(),
1000 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1001 << Ty << CT;
1002 else if (Ty->isObjCObjectType())
1003 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1004 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1005 << Ty << CT);
1006 else
1007 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1008 << isa<InitListExpr>(E) << Ty << CT;
1009 break;
1010 }
1011}
1012
1013/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1014/// will create a trap if the resulting type is not a POD type.
1015ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1016 FunctionDecl *FDecl) {
1017 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1018 // Strip the unbridged-cast placeholder expression off, if applicable.
1019 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1020 (CT == VariadicMethod ||
1021 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1022 E = stripARCUnbridgedCast(E);
1023
1024 // Otherwise, do normal placeholder checking.
1025 } else {
1026 ExprResult ExprRes = CheckPlaceholderExpr(E);
1027 if (ExprRes.isInvalid())
1028 return ExprError();
1029 E = ExprRes.get();
1030 }
1031 }
1032
1033 ExprResult ExprRes = DefaultArgumentPromotion(E);
1034 if (ExprRes.isInvalid())
1035 return ExprError();
1036
1037 // Copy blocks to the heap.
1038 if (ExprRes.get()->getType()->isBlockPointerType())
1039 maybeExtendBlockObject(ExprRes);
1040
1041 E = ExprRes.get();
1042
1043 // Diagnostics regarding non-POD argument types are
1044 // emitted along with format string checking in Sema::CheckFunctionCall().
1045 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1046 // Turn this into a trap.
1047 CXXScopeSpec SS;
1048 SourceLocation TemplateKWLoc;
1049 UnqualifiedId Name;
1050 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1051 E->getBeginLoc());
1052 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1053 /*HasTrailingLParen=*/true,
1054 /*IsAddressOfOperand=*/false);
1055 if (TrapFn.isInvalid())
1056 return ExprError();
1057
1058 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1059 None, E->getEndLoc());
1060 if (Call.isInvalid())
1061 return ExprError();
1062
1063 ExprResult Comma =
1064 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1065 if (Comma.isInvalid())
1066 return ExprError();
1067 return Comma.get();
1068 }
1069
1070 if (!getLangOpts().CPlusPlus &&
1071 RequireCompleteType(E->getExprLoc(), E->getType(),
1072 diag::err_call_incomplete_argument))
1073 return ExprError();
1074
1075 return E;
1076}
1077
1078/// Converts an integer to complex float type. Helper function of
1079/// UsualArithmeticConversions()
1080///
1081/// \return false if the integer expression is an integer type and is
1082/// successfully converted to the complex type.
1083static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1084 ExprResult &ComplexExpr,
1085 QualType IntTy,
1086 QualType ComplexTy,
1087 bool SkipCast) {
1088 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1089 if (SkipCast) return false;
1090 if (IntTy->isIntegerType()) {
1091 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1092 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1093 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1094 CK_FloatingRealToComplex);
1095 } else {
1096 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "clang/lib/Sema/SemaExpr.cpp", 1096, __extension__ __PRETTY_FUNCTION__
))
;
1097 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1098 CK_IntegralComplexToFloatingComplex);
1099 }
1100 return false;
1101}
1102
1103/// Handle arithmetic conversion with complex types. Helper function of
1104/// UsualArithmeticConversions()
1105static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1106 ExprResult &RHS, QualType LHSType,
1107 QualType RHSType,
1108 bool IsCompAssign) {
1109 // if we have an integer operand, the result is the complex type.
1110 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1111 /*skipCast*/false))
1112 return LHSType;
1113 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1114 /*skipCast*/IsCompAssign))
1115 return RHSType;
1116
1117 // This handles complex/complex, complex/float, or float/complex.
1118 // When both operands are complex, the shorter operand is converted to the
1119 // type of the longer, and that is the type of the result. This corresponds
1120 // to what is done when combining two real floating-point operands.
1121 // The fun begins when size promotion occur across type domains.
1122 // From H&S 6.3.4: When one operand is complex and the other is a real
1123 // floating-point type, the less precise type is converted, within it's
1124 // real or complex domain, to the precision of the other type. For example,
1125 // when combining a "long double" with a "double _Complex", the
1126 // "double _Complex" is promoted to "long double _Complex".
1127
1128 // Compute the rank of the two types, regardless of whether they are complex.
1129 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1130
1131 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1132 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1133 QualType LHSElementType =
1134 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1135 QualType RHSElementType =
1136 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1137
1138 QualType ResultType = S.Context.getComplexType(LHSElementType);
1139 if (Order < 0) {
1140 // Promote the precision of the LHS if not an assignment.
1141 ResultType = S.Context.getComplexType(RHSElementType);
1142 if (!IsCompAssign) {
1143 if (LHSComplexType)
1144 LHS =
1145 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1146 else
1147 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1148 }
1149 } else if (Order > 0) {
1150 // Promote the precision of the RHS.
1151 if (RHSComplexType)
1152 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1153 else
1154 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1155 }
1156 return ResultType;
1157}
1158
1159/// Handle arithmetic conversion from integer to float. Helper function
1160/// of UsualArithmeticConversions()
1161static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1162 ExprResult &IntExpr,
1163 QualType FloatTy, QualType IntTy,
1164 bool ConvertFloat, bool ConvertInt) {
1165 if (IntTy->isIntegerType()) {
1166 if (ConvertInt)
1167 // Convert intExpr to the lhs floating point type.
1168 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1169 CK_IntegralToFloating);
1170 return FloatTy;
1171 }
1172
1173 // Convert both sides to the appropriate complex float.
1174 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "clang/lib/Sema/SemaExpr.cpp", 1174, __extension__ __PRETTY_FUNCTION__
))
;
1175 QualType result = S.Context.getComplexType(FloatTy);
1176
1177 // _Complex int -> _Complex float
1178 if (ConvertInt)
1179 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1180 CK_IntegralComplexToFloatingComplex);
1181
1182 // float -> _Complex float
1183 if (ConvertFloat)
1184 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1185 CK_FloatingRealToComplex);
1186
1187 return result;
1188}
1189
1190/// Handle arithmethic conversion with floating point types. Helper
1191/// function of UsualArithmeticConversions()
1192static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1193 ExprResult &RHS, QualType LHSType,
1194 QualType RHSType, bool IsCompAssign) {
1195 bool LHSFloat = LHSType->isRealFloatingType();
1196 bool RHSFloat = RHSType->isRealFloatingType();
1197
1198 // N1169 4.1.4: If one of the operands has a floating type and the other
1199 // operand has a fixed-point type, the fixed-point operand
1200 // is converted to the floating type [...]
1201 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1202 if (LHSFloat)
1203 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1204 else if (!IsCompAssign)
1205 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1206 return LHSFloat ? LHSType : RHSType;
1207 }
1208
1209 // If we have two real floating types, convert the smaller operand
1210 // to the bigger result.
1211 if (LHSFloat && RHSFloat) {
1212 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1213 if (order > 0) {
1214 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1215 return LHSType;
1216 }
1217
1218 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", 1218, __extension__ __PRETTY_FUNCTION__
))
;
1219 if (!IsCompAssign)
1220 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1221 return RHSType;
1222 }
1223
1224 if (LHSFloat) {
1225 // Half FP has to be promoted to float unless it is natively supported
1226 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1227 LHSType = S.Context.FloatTy;
1228
1229 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1230 /*ConvertFloat=*/!IsCompAssign,
1231 /*ConvertInt=*/ true);
1232 }
1233 assert(RHSFloat)(static_cast <bool> (RHSFloat) ? void (0) : __assert_fail
("RHSFloat", "clang/lib/Sema/SemaExpr.cpp", 1233, __extension__
__PRETTY_FUNCTION__))
;
1234 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1235 /*ConvertFloat=*/ true,
1236 /*ConvertInt=*/!IsCompAssign);
1237}
1238
1239/// Diagnose attempts to convert between __float128, __ibm128 and
1240/// long double if there is no support for such conversion.
1241/// Helper function of UsualArithmeticConversions().
1242static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1243 QualType RHSType) {
1244 // No issue if either is not a floating point type.
1245 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1246 return false;
1247
1248 // No issue if both have the same 128-bit float semantics.
1249 auto *LHSComplex = LHSType->getAs<ComplexType>();
1250 auto *RHSComplex = RHSType->getAs<ComplexType>();
1251
1252 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1253 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1254
1255 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1256 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1257
1258 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1259 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1260 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1261 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1262 return false;
1263
1264 return true;
1265}
1266
1267typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1268
1269namespace {
1270/// These helper callbacks are placed in an anonymous namespace to
1271/// permit their use as function template parameters.
1272ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1273 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1274}
1275
1276ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1277 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1278 CK_IntegralComplexCast);
1279}
1280}
1281
1282/// Handle integer arithmetic conversions. Helper function of
1283/// UsualArithmeticConversions()
1284template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1285static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1286 ExprResult &RHS, QualType LHSType,
1287 QualType RHSType, bool IsCompAssign) {
1288 // The rules for this case are in C99 6.3.1.8
1289 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1290 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1291 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1292 if (LHSSigned == RHSSigned) {
1293 // Same signedness; use the higher-ranked type
1294 if (order >= 0) {
1295 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1296 return LHSType;
1297 } else if (!IsCompAssign)
1298 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1299 return RHSType;
1300 } else if (order != (LHSSigned ? 1 : -1)) {
1301 // The unsigned type has greater than or equal rank to the
1302 // signed type, so use the unsigned type
1303 if (RHSSigned) {
1304 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1305 return LHSType;
1306 } else if (!IsCompAssign)
1307 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1308 return RHSType;
1309 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1310 // The two types are different widths; if we are here, that
1311 // means the signed type is larger than the unsigned type, so
1312 // use the signed type.
1313 if (LHSSigned) {
1314 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1315 return LHSType;
1316 } else if (!IsCompAssign)
1317 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1318 return RHSType;
1319 } else {
1320 // The signed type is higher-ranked than the unsigned type,
1321 // but isn't actually any bigger (like unsigned int and long
1322 // on most 32-bit systems). Use the unsigned type corresponding
1323 // to the signed type.
1324 QualType result =
1325 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1326 RHS = (*doRHSCast)(S, RHS.get(), result);
1327 if (!IsCompAssign)
1328 LHS = (*doLHSCast)(S, LHS.get(), result);
1329 return result;
1330 }
1331}
1332
1333/// Handle conversions with GCC complex int extension. Helper function
1334/// of UsualArithmeticConversions()
1335static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1336 ExprResult &RHS, QualType LHSType,
1337 QualType RHSType,
1338 bool IsCompAssign) {
1339 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1340 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1341
1342 if (LHSComplexInt && RHSComplexInt) {
1343 QualType LHSEltType = LHSComplexInt->getElementType();
1344 QualType RHSEltType = RHSComplexInt->getElementType();
1345 QualType ScalarType =
1346 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1347 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1348
1349 return S.Context.getComplexType(ScalarType);
1350 }
1351
1352 if (LHSComplexInt) {
1353 QualType LHSEltType = LHSComplexInt->getElementType();
1354 QualType ScalarType =
1355 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1356 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1357 QualType ComplexType = S.Context.getComplexType(ScalarType);
1358 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1359 CK_IntegralRealToComplex);
1360
1361 return ComplexType;
1362 }
1363
1364 assert(RHSComplexInt)(static_cast <bool> (RHSComplexInt) ? void (0) : __assert_fail
("RHSComplexInt", "clang/lib/Sema/SemaExpr.cpp", 1364, __extension__
__PRETTY_FUNCTION__))
;
1365
1366 QualType RHSEltType = RHSComplexInt->getElementType();
1367 QualType ScalarType =
1368 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1369 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1370 QualType ComplexType = S.Context.getComplexType(ScalarType);
1371
1372 if (!IsCompAssign)
1373 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1374 CK_IntegralRealToComplex);
1375 return ComplexType;
1376}
1377
1378/// Return the rank of a given fixed point or integer type. The value itself
1379/// doesn't matter, but the values must be increasing with proper increasing
1380/// rank as described in N1169 4.1.1.
1381static unsigned GetFixedPointRank(QualType Ty) {
1382 const auto *BTy = Ty->getAs<BuiltinType>();
1383 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", 1383, __extension__ __PRETTY_FUNCTION__
))
;
1384
1385 switch (BTy->getKind()) {
1386 case BuiltinType::ShortFract:
1387 case BuiltinType::UShortFract:
1388 case BuiltinType::SatShortFract:
1389 case BuiltinType::SatUShortFract:
1390 return 1;
1391 case BuiltinType::Fract:
1392 case BuiltinType::UFract:
1393 case BuiltinType::SatFract:
1394 case BuiltinType::SatUFract:
1395 return 2;
1396 case BuiltinType::LongFract:
1397 case BuiltinType::ULongFract:
1398 case BuiltinType::SatLongFract:
1399 case BuiltinType::SatULongFract:
1400 return 3;
1401 case BuiltinType::ShortAccum:
1402 case BuiltinType::UShortAccum:
1403 case BuiltinType::SatShortAccum:
1404 case BuiltinType::SatUShortAccum:
1405 return 4;
1406 case BuiltinType::Accum:
1407 case BuiltinType::UAccum:
1408 case BuiltinType::SatAccum:
1409 case BuiltinType::SatUAccum:
1410 return 5;
1411 case BuiltinType::LongAccum:
1412 case BuiltinType::ULongAccum:
1413 case BuiltinType::SatLongAccum:
1414 case BuiltinType::SatULongAccum:
1415 return 6;
1416 default:
1417 if (BTy->isInteger())
1418 return 0;
1419 llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type"
, "clang/lib/Sema/SemaExpr.cpp", 1419)
;
1420 }
1421}
1422
1423/// handleFixedPointConversion - Fixed point operations between fixed
1424/// point types and integers or other fixed point types do not fall under
1425/// usual arithmetic conversion since these conversions could result in loss
1426/// of precsision (N1169 4.1.4). These operations should be calculated with
1427/// the full precision of their result type (N1169 4.1.6.2.1).
1428static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1429 QualType RHSTy) {
1430 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", 1431, __extension__ __PRETTY_FUNCTION__
))
1431 "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", 1431, __extension__ __PRETTY_FUNCTION__
))
;
1432 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", 1435, __extension__ __PRETTY_FUNCTION__
))
1433 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", 1435, __extension__ __PRETTY_FUNCTION__
))
1434 "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", 1435, __extension__ __PRETTY_FUNCTION__
))
1435 "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", 1435, __extension__ __PRETTY_FUNCTION__
))
;
1436
1437 // If one operand has signed fixed-point type and the other operand has
1438 // unsigned fixed-point type, then the unsigned fixed-point operand is
1439 // converted to its corresponding signed fixed-point type and the resulting
1440 // type is the type of the converted operand.
1441 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1442 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1443 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1444 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1445
1446 // The result type is the type with the highest rank, whereby a fixed-point
1447 // conversion rank is always greater than an integer conversion rank; if the
1448 // type of either of the operands is a saturating fixedpoint type, the result
1449 // type shall be the saturating fixed-point type corresponding to the type
1450 // with the highest rank; the resulting value is converted (taking into
1451 // account rounding and overflow) to the precision of the resulting type.
1452 // Same ranks between signed and unsigned types are resolved earlier, so both
1453 // types are either signed or both unsigned at this point.
1454 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1455 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1456
1457 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1458
1459 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1460 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1461
1462 return ResultTy;
1463}
1464
1465/// Check that the usual arithmetic conversions can be performed on this pair of
1466/// expressions that might be of enumeration type.
1467static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1468 SourceLocation Loc,
1469 Sema::ArithConvKind ACK) {
1470 // C++2a [expr.arith.conv]p1:
1471 // If one operand is of enumeration type and the other operand is of a
1472 // different enumeration type or a floating-point type, this behavior is
1473 // deprecated ([depr.arith.conv.enum]).
1474 //
1475 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1476 // Eventually we will presumably reject these cases (in C++23 onwards?).
1477 QualType L = LHS->getType(), R = RHS->getType();
1478 bool LEnum = L->isUnscopedEnumerationType(),
1479 REnum = R->isUnscopedEnumerationType();
1480 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1481 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1482 (REnum && L->isFloatingType())) {
1483 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1484 ? diag::warn_arith_conv_enum_float_cxx20
1485 : diag::warn_arith_conv_enum_float)
1486 << LHS->getSourceRange() << RHS->getSourceRange()
1487 << (int)ACK << LEnum << L << R;
1488 } else if (!IsCompAssign && LEnum && REnum &&
1489 !S.Context.hasSameUnqualifiedType(L, R)) {
1490 unsigned DiagID;
1491 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1492 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1493 // If either enumeration type is unnamed, it's less likely that the
1494 // user cares about this, but this situation is still deprecated in
1495 // C++2a. Use a different warning group.
1496 DiagID = S.getLangOpts().CPlusPlus20
1497 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1498 : diag::warn_arith_conv_mixed_anon_enum_types;
1499 } else if (ACK == Sema::ACK_Conditional) {
1500 // Conditional expressions are separated out because they have
1501 // historically had a different warning flag.
1502 DiagID = S.getLangOpts().CPlusPlus20
1503 ? diag::warn_conditional_mixed_enum_types_cxx20
1504 : diag::warn_conditional_mixed_enum_types;
1505 } else if (ACK == Sema::ACK_Comparison) {
1506 // Comparison expressions are separated out because they have
1507 // historically had a different warning flag.
1508 DiagID = S.getLangOpts().CPlusPlus20
1509 ? diag::warn_comparison_mixed_enum_types_cxx20
1510 : diag::warn_comparison_mixed_enum_types;
1511 } else {
1512 DiagID = S.getLangOpts().CPlusPlus20
1513 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1514 : diag::warn_arith_conv_mixed_enum_types;
1515 }
1516 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1517 << (int)ACK << L << R;
1518 }
1519}
1520
1521/// UsualArithmeticConversions - Performs various conversions that are common to
1522/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1523/// routine returns the first non-arithmetic type found. The client is
1524/// responsible for emitting appropriate error diagnostics.
1525QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1526 SourceLocation Loc,
1527 ArithConvKind ACK) {
1528 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1529
1530 if (ACK != ACK_CompAssign) {
1531 LHS = UsualUnaryConversions(LHS.get());
1532 if (LHS.isInvalid())
1533 return QualType();
1534 }
1535
1536 RHS = UsualUnaryConversions(RHS.get());
1537 if (RHS.isInvalid())
1538 return QualType();
1539
1540 // For conversion purposes, we ignore any qualifiers.
1541 // For example, "const float" and "float" are equivalent.
1542 QualType LHSType =
1543 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1544 QualType RHSType =
1545 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1546
1547 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1548 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1549 LHSType = AtomicLHS->getValueType();
1550
1551 // If both types are identical, no conversion is needed.
1552 if (LHSType == RHSType)
1553 return LHSType;
1554
1555 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1556 // The caller can deal with this (e.g. pointer + int).
1557 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1558 return QualType();
1559
1560 // Apply unary and bitfield promotions to the LHS's type.
1561 QualType LHSUnpromotedType = LHSType;
1562 if (LHSType->isPromotableIntegerType())
1563 LHSType = Context.getPromotedIntegerType(LHSType);
1564 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1565 if (!LHSBitfieldPromoteTy.isNull())
1566 LHSType = LHSBitfieldPromoteTy;
1567 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1568 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1569
1570 // If both types are identical, no conversion is needed.
1571 if (LHSType == RHSType)
1572 return LHSType;
1573
1574 // At this point, we have two different arithmetic types.
1575
1576 // Diagnose attempts to convert between __ibm128, __float128 and long double
1577 // where such conversions currently can't be handled.
1578 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1579 return QualType();
1580
1581 // Handle complex types first (C99 6.3.1.8p1).
1582 if (LHSType->isComplexType() || RHSType->isComplexType())
1583 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1584 ACK == ACK_CompAssign);
1585
1586 // Now handle "real" floating types (i.e. float, double, long double).
1587 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1588 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1589 ACK == ACK_CompAssign);
1590
1591 // Handle GCC complex int extension.
1592 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1593 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1594 ACK == ACK_CompAssign);
1595
1596 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1597 return handleFixedPointConversion(*this, LHSType, RHSType);
1598
1599 // Finally, we have two differing integer types.
1600 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1601 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1602}
1603
1604//===----------------------------------------------------------------------===//
1605// Semantic Analysis for various Expression Types
1606//===----------------------------------------------------------------------===//
1607
1608
1609ExprResult
1610Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1611 SourceLocation DefaultLoc,
1612 SourceLocation RParenLoc,
1613 Expr *ControllingExpr,
1614 ArrayRef<ParsedType> ArgTypes,
1615 ArrayRef<Expr *> ArgExprs) {
1616 unsigned NumAssocs = ArgTypes.size();
1617 assert(NumAssocs == ArgExprs.size())(static_cast <bool> (NumAssocs == ArgExprs.size()) ? void
(0) : __assert_fail ("NumAssocs == ArgExprs.size()", "clang/lib/Sema/SemaExpr.cpp"
, 1617, __extension__ __PRETTY_FUNCTION__))
;
1618
1619 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1620 for (unsigned i = 0; i < NumAssocs; ++i) {
1621 if (ArgTypes[i])
1622 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1623 else
1624 Types[i] = nullptr;
1625 }
1626
1627 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1628 ControllingExpr,
1629 llvm::makeArrayRef(Types, NumAssocs),
1630 ArgExprs);
1631 delete [] Types;
1632 return ER;
1633}
1634
1635ExprResult
1636Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1637 SourceLocation DefaultLoc,
1638 SourceLocation RParenLoc,
1639 Expr *ControllingExpr,
1640 ArrayRef<TypeSourceInfo *> Types,
1641 ArrayRef<Expr *> Exprs) {
1642 unsigned NumAssocs = Types.size();
1643 assert(NumAssocs == Exprs.size())(static_cast <bool> (NumAssocs == Exprs.size()) ? void (
0) : __assert_fail ("NumAssocs == Exprs.size()", "clang/lib/Sema/SemaExpr.cpp"
, 1643, __extension__ __PRETTY_FUNCTION__))
;
1644
1645 // Decay and strip qualifiers for the controlling expression type, and handle
1646 // placeholder type replacement. See committee discussion from WG14 DR423.
1647 {
1648 EnterExpressionEvaluationContext Unevaluated(
1649 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1650 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1651 if (R.isInvalid())
1652 return ExprError();
1653 ControllingExpr = R.get();
1654 }
1655
1656 // The controlling expression is an unevaluated operand, so side effects are
1657 // likely unintended.
1658 if (!inTemplateInstantiation() &&
1659 ControllingExpr->HasSideEffects(Context, false))
1660 Diag(ControllingExpr->getExprLoc(),
1661 diag::warn_side_effects_unevaluated_context);
1662
1663 bool TypeErrorFound = false,
1664 IsResultDependent = ControllingExpr->isTypeDependent(),
1665 ContainsUnexpandedParameterPack
1666 = ControllingExpr->containsUnexpandedParameterPack();
1667
1668 for (unsigned i = 0; i < NumAssocs; ++i) {
1669 if (Exprs[i]->containsUnexpandedParameterPack())
1670 ContainsUnexpandedParameterPack = true;
1671
1672 if (Types[i]) {
1673 if (Types[i]->getType()->containsUnexpandedParameterPack())
1674 ContainsUnexpandedParameterPack = true;
1675
1676 if (Types[i]->getType()->isDependentType()) {
1677 IsResultDependent = true;
1678 } else {
1679 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1680 // complete object type other than a variably modified type."
1681 unsigned D = 0;
1682 if (Types[i]->getType()->isIncompleteType())
1683 D = diag::err_assoc_type_incomplete;
1684 else if (!Types[i]->getType()->isObjectType())
1685 D = diag::err_assoc_type_nonobject;
1686 else if (Types[i]->getType()->isVariablyModifiedType())
1687 D = diag::err_assoc_type_variably_modified;
1688
1689 if (D != 0) {
1690 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1691 << Types[i]->getTypeLoc().getSourceRange()
1692 << Types[i]->getType();
1693 TypeErrorFound = true;
1694 }
1695
1696 // C11 6.5.1.1p2 "No two generic associations in the same generic
1697 // selection shall specify compatible types."
1698 for (unsigned j = i+1; j < NumAssocs; ++j)
1699 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1700 Context.typesAreCompatible(Types[i]->getType(),
1701 Types[j]->getType())) {
1702 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1703 diag::err_assoc_compatible_types)
1704 << Types[j]->getTypeLoc().getSourceRange()
1705 << Types[j]->getType()
1706 << Types[i]->getType();
1707 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1708 diag::note_compat_assoc)
1709 << Types[i]->getTypeLoc().getSourceRange()
1710 << Types[i]->getType();
1711 TypeErrorFound = true;
1712 }
1713 }
1714 }
1715 }
1716 if (TypeErrorFound)
1717 return ExprError();
1718
1719 // If we determined that the generic selection is result-dependent, don't
1720 // try to compute the result expression.
1721 if (IsResultDependent)
1722 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1723 Exprs, DefaultLoc, RParenLoc,
1724 ContainsUnexpandedParameterPack);
1725
1726 SmallVector<unsigned, 1> CompatIndices;
1727 unsigned DefaultIndex = -1U;
1728 for (unsigned i = 0; i < NumAssocs; ++i) {
1729 if (!Types[i])
1730 DefaultIndex = i;
1731 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1732 Types[i]->getType()))
1733 CompatIndices.push_back(i);
1734 }
1735
1736 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1737 // type compatible with at most one of the types named in its generic
1738 // association list."
1739 if (CompatIndices.size() > 1) {
1740 // We strip parens here because the controlling expression is typically
1741 // parenthesized in macro definitions.
1742 ControllingExpr = ControllingExpr->IgnoreParens();
1743 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1744 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1745 << (unsigned)CompatIndices.size();
1746 for (unsigned I : CompatIndices) {
1747 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1748 diag::note_compat_assoc)
1749 << Types[I]->getTypeLoc().getSourceRange()
1750 << Types[I]->getType();
1751 }
1752 return ExprError();
1753 }
1754
1755 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1756 // its controlling expression shall have type compatible with exactly one of
1757 // the types named in its generic association list."
1758 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1759 // We strip parens here because the controlling expression is typically
1760 // parenthesized in macro definitions.
1761 ControllingExpr = ControllingExpr->IgnoreParens();
1762 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1763 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1764 return ExprError();
1765 }
1766
1767 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1768 // type name that is compatible with the type of the controlling expression,
1769 // then the result expression of the generic selection is the expression
1770 // in that generic association. Otherwise, the result expression of the
1771 // generic selection is the expression in the default generic association."
1772 unsigned ResultIndex =
1773 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1774
1775 return GenericSelectionExpr::Create(
1776 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1777 ContainsUnexpandedParameterPack, ResultIndex);
1778}
1779
1780/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1781/// location of the token and the offset of the ud-suffix within it.
1782static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1783 unsigned Offset) {
1784 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1785 S.getLangOpts());
1786}
1787
1788/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1789/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1790static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1791 IdentifierInfo *UDSuffix,
1792 SourceLocation UDSuffixLoc,
1793 ArrayRef<Expr*> Args,
1794 SourceLocation LitEndLoc) {
1795 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", 1795, __extension__ __PRETTY_FUNCTION__
))
;
1796
1797 QualType ArgTy[2];
1798 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1799 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1800 if (ArgTy[ArgIdx]->isArrayType())
1801 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1802 }
1803
1804 DeclarationName OpName =
1805 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1806 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1807 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1808
1809 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1810 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1811 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1812 /*AllowStringTemplatePack*/ false,
1813 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1814 return ExprError();
1815
1816 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1817}
1818
1819/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1820/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1821/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1822/// multiple tokens. However, the common case is that StringToks points to one
1823/// string.
1824///
1825ExprResult
1826Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1827 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", 1827, __extension__ __PRETTY_FUNCTION__
))
;
1828
1829 StringLiteralParser Literal(StringToks, PP);
1830 if (Literal.hadError)
1831 return ExprError();
1832
1833 SmallVector<SourceLocation, 4> StringTokLocs;
1834 for (const Token &Tok : StringToks)
1835 StringTokLocs.push_back(Tok.getLocation());
1836
1837 QualType CharTy = Context.CharTy;
1838 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1839 if (Literal.isWide()) {
1840 CharTy = Context.getWideCharType();
1841 Kind = StringLiteral::Wide;
1842 } else if (Literal.isUTF8()) {
1843 if (getLangOpts().Char8)
1844 CharTy = Context.Char8Ty;
1845 Kind = StringLiteral::UTF8;
1846 } else if (Literal.isUTF16()) {
1847 CharTy = Context.Char16Ty;
1848 Kind = StringLiteral::UTF16;
1849 } else if (Literal.isUTF32()) {
1850 CharTy = Context.Char32Ty;
1851 Kind = StringLiteral::UTF32;
1852 } else if (Literal.isPascal()) {
1853 CharTy = Context.UnsignedCharTy;
1854 }
1855
1856 // Warn on initializing an array of char from a u8 string literal; this
1857 // becomes ill-formed in C++2a.
1858 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1859 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1860 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1861
1862 // Create removals for all 'u8' prefixes in the string literal(s). This
1863 // ensures C++2a compatibility (but may change the program behavior when
1864 // built by non-Clang compilers for which the execution character set is
1865 // not always UTF-8).
1866 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1867 SourceLocation RemovalDiagLoc;
1868 for (const Token &Tok : StringToks) {
1869 if (Tok.getKind() == tok::utf8_string_literal) {
1870 if (RemovalDiagLoc.isInvalid())
1871 RemovalDiagLoc = Tok.getLocation();
1872 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1873 Tok.getLocation(),
1874 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1875 getSourceManager(), getLangOpts())));
1876 }
1877 }
1878 Diag(RemovalDiagLoc, RemovalDiag);
1879 }
1880
1881 QualType StrTy =
1882 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1883
1884 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1885 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1886 Kind, Literal.Pascal, StrTy,
1887 &StringTokLocs[0],
1888 StringTokLocs.size());
1889 if (Literal.getUDSuffix().empty())
1890 return Lit;
1891
1892 // We're building a user-defined literal.
1893 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1894 SourceLocation UDSuffixLoc =
1895 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1896 Literal.getUDSuffixOffset());
1897
1898 // Make sure we're allowed user-defined literals here.
1899 if (!UDLScope)
1900 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1901
1902 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1903 // operator "" X (str, len)
1904 QualType SizeType = Context.getSizeType();
1905
1906 DeclarationName OpName =
1907 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1908 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1909 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1910
1911 QualType ArgTy[] = {
1912 Context.getArrayDecayedType(StrTy), SizeType
1913 };
1914
1915 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1916 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1917 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1918 /*AllowStringTemplatePack*/ true,
1919 /*DiagnoseMissing*/ true, Lit)) {
1920
1921 case LOLR_Cooked: {
1922 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1923 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1924 StringTokLocs[0]);
1925 Expr *Args[] = { Lit, LenArg };
1926
1927 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1928 }
1929
1930 case LOLR_Template: {
1931 TemplateArgumentListInfo ExplicitArgs;
1932 TemplateArgument Arg(Lit);
1933 TemplateArgumentLocInfo ArgInfo(Lit);
1934 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1935 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1936 &ExplicitArgs);
1937 }
1938
1939 case LOLR_StringTemplatePack: {
1940 TemplateArgumentListInfo ExplicitArgs;
1941
1942 unsigned CharBits = Context.getIntWidth(CharTy);
1943 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1944 llvm::APSInt Value(CharBits, CharIsUnsigned);
1945
1946 TemplateArgument TypeArg(CharTy);
1947 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1948 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1949
1950 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1951 Value = Lit->getCodeUnit(I);
1952 TemplateArgument Arg(Context, Value, CharTy);
1953 TemplateArgumentLocInfo ArgInfo;
1954 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1955 }
1956 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1957 &ExplicitArgs);
1958 }
1959 case LOLR_Raw:
1960 case LOLR_ErrorNoDiagnostic:
1961 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 1961)
;
1962 case LOLR_Error:
1963 return ExprError();
1964 }
1965 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 1965)
;
1966}
1967
1968DeclRefExpr *
1969Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1970 SourceLocation Loc,
1971 const CXXScopeSpec *SS) {
1972 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1973 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1974}
1975
1976DeclRefExpr *
1977Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1978 const DeclarationNameInfo &NameInfo,
1979 const CXXScopeSpec *SS, NamedDecl *FoundD,
1980 SourceLocation TemplateKWLoc,
1981 const TemplateArgumentListInfo *TemplateArgs) {
1982 NestedNameSpecifierLoc NNS =
1983 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1984 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1985 TemplateArgs);
1986}
1987
1988// CUDA/HIP: Check whether a captured reference variable is referencing a
1989// host variable in a device or host device lambda.
1990static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1991 VarDecl *VD) {
1992 if (!S.getLangOpts().CUDA || !VD->hasInit())
1993 return false;
1994 assert(VD->getType()->isReferenceType())(static_cast <bool> (VD->getType()->isReferenceType
()) ? void (0) : __assert_fail ("VD->getType()->isReferenceType()"
, "clang/lib/Sema/SemaExpr.cpp", 1994, __extension__ __PRETTY_FUNCTION__
))
;
1995
1996 // Check whether the reference variable is referencing a host variable.
1997 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1998 if (!DRE)
1999 return false;
2000 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2001 if (!Referee || !Referee->hasGlobalStorage() ||
2002 Referee->hasAttr<CUDADeviceAttr>())
2003 return false;
2004
2005 // Check whether the current function is a device or host device lambda.
2006 // Check whether the reference variable is a capture by getDeclContext()
2007 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2008 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2009 if (MD && MD->getParent()->isLambda() &&
2010 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2011 VD->getDeclContext() != MD)
2012 return true;
2013
2014 return false;
2015}
2016
2017NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2018 // A declaration named in an unevaluated operand never constitutes an odr-use.
2019 if (isUnevaluatedContext())
2020 return NOUR_Unevaluated;
2021
2022 // C++2a [basic.def.odr]p4:
2023 // A variable x whose name appears as a potentially-evaluated expression e
2024 // is odr-used by e unless [...] x is a reference that is usable in
2025 // constant expressions.
2026 // CUDA/HIP:
2027 // If a reference variable referencing a host variable is captured in a
2028 // device or host device lambda, the value of the referee must be copied
2029 // to the capture and the reference variable must be treated as odr-use
2030 // since the value of the referee is not known at compile time and must
2031 // be loaded from the captured.
2032 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2033 if (VD->getType()->isReferenceType() &&
2034 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2035 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2036 VD->isUsableInConstantExpressions(Context))
2037 return NOUR_Constant;
2038 }
2039
2040 // All remaining non-variable cases constitute an odr-use. For variables, we
2041 // need to wait and see how the expression is used.
2042 return NOUR_None;
2043}
2044
2045/// BuildDeclRefExpr - Build an expression that references a
2046/// declaration that does not require a closure capture.
2047DeclRefExpr *
2048Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2049 const DeclarationNameInfo &NameInfo,
2050 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2051 SourceLocation TemplateKWLoc,
2052 const TemplateArgumentListInfo *TemplateArgs) {
2053 bool RefersToCapturedVariable =
2054 isa<VarDecl>(D) &&
2055 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2056
2057 DeclRefExpr *E = DeclRefExpr::Create(
2058 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2059 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2060 MarkDeclRefReferenced(E);
2061
2062 // C++ [except.spec]p17:
2063 // An exception-specification is considered to be needed when:
2064 // - in an expression, the function is the unique lookup result or
2065 // the selected member of a set of overloaded functions.
2066 //
2067 // We delay doing this until after we've built the function reference and
2068 // marked it as used so that:
2069 // a) if the function is defaulted, we get errors from defining it before /
2070 // instead of errors from computing its exception specification, and
2071 // b) if the function is a defaulted comparison, we can use the body we
2072 // build when defining it as input to the exception specification
2073 // computation rather than computing a new body.
2074 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2075 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2076 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2077 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2078 }
2079 }
2080
2081 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2082 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2083 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2084 getCurFunction()->recordUseOfWeak(E);
2085
2086 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2087 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2088 FD = IFD->getAnonField();
2089 if (FD) {
2090 UnusedPrivateFields.remove(FD);
2091 // Just in case we're building an illegal pointer-to-member.
2092 if (FD->isBitField())
2093 E->setObjectKind(OK_BitField);
2094 }
2095
2096 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2097 // designates a bit-field.
2098 if (auto *BD = dyn_cast<BindingDecl>(D))
2099 if (auto *BE = BD->getBinding())
2100 E->setObjectKind(BE->getObjectKind());
2101
2102 return E;
2103}
2104
2105/// Decomposes the given name into a DeclarationNameInfo, its location, and
2106/// possibly a list of template arguments.
2107///
2108/// If this produces template arguments, it is permitted to call
2109/// DecomposeTemplateName.
2110///
2111/// This actually loses a lot of source location information for
2112/// non-standard name kinds; we should consider preserving that in
2113/// some way.
2114void
2115Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2116 TemplateArgumentListInfo &Buffer,
2117 DeclarationNameInfo &NameInfo,
2118 const TemplateArgumentListInfo *&TemplateArgs) {
2119 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2120 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2121 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2122
2123 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2124 Id.TemplateId->NumArgs);
2125 translateTemplateArguments(TemplateArgsPtr, Buffer);
2126
2127 TemplateName TName = Id.TemplateId->Template.get();
2128 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2129 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2130 TemplateArgs = &Buffer;
2131 } else {
2132 NameInfo = GetNameFromUnqualifiedId(Id);
2133 TemplateArgs = nullptr;
2134 }
2135}
2136
2137static void emitEmptyLookupTypoDiagnostic(
2138 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2139 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2140 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2141 DeclContext *Ctx =
2142 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2143 if (!TC) {
2144 // Emit a special diagnostic for failed member lookups.
2145 // FIXME: computing the declaration context might fail here (?)
2146 if (Ctx)
2147 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2148 << SS.getRange();
2149 else
2150 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2151 return;
2152 }
2153
2154 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2155 bool DroppedSpecifier =
2156 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2157 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2158 ? diag::note_implicit_param_decl
2159 : diag::note_previous_decl;
2160 if (!Ctx)
2161 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2162 SemaRef.PDiag(NoteID));
2163 else
2164 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2165 << Typo << Ctx << DroppedSpecifier
2166 << SS.getRange(),
2167 SemaRef.PDiag(NoteID));
2168}
2169
2170/// Diagnose a lookup that found results in an enclosing class during error
2171/// recovery. This usually indicates that the results were found in a dependent
2172/// base class that could not be searched as part of a template definition.
2173/// Always issues a diagnostic (though this may be only a warning in MS
2174/// compatibility mode).
2175///
2176/// Return \c true if the error is unrecoverable, or \c false if the caller
2177/// should attempt to recover using these lookup results.
2178bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2179 // During a default argument instantiation the CurContext points
2180 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2181 // function parameter list, hence add an explicit check.
2182 bool isDefaultArgument =
2183 !CodeSynthesisContexts.empty() &&
2184 CodeSynthesisContexts.back().Kind ==
2185 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2186 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2187 bool isInstance = CurMethod && CurMethod->isInstance() &&
2188 R.getNamingClass() == CurMethod->getParent() &&
2189 !isDefaultArgument;
2190
2191 // There are two ways we can find a class-scope declaration during template
2192 // instantiation that we did not find in the template definition: if it is a
2193 // member of a dependent base class, or if it is declared after the point of
2194 // use in the same class. Distinguish these by comparing the class in which
2195 // the member was found to the naming class of the lookup.
2196 unsigned DiagID = diag::err_found_in_dependent_base;
2197 unsigned NoteID = diag::note_member_declared_at;
2198 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2199 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2200 : diag::err_found_later_in_class;
2201 } else if (getLangOpts().MSVCCompat) {
2202 DiagID = diag::ext_found_in_dependent_base;
2203 NoteID = diag::note_dependent_member_use;
2204 }
2205
2206 if (isInstance) {
2207 // Give a code modification hint to insert 'this->'.
2208 Diag(R.getNameLoc(), DiagID)
2209 << R.getLookupName()
2210 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2211 CheckCXXThisCapture(R.getNameLoc());
2212 } else {
2213 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2214 // they're not shadowed).
2215 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2216 }
2217
2218 for (NamedDecl *D : R)
2219 Diag(D->getLocation(), NoteID);
2220
2221 // Return true if we are inside a default argument instantiation
2222 // and the found name refers to an instance member function, otherwise
2223 // the caller will try to create an implicit member call and this is wrong
2224 // for default arguments.
2225 //
2226 // FIXME: Is this special case necessary? We could allow the caller to
2227 // diagnose this.
2228 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2229 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2230 return true;
2231 }
2232
2233 // Tell the callee to try to recover.
2234 return false;
2235}
2236
2237/// Diagnose an empty lookup.
2238///
2239/// \return false if new lookup candidates were found
2240bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2241 CorrectionCandidateCallback &CCC,
2242 TemplateArgumentListInfo *ExplicitTemplateArgs,
2243 ArrayRef<Expr *> Args, TypoExpr **Out) {
2244 DeclarationName Name = R.getLookupName();
2245
2246 unsigned diagnostic = diag::err_undeclared_var_use;
2247 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2248 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2249 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2250 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2251 diagnostic = diag::err_undeclared_use;
2252 diagnostic_suggest = diag::err_undeclared_use_suggest;
2253 }
2254
2255 // If the original lookup was an unqualified lookup, fake an
2256 // unqualified lookup. This is useful when (for example) the
2257 // original lookup would not have found something because it was a
2258 // dependent name.
2259 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2260 while (DC) {
2261 if (isa<CXXRecordDecl>(DC)) {
2262 LookupQualifiedName(R, DC);
2263
2264 if (!R.empty()) {
2265 // Don't give errors about ambiguities in this lookup.
2266 R.suppressDiagnostics();
2267
2268 // If there's a best viable function among the results, only mention
2269 // that one in the notes.
2270 OverloadCandidateSet Candidates(R.getNameLoc(),
2271 OverloadCandidateSet::CSK_Normal);
2272 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2273 OverloadCandidateSet::iterator Best;
2274 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2275 OR_Success) {
2276 R.clear();
2277 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2278 R.resolveKind();
2279 }
2280
2281 return DiagnoseDependentMemberLookup(R);
2282 }
2283
2284 R.clear();
2285 }
2286
2287 DC = DC->getLookupParent();
2288 }
2289
2290 // We didn't find anything, so try to correct for a typo.
2291 TypoCorrection Corrected;
2292 if (S && Out) {
2293 SourceLocation TypoLoc = R.getNameLoc();
2294 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", 2295, __extension__ __PRETTY_FUNCTION__
))
2295 "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", 2295, __extension__ __PRETTY_FUNCTION__
))
;
2296 *Out = CorrectTypoDelayed(
2297 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2298 [=](const TypoCorrection &TC) {
2299 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2300 diagnostic, diagnostic_suggest);
2301 },
2302 nullptr, CTK_ErrorRecovery);
2303 if (*Out)
2304 return true;
2305 } else if (S &&
2306 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2307 S, &SS, CCC, CTK_ErrorRecovery))) {
2308 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2309 bool DroppedSpecifier =
2310 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2311 R.setLookupName(Corrected.getCorrection());
2312
2313 bool AcceptableWithRecovery = false;
2314 bool AcceptableWithoutRecovery = false;
2315 NamedDecl *ND = Corrected.getFoundDecl();
2316 if (ND) {
2317 if (Corrected.isOverloaded()) {
2318 OverloadCandidateSet OCS(R.getNameLoc(),
2319 OverloadCandidateSet::CSK_Normal);
2320 OverloadCandidateSet::iterator Best;
2321 for (NamedDecl *CD : Corrected) {
2322 if (FunctionTemplateDecl *FTD =
2323 dyn_cast<FunctionTemplateDecl>(CD))
2324 AddTemplateOverloadCandidate(
2325 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2326 Args, OCS);
2327 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2328 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2329 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2330 Args, OCS);
2331 }
2332 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2333 case OR_Success:
2334 ND = Best->FoundDecl;
2335 Corrected.setCorrectionDecl(ND);
2336 break;
2337 default:
2338 // FIXME: Arbitrarily pick the first declaration for the note.
2339 Corrected.setCorrectionDecl(ND);
2340 break;
2341 }
2342 }
2343 R.addDecl(ND);
2344 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2345 CXXRecordDecl *Record = nullptr;
2346 if (Corrected.getCorrectionSpecifier()) {
2347 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2348 Record = Ty->getAsCXXRecordDecl();
2349 }
2350 if (!Record)
2351 Record = cast<CXXRecordDecl>(
2352 ND->getDeclContext()->getRedeclContext());
2353 R.setNamingClass(Record);
2354 }
2355
2356 auto *UnderlyingND = ND->getUnderlyingDecl();
2357 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2358 isa<FunctionTemplateDecl>(UnderlyingND);
2359 // FIXME: If we ended up with a typo for a type name or
2360 // Objective-C class name, we're in trouble because the parser
2361 // is in the wrong place to recover. Suggest the typo
2362 // correction, but don't make it a fix-it since we're not going
2363 // to recover well anyway.
2364 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2365 getAsTypeTemplateDecl(UnderlyingND) ||
2366 isa<ObjCInterfaceDecl>(UnderlyingND);
2367 } else {
2368 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2369 // because we aren't able to recover.
2370 AcceptableWithoutRecovery = true;
2371 }
2372
2373 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2374 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2375 ? diag::note_implicit_param_decl
2376 : diag::note_previous_decl;
2377 if (SS.isEmpty())
2378 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2379 PDiag(NoteID), AcceptableWithRecovery);
2380 else
2381 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2382 << Name << computeDeclContext(SS, false)
2383 << DroppedSpecifier << SS.getRange(),
2384 PDiag(NoteID), AcceptableWithRecovery);
2385
2386 // Tell the callee whether to try to recover.
2387 return !AcceptableWithRecovery;
2388 }
2389 }
2390 R.clear();
2391
2392 // Emit a special diagnostic for failed member lookups.
2393 // FIXME: computing the declaration context might fail here (?)
2394 if (!SS.isEmpty()) {
2395 Diag(R.getNameLoc(), diag::err_no_member)
2396 << Name << computeDeclContext(SS, false)
2397 << SS.getRange();
2398 return true;
2399 }
2400
2401 // Give up, we can't recover.
2402 Diag(R.getNameLoc(), diagnostic) << Name;
2403 return true;
2404}
2405
2406/// In Microsoft mode, if we are inside a template class whose parent class has
2407/// dependent base classes, and we can't resolve an unqualified identifier, then
2408/// assume the identifier is a member of a dependent base class. We can only
2409/// recover successfully in static methods, instance methods, and other contexts
2410/// where 'this' is available. This doesn't precisely match MSVC's
2411/// instantiation model, but it's close enough.
2412static Expr *
2413recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2414 DeclarationNameInfo &NameInfo,
2415 SourceLocation TemplateKWLoc,
2416 const TemplateArgumentListInfo *TemplateArgs) {
2417 // Only try to recover from lookup into dependent bases in static methods or
2418 // contexts where 'this' is available.
2419 QualType ThisType = S.getCurrentThisType();
2420 const CXXRecordDecl *RD = nullptr;
2421 if (!ThisType.isNull())
2422 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2423 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2424 RD = MD->getParent();
2425 if (!RD || !RD->hasAnyDependentBases())
2426 return nullptr;
2427
2428 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2429 // is available, suggest inserting 'this->' as a fixit.
2430 SourceLocation Loc = NameInfo.getLoc();
2431 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2432 DB << NameInfo.getName() << RD;
2433
2434 if (!ThisType.isNull()) {
2435 DB << FixItHint::CreateInsertion(Loc, "this->");
2436 return CXXDependentScopeMemberExpr::Create(
2437 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2438 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2439 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2440 }
2441
2442 // Synthesize a fake NNS that points to the derived class. This will
2443 // perform name lookup during template instantiation.
2444 CXXScopeSpec SS;
2445 auto *NNS =
2446 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2447 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2448 return DependentScopeDeclRefExpr::Create(
2449 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2450 TemplateArgs);
2451}
2452
2453ExprResult
2454Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2455 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2456 bool HasTrailingLParen, bool IsAddressOfOperand,
2457 CorrectionCandidateCallback *CCC,
2458 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2459 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", 2460, __extension__ __PRETTY_FUNCTION__
))
2460 "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", 2460, __extension__ __PRETTY_FUNCTION__
))
;
2461 if (SS.isInvalid())
2462 return ExprError();
2463
2464 TemplateArgumentListInfo TemplateArgsBuffer;
2465
2466 // Decompose the UnqualifiedId into the following data.
2467 DeclarationNameInfo NameInfo;
2468 const TemplateArgumentListInfo *TemplateArgs;
2469 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2470
2471 DeclarationName Name = NameInfo.getName();
2472 IdentifierInfo *II = Name.getAsIdentifierInfo();
2473 SourceLocation NameLoc = NameInfo.getLoc();
2474
2475 if (II && II->isEditorPlaceholder()) {
2476 // FIXME: When typed placeholders are supported we can create a typed
2477 // placeholder expression node.
2478 return ExprError();
2479 }
2480
2481 // C++ [temp.dep.expr]p3:
2482 // An id-expression is type-dependent if it contains:
2483 // -- an identifier that was declared with a dependent type,
2484 // (note: handled after lookup)
2485 // -- a template-id that is dependent,
2486 // (note: handled in BuildTemplateIdExpr)
2487 // -- a conversion-function-id that specifies a dependent type,
2488 // -- a nested-name-specifier that contains a class-name that
2489 // names a dependent type.
2490 // Determine whether this is a member of an unknown specialization;
2491 // we need to handle these differently.
2492 bool DependentID = false;
2493 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2494 Name.getCXXNameType()->isDependentType()) {
2495 DependentID = true;
2496 } else if (SS.isSet()) {
2497 if (DeclContext *DC = computeDeclContext(SS, false)) {
2498 if (RequireCompleteDeclContext(SS, DC))
2499 return ExprError();
2500 } else {
2501 DependentID = true;
2502 }
2503 }
2504
2505 if (DependentID)
2506 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2507 IsAddressOfOperand, TemplateArgs);
2508
2509 // Perform the required lookup.
2510 LookupResult R(*this, NameInfo,
2511 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2512 ? LookupObjCImplicitSelfParam
2513 : LookupOrdinaryName);
2514 if (TemplateKWLoc.isValid() || TemplateArgs) {
2515 // Lookup the template name again to correctly establish the context in
2516 // which it was found. This is really unfortunate as we already did the
2517 // lookup to determine that it was a template name in the first place. If
2518 // this becomes a performance hit, we can work harder to preserve those
2519 // results until we get here but it's likely not worth it.
2520 bool MemberOfUnknownSpecialization;
2521 AssumedTemplateKind AssumedTemplate;
2522 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2523 MemberOfUnknownSpecialization, TemplateKWLoc,
2524 &AssumedTemplate))
2525 return ExprError();
2526
2527 if (MemberOfUnknownSpecialization ||
2528 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2529 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2530 IsAddressOfOperand, TemplateArgs);
2531 } else {
2532 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2533 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2534
2535 // If the result might be in a dependent base class, this is a dependent
2536 // id-expression.
2537 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2538 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2539 IsAddressOfOperand, TemplateArgs);
2540
2541 // If this reference is in an Objective-C method, then we need to do
2542 // some special Objective-C lookup, too.
2543 if (IvarLookupFollowUp) {
2544 ExprResult E(LookupInObjCMethod(R, S, II, true));
2545 if (E.isInvalid())
2546 return ExprError();
2547
2548 if (Expr *Ex = E.getAs<Expr>())
2549 return Ex;
2550 }
2551 }
2552
2553 if (R.isAmbiguous())
2554 return ExprError();
2555
2556 // This could be an implicitly declared function reference (legal in C90,
2557 // extension in C99, forbidden in C++).
2558 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2559 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2560 if (D) R.addDecl(D);
2561 }
2562
2563 // Determine whether this name might be a candidate for
2564 // argument-dependent lookup.
2565 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2566
2567 if (R.empty() && !ADL) {
2568 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2569 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2570 TemplateKWLoc, TemplateArgs))
2571 return E;
2572 }
2573
2574 // Don't diagnose an empty lookup for inline assembly.
2575 if (IsInlineAsmIdentifier)
2576 return ExprError();
2577
2578 // If this name wasn't predeclared and if this is not a function
2579 // call, diagnose the problem.
2580 TypoExpr *TE = nullptr;
2581 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2582 : nullptr);
2583 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2584 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", 2585, __extension__ __PRETTY_FUNCTION__
))
2585 "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", 2585, __extension__ __PRETTY_FUNCTION__
))
;
2586 if (CCC) {
2587 // Make sure the callback knows what the typo being diagnosed is.
2588 CCC->setTypoName(II);
2589 if (SS.isValid())
2590 CCC->setTypoNNS(SS.getScopeRep());
2591 }
2592 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2593 // a template name, but we happen to have always already looked up the name
2594 // before we get here if it must be a template name.
2595 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2596 None, &TE)) {
2597 if (TE && KeywordReplacement) {
2598 auto &State = getTypoExprState(TE);
2599 auto BestTC = State.Consumer->getNextCorrection();
2600 if (BestTC.isKeyword()) {
2601 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2602 if (State.DiagHandler)
2603 State.DiagHandler(BestTC);
2604 KeywordReplacement->startToken();
2605 KeywordReplacement->setKind(II->getTokenID());
2606 KeywordReplacement->setIdentifierInfo(II);
2607 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2608 // Clean up the state associated with the TypoExpr, since it has
2609 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2610 clearDelayedTypo(TE);
2611 // Signal that a correction to a keyword was performed by returning a
2612 // valid-but-null ExprResult.
2613 return (Expr*)nullptr;
2614 }
2615 State.Consumer->resetCorrectionStream();
2616 }
2617 return TE ? TE : ExprError();
2618 }
2619
2620 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", 2621, __extension__ __PRETTY_FUNCTION__
))
2621 "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", 2621, __extension__ __PRETTY_FUNCTION__
))
;
2622
2623 // If we found an Objective-C instance variable, let
2624 // LookupInObjCMethod build the appropriate expression to
2625 // reference the ivar.
2626 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2627 R.clear();
2628 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2629 // In a hopelessly buggy code, Objective-C instance variable
2630 // lookup fails and no expression will be built to reference it.
2631 if (!E.isInvalid() && !E.get())
2632 return ExprError();
2633 return E;
2634 }
2635 }
2636
2637 // This is guaranteed from this point on.
2638 assert(!R.empty() || ADL)(static_cast <bool> (!R.empty() || ADL) ? void (0) : __assert_fail
("!R.empty() || ADL", "clang/lib/Sema/SemaExpr.cpp", 2638, __extension__
__PRETTY_FUNCTION__))
;
2639
2640 // Check whether this might be a C++ implicit instance member access.
2641 // C++ [class.mfct.non-static]p3:
2642 // When an id-expression that is not part of a class member access
2643 // syntax and not used to form a pointer to member is used in the
2644 // body of a non-static member function of class X, if name lookup
2645 // resolves the name in the id-expression to a non-static non-type
2646 // member of some class C, the id-expression is transformed into a
2647 // class member access expression using (*this) as the
2648 // postfix-expression to the left of the . operator.
2649 //
2650 // But we don't actually need to do this for '&' operands if R
2651 // resolved to a function or overloaded function set, because the
2652 // expression is ill-formed if it actually works out to be a
2653 // non-static member function:
2654 //
2655 // C++ [expr.ref]p4:
2656 // Otherwise, if E1.E2 refers to a non-static member function. . .
2657 // [t]he expression can be used only as the left-hand operand of a
2658 // member function call.
2659 //
2660 // There are other safeguards against such uses, but it's important
2661 // to get this right here so that we don't end up making a
2662 // spuriously dependent expression if we're inside a dependent
2663 // instance method.
2664 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2665 bool MightBeImplicitMember;
2666 if (!IsAddressOfOperand)
2667 MightBeImplicitMember = true;
2668 else if (!SS.isEmpty())
2669 MightBeImplicitMember = false;
2670 else if (R.isOverloadedResult())
2671 MightBeImplicitMember = false;
2672 else if (R.isUnresolvableResult())
2673 MightBeImplicitMember = true;
2674 else
2675 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2676 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2677 isa<MSPropertyDecl>(R.getFoundDecl());
2678
2679 if (MightBeImplicitMember)
2680 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2681 R, TemplateArgs, S);
2682 }
2683
2684 if (TemplateArgs || TemplateKWLoc.isValid()) {
2685
2686 // In C++1y, if this is a variable template id, then check it
2687 // in BuildTemplateIdExpr().
2688 // The single lookup result must be a variable template declaration.
2689 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2690 Id.TemplateId->Kind == TNK_Var_template) {
2691 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", 2692, __extension__ __PRETTY_FUNCTION__
))
2692 "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", 2692, __extension__ __PRETTY_FUNCTION__
))
;
2693 }
2694
2695 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2696 }
2697
2698 return BuildDeclarationNameExpr(SS, R, ADL);
2699}
2700
2701ExprResult Sema::ActOnMutableAgnosticIdExpression(Scope *S, CXXScopeSpec &SS,
2702 UnqualifiedId &Id) {
2703 MutableAgnosticContextRAII Ctx(*this);
2704 return ActOnIdExpression(S, SS, /*TemplateKwLoc*/
2705 SourceLocation(), Id,
2706 /*HasTrailingLParen*/ false,
2707 /*IsAddressOfOperand*/ false,
2708 /*CorrectionCandidateCallback*/ nullptr,
2709 /*IsInlineAsmIdentifier*/ false,
2710 /*KeywordReplacement*/ nullptr);
2711}
2712
2713/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2714/// declaration name, generally during template instantiation.
2715/// There's a large number of things which don't need to be done along
2716/// this path.
2717ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2718 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2719 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2720 DeclContext *DC = computeDeclContext(SS, false);
2721 if (!DC)
2722 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2723 NameInfo, /*TemplateArgs=*/nullptr);
2724
2725 if (RequireCompleteDeclContext(SS, DC))
2726 return ExprError();
2727
2728 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2729 LookupQualifiedName(R, DC);
2730
2731 if (R.isAmbiguous())
2732 return ExprError();
2733
2734 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2735 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2736 NameInfo, /*TemplateArgs=*/nullptr);
2737
2738 if (R.empty()) {
2739 // Don't diagnose problems with invalid record decl, the secondary no_member
2740 // diagnostic during template instantiation is likely bogus, e.g. if a class
2741 // is invalid because it's derived from an invalid base class, then missing
2742 // members were likely supposed to be inherited.
2743 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2744 if (CD->isInvalidDecl())
2745 return ExprError();
2746 Diag(NameInfo.getLoc(), diag::err_no_member)
2747 << NameInfo.getName() << DC << SS.getRange();
2748 return ExprError();
2749 }
2750
2751 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2752 // Diagnose a missing typename if this resolved unambiguously to a type in
2753 // a dependent context. If we can recover with a type, downgrade this to
2754 // a warning in Microsoft compatibility mode.
2755 unsigned DiagID = diag::err_typename_missing;
2756 if (RecoveryTSI && getLangOpts().MSVCCompat)
2757 DiagID = diag::ext_typename_missing;
2758 SourceLocation Loc = SS.getBeginLoc();
2759 auto D = Diag(Loc, DiagID);
2760 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2761 << SourceRange(Loc, NameInfo.getEndLoc());
2762
2763 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2764 // context.
2765 if (!RecoveryTSI)
2766 return ExprError();
2767
2768 // Only issue the fixit if we're prepared to recover.
2769 D << FixItHint::CreateInsertion(Loc, "typename ");
2770
2771 // Recover by pretending this was an elaborated type.
2772 QualType Ty = Context.getTypeDeclType(TD);
2773 TypeLocBuilder TLB;
2774 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2775
2776 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2777 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2778 QTL.setElaboratedKeywordLoc(SourceLocation());
2779 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2780
2781 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2782
2783 return ExprEmpty();
2784 }
2785
2786 // Defend against this resolving to an implicit member access. We usually
2787 // won't get here if this might be a legitimate a class member (we end up in
2788 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2789 // a pointer-to-member or in an unevaluated context in C++11.
2790 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2791 return BuildPossibleImplicitMemberExpr(SS,
2792 /*TemplateKWLoc=*/SourceLocation(),
2793 R, /*TemplateArgs=*/nullptr, S);
2794
2795 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2796}
2797
2798/// The parser has read a name in, and Sema has detected that we're currently
2799/// inside an ObjC method. Perform some additional checks and determine if we
2800/// should form a reference to an ivar.
2801///
2802/// Ideally, most of this would be done by lookup, but there's
2803/// actually quite a lot of extra work involved.
2804DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2805 IdentifierInfo *II) {
2806 SourceLocation Loc = Lookup.getNameLoc();
2807 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2808
2809 // Check for error condition which is already reported.
2810 if (!CurMethod)
2811 return DeclResult(true);
2812
2813 // There are two cases to handle here. 1) scoped lookup could have failed,
2814 // in which case we should look for an ivar. 2) scoped lookup could have
2815 // found a decl, but that decl is outside the current instance method (i.e.
2816 // a global variable). In these two cases, we do a lookup for an ivar with
2817 // this name, if the lookup sucedes, we replace it our current decl.
2818
2819 // If we're in a class method, we don't normally want to look for
2820 // ivars. But if we don't find anything else, and there's an
2821 // ivar, that's an error.
2822 bool IsClassMethod = CurMethod->isClassMethod();
2823
2824 bool LookForIvars;
2825 if (Lookup.empty())
2826 LookForIvars = true;
2827 else if (IsClassMethod)
2828 LookForIvars = false;
2829 else
2830 LookForIvars = (Lookup.isSingleResult() &&
2831 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2832 ObjCInterfaceDecl *IFace = nullptr;
2833 if (LookForIvars) {
2834 IFace = CurMethod->getClassInterface();
2835 ObjCInterfaceDecl *ClassDeclared;
2836 ObjCIvarDecl *IV = nullptr;
2837 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2838 // Diagnose using an ivar in a class method.
2839 if (IsClassMethod) {
2840 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2841 return DeclResult(true);
2842 }
2843
2844 // Diagnose the use of an ivar outside of the declaring class.
2845 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2846 !declaresSameEntity(ClassDeclared, IFace) &&
2847 !getLangOpts().DebuggerSupport)
2848 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2849
2850 // Success.
2851 return IV;
2852 }
2853 } else if (CurMethod->isInstanceMethod()) {
2854 // We should warn if a local variable hides an ivar.
2855 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2856 ObjCInterfaceDecl *ClassDeclared;
2857 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2858 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2859 declaresSameEntity(IFace, ClassDeclared))
2860 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2861 }
2862 }
2863 } else if (Lookup.isSingleResult() &&
2864 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2865 // If accessing a stand-alone ivar in a class method, this is an error.
2866 if (const ObjCIvarDecl *IV =
2867 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2868 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2869 return DeclResult(true);
2870 }
2871 }
2872
2873 // Didn't encounter an error, didn't find an ivar.
2874 return DeclResult(false);
2875}
2876
2877ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2878 ObjCIvarDecl *IV) {
2879 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2880 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", 2881, __extension__ __PRETTY_FUNCTION__
))
2881 "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", 2881, __extension__ __PRETTY_FUNCTION__
))
;
2882
2883 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2884 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", 2884, __extension__ __PRETTY_FUNCTION__
))
;
2885
2886 // If we're referencing an invalid decl, just return this as a silent
2887 // error node. The error diagnostic was already emitted on the decl.
2888 if (IV->isInvalidDecl())
2889 return ExprError();
2890
2891 // Check if referencing a field with __attribute__((deprecated)).
2892 if (DiagnoseUseOfDecl(IV, Loc))
2893 return ExprError();
2894
2895 // FIXME: This should use a new expr for a direct reference, don't
2896 // turn this into Self->ivar, just return a BareIVarExpr or something.
2897 IdentifierInfo &II = Context.Idents.get("self");
2898 UnqualifiedId SelfName;
2899 SelfName.setImplicitSelfParam(&II);
2900 CXXScopeSpec SelfScopeSpec;
2901 SourceLocation TemplateKWLoc;
2902 ExprResult SelfExpr =
2903 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2904 /*HasTrailingLParen=*/false,
2905 /*IsAddressOfOperand=*/false);
2906 if (SelfExpr.isInvalid())
2907 return ExprError();
2908
2909 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2910 if (SelfExpr.isInvalid())
2911 return ExprError();
2912
2913 MarkAnyDeclReferenced(Loc, IV, true);
2914
2915 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2916 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2917 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2918 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2919
2920 ObjCIvarRefExpr *Result = new (Context)
2921 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2922 IV->getLocation(), SelfExpr.get(), true, true);
2923
2924 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2925 if (!isUnevaluatedContext() &&
2926 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2927 getCurFunction()->recordUseOfWeak(Result);
2928 }
2929 if (getLangOpts().ObjCAutoRefCount)
2930 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2931 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2932
2933 return Result;
2934}
2935
2936/// The parser has read a name in, and Sema has detected that we're currently
2937/// inside an ObjC method. Perform some additional checks and determine if we
2938/// should form a reference to an ivar. If so, build an expression referencing
2939/// that ivar.
2940ExprResult
2941Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2942 IdentifierInfo *II, bool AllowBuiltinCreation) {
2943 // FIXME: Integrate this lookup step into LookupParsedName.
2944 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2945 if (Ivar.isInvalid())
2946 return ExprError();
2947 if (Ivar.isUsable())
2948 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2949 cast<ObjCIvarDecl>(Ivar.get()));
2950
2951 if (Lookup.empty() && II && AllowBuiltinCreation)
2952 LookupBuiltin(Lookup);
2953
2954 // Sentinel value saying that we didn't do anything special.
2955 return ExprResult(false);
2956}
2957
2958/// Cast a base object to a member's actual type.
2959///
2960/// There are two relevant checks:
2961///
2962/// C++ [class.access.base]p7:
2963///
2964/// If a class member access operator [...] is used to access a non-static
2965/// data member or non-static member function, the reference is ill-formed if
2966/// the left operand [...] cannot be implicitly converted to a pointer to the
2967/// naming class of the right operand.
2968///
2969/// C++ [expr.ref]p7:
2970///
2971/// If E2 is a non-static data member or a non-static member function, the
2972/// program is ill-formed if the class of which E2 is directly a member is an
2973/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
2974///
2975/// Note that the latter check does not consider access; the access of the
2976/// "real" base class is checked as appropriate when checking the access of the
2977/// member name.
2978ExprResult
2979Sema::PerformObjectMemberConversion(Expr *From,
2980 NestedNameSpecifier *Qualifier,
2981 NamedDecl *FoundDecl,
2982 NamedDecl *Member) {
2983 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2984 if (!RD)
2985 return From;
2986
2987 QualType DestRecordType;
2988 QualType DestType;
2989 QualType FromRecordType;
2990 QualType FromType = From->getType();
2991 bool PointerConversions = false;
2992 if (isa<FieldDecl>(Member)) {
2993 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2994 auto FromPtrType = FromType->getAs<PointerType>();
2995 DestRecordType = Context.getAddrSpaceQualType(
2996 DestRecordType, FromPtrType
2997 ? FromType->getPointeeType().getAddressSpace()
2998 : FromType.getAddressSpace());
2999
3000 if (FromPtrType) {
3001 DestType = Context.getPointerType(DestRecordType);
3002 FromRecordType = FromPtrType->getPointeeType();
3003 PointerConversions = true;
3004 } else {
3005 DestType = DestRecordType;
3006 FromRecordType = FromType;
3007 }
3008 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
3009 if (Method->isStatic())
3010 return From;
3011
3012 DestType = Method->getThisType();
3013 DestRecordType = DestType->getPointeeType();
3014
3015 if (FromType->getAs<PointerType>()) {
3016 FromRecordType = FromType->getPointeeType();
3017 PointerConversions = true;
3018 } else {
3019 FromRecordType = FromType;
3020 DestType = DestRecordType;
3021 }
3022
3023 LangAS FromAS = FromRecordType.getAddressSpace();
3024 LangAS DestAS = DestRecordType.getAddressSpace();
3025 if (FromAS != DestAS) {
3026 QualType FromRecordTypeWithoutAS =
3027 Context.removeAddrSpaceQualType(FromRecordType);
3028 QualType FromTypeWithDestAS =
3029 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3030 if (PointerConversions)
3031 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3032 From = ImpCastExprToType(From, FromTypeWithDestAS,
3033 CK_AddressSpaceConversion, From->getValueKind())
3034 .get();
3035 }
3036 } else {
3037 // No conversion necessary.
3038 return From;
3039 }
3040
3041 if (DestType->isDependentType() || FromType->isDependentType())
3042 return From;
3043
3044 // If the unqualified types are the same, no conversion is necessary.
3045 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3046 return From;
3047
3048 SourceRange FromRange = From->getSourceRange();
3049 SourceLocation FromLoc = FromRange.getBegin();
3050
3051 ExprValueKind VK = From->getValueKind();
3052
3053 // C++ [class.member.lookup]p8:
3054 // [...] Ambiguities can often be resolved by qualifying a name with its
3055 // class name.
3056 //
3057 // If the member was a qualified name and the qualified referred to a
3058 // specific base subobject type, we'll cast to that intermediate type
3059 // first and then to the object in which the member is declared. That allows
3060 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3061 //
3062 // class Base { public: int x; };
3063 // class Derived1 : public Base { };
3064 // class Derived2 : public Base { };
3065 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3066 //
3067 // void VeryDerived::f() {
3068 // x = 17; // error: ambiguous base subobjects
3069 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3070 // }
3071 if (Qualifier && Qualifier->getAsType()) {
3072 QualType QType = QualType(Qualifier->getAsType(), 0);
3073 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", 3073, __extension__ __PRETTY_FUNCTION__
))
;
3074
3075 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3076
3077 // In C++98, the qualifier type doesn't actually have to be a base
3078 // type of the object type, in which case we just ignore it.
3079 // Otherwise build the appropriate casts.
3080 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3081 CXXCastPath BasePath;
3082 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3083 FromLoc, FromRange, &BasePath))
3084 return ExprError();
3085
3086 if (PointerConversions)
3087 QType = Context.getPointerType(QType);
3088 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3089 VK, &BasePath).get();
3090
3091 FromType = QType;
3092 FromRecordType = QRecordType;
3093
3094 // If the qualifier type was the same as the destination type,
3095 // we're done.
3096 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3097 return From;
3098 }
3099 }
3100
3101 CXXCastPath BasePath;
3102 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3103 FromLoc, FromRange, &BasePath,
3104 /*IgnoreAccess=*/true))
3105 return ExprError();
3106
3107 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3108 VK, &BasePath);
3109}
3110
3111bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3112 const LookupResult &R,
3113 bool HasTrailingLParen) {
3114 // Only when used directly as the postfix-expression of a call.
3115 if (!HasTrailingLParen)
3116 return false;
3117
3118 // Never if a scope specifier was provided.
3119 if (SS.isSet())
3120 return false;
3121
3122 // Only in C++ or ObjC++.
3123 if (!getLangOpts().CPlusPlus)
3124 return false;
3125
3126 // Turn off ADL when we find certain kinds of declarations during
3127 // normal lookup:
3128 for (NamedDecl *D : R) {
3129 // C++0x [basic.lookup.argdep]p3:
3130 // -- a declaration of a class member
3131 // Since using decls preserve this property, we check this on the
3132 // original decl.
3133 if (D->isCXXClassMember())
3134 return false;
3135
3136 // C++0x [basic.lookup.argdep]p3:
3137 // -- a block-scope function declaration that is not a
3138 // using-declaration
3139 // NOTE: we also trigger this for function templates (in fact, we
3140 // don't check the decl type at all, since all other decl types
3141 // turn off ADL anyway).
3142 if (isa<UsingShadowDecl>(D))
3143 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3144 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3145 return false;
3146
3147 // C++0x [basic.lookup.argdep]p3:
3148 // -- a declaration that is neither a function or a function
3149 // template
3150 // And also for builtin functions.
3151 if (isa<FunctionDecl>(D)) {
3152 FunctionDecl *FDecl = cast<FunctionDecl>(D);
3153
3154 // But also builtin functions.
3155 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3156 return false;
3157 } else if (!isa<FunctionTemplateDecl>(D))
3158 return false;
3159 }
3160
3161 return true;
3162}
3163
3164
3165/// Diagnoses obvious problems with the use of the given declaration
3166/// as an expression. This is only actually called for lookups that
3167/// were not overloaded, and it doesn't promise that the declaration
3168/// will in fact be used.
3169static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3170 if (D->isInvalidDecl())
3171 return true;
3172
3173 if (isa<TypedefNameDecl>(D)) {
3174 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3175 return true;
3176 }
3177
3178 if (isa<ObjCInterfaceDecl>(D)) {
3179 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3180 return true;
3181 }
3182
3183 if (isa<NamespaceDecl>(D)) {
3184 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3185 return true;
3186 }
3187
3188 return false;
3189}
3190
3191// Certain multiversion types should be treated as overloaded even when there is
3192// only one result.
3193static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3194 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", 3194, __extension__ __PRETTY_FUNCTION__
))
;
3195 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3196 return FD &&
3197 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3198}
3199
3200ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3201 LookupResult &R, bool NeedsADL,
3202 bool AcceptInvalidDecl) {
3203 // If this is a single, fully-resolved result and we don't need ADL,
3204 // just build an ordinary singleton decl ref.
3205 if (!NeedsADL && R.isSingleResult() &&
3206 !R.getAsSingle<FunctionTemplateDecl>() &&
3207 !ShouldLookupResultBeMultiVersionOverload(R))
3208 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3209 R.getRepresentativeDecl(), nullptr,
3210 AcceptInvalidDecl);
3211
3212 // We only need to check the declaration if there's exactly one
3213 // result, because in the overloaded case the results can only be
3214 // functions and function templates.
3215 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3216 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3217 return ExprError();
3218
3219 // Otherwise, just build an unresolved lookup expression. Suppress
3220 // any lookup-related diagnostics; we'll hash these out later, when
3221 // we've picked a target.
3222 R.suppressDiagnostics();
3223
3224 UnresolvedLookupExpr *ULE
3225 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3226 SS.getWithLocInContext(Context),
3227 R.getLookupNameInfo(),
3228 NeedsADL, R.isOverloadedResult(),
3229 R.begin(), R.end());
3230
3231 return ULE;
3232}
3233
3234static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3235 ValueDecl *var);
3236
3237/// Complete semantic analysis for a reference to the given declaration.
3238ExprResult Sema::BuildDeclarationNameExpr(
3239 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3240 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3241 bool AcceptInvalidDecl) {
3242 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", 3242, __extension__ __PRETTY_FUNCTION__
))
;
3243 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", 3244, __extension__ __PRETTY_FUNCTION__
))
3244 "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", 3244, __extension__ __PRETTY_FUNCTION__
))
;
3245
3246 SourceLocation Loc = NameInfo.getLoc();
3247 if (CheckDeclInExpr(*this, Loc, D)) {
3248 // Recovery from invalid cases (e.g. D is an invalid Decl).
3249 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3250 // diagnostics, as invalid decls use int as a fallback type.
3251 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3252 }
3253
3254 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3255 // Specifically diagnose references to class templates that are missing
3256 // a template argument list.
3257 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3258 return ExprError();
3259 }
3260
3261 // Make sure that we're referring to a value.
3262 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3263 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3264 Diag(D->getLocation(), diag::note_declared_at);
3265 return ExprError();
3266 }
3267
3268 // Check whether this declaration can be used. Note that we suppress
3269 // this check when we're going to perform argument-dependent lookup
3270 // on this function name, because this might not be the function
3271 // that overload resolution actually selects.
3272 if (DiagnoseUseOfDecl(D, Loc))
3273 return ExprError();
3274
3275 auto *VD = cast<ValueDecl>(D);
3276
3277 // Only create DeclRefExpr's for valid Decl's.
3278 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3279 return ExprError();
3280
3281 // Handle members of anonymous structs and unions. If we got here,
3282 // and the reference is to a class member indirect field, then this
3283 // must be the subject of a pointer-to-member expression.
3284 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3285 if (!indirectField->isCXXClassMember())
3286 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3287 indirectField);
3288
3289 QualType type = VD->getType();
3290 if (type.isNull())
3291 return ExprError();
3292 ExprValueKind valueKind = VK_PRValue;
3293
3294 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3295 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3296 // is expanded by some outer '...' in the context of the use.
3297 type = type.getNonPackExpansionType();
3298
3299 switch (D->getKind()) {
3300 // Ignore all the non-ValueDecl kinds.
3301#define ABSTRACT_DECL(kind)
3302#define VALUE(type, base)
3303#define DECL(type, base) case Decl::type:
3304#include "clang/AST/DeclNodes.inc"
3305 llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "clang/lib/Sema/SemaExpr.cpp"
, 3305)
;
3306
3307 // These shouldn't make it here.
3308 case Decl::ObjCAtDefsField:
3309 llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?"
, "clang/lib/Sema/SemaExpr.cpp", 3309)
;
3310
3311 // Enum constants are always r-values and never references.
3312 // Unresolved using declarations are dependent.
3313 case Decl::EnumConstant:
3314 case Decl::UnresolvedUsingValue:
3315 case Decl::OMPDeclareReduction:
3316 case Decl::OMPDeclareMapper:
3317 valueKind = VK_PRValue;
3318 break;
3319
3320 // Fields and indirect fields that got here must be for
3321 // pointer-to-member expressions; we just call them l-values for
3322 // internal consistency, because this subexpression doesn't really
3323 // exist in the high-level semantics.
3324 case Decl::Field:
3325 case Decl::IndirectField:
3326 case Decl::ObjCIvar:
3327 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", 3327, __extension__ __PRETTY_FUNCTION__
))
;
3328
3329 // These can't have reference type in well-formed programs, but
3330 // for internal consistency we do this anyway.
3331 type = type.getNonReferenceType();
3332 valueKind = VK_LValue;
3333 break;
3334
3335 // Non-type template parameters are either l-values or r-values
3336 // depending on the type.
3337 case Decl::NonTypeTemplateParm: {
3338 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3339 type = reftype->getPointeeType();
3340 valueKind = VK_LValue; // even if the parameter is an r-value reference
3341 break;
3342 }
3343
3344 // [expr.prim.id.unqual]p2:
3345 // If the entity is a template parameter object for a template
3346 // parameter of type T, the type of the expression is const T.
3347 // [...] The expression is an lvalue if the entity is a [...] template
3348 // parameter object.
3349 if (type->isRecordType()) {
3350 type = type.getUnqualifiedType().withConst();
3351 valueKind = VK_LValue;
3352 break;
3353 }
3354
3355 // For non-references, we need to strip qualifiers just in case
3356 // the template parameter was declared as 'const int' or whatever.
3357 valueKind = VK_PRValue;
3358 type = type.getUnqualifiedType();
3359 break;
3360 }
3361
3362 case Decl::Var:
3363 case Decl::VarTemplateSpecialization:
3364 case Decl::VarTemplatePartialSpecialization:
3365 case Decl::Decomposition:
3366 case Decl::OMPCapturedExpr:
3367 // In C, "extern void blah;" is valid and is an r-value.
3368 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3369 type->isVoidType()) {
3370 valueKind = VK_PRValue;
3371 break;
3372 }
3373 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3374
3375 case Decl::ImplicitParam:
3376 case Decl::ParmVar: {
3377 // These are always l-values.
3378 valueKind = VK_LValue;
3379 type = type.getNonReferenceType();
3380
3381 // FIXME: Does the addition of const really only apply in
3382 // potentially-evaluated contexts? Since the variable isn't actually
3383 // captured in an unevaluated context, it seems that the answer is no.
3384 if (!isUnevaluatedContext()) {
3385 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3386 if (!CapturedType.isNull())
3387 type = CapturedType;
3388 }
3389
3390 break;
3391 }
3392
3393 case Decl::Binding: {
3394 // These are always lvalues.
3395 valueKind = VK_LValue;
3396 type = type.getNonReferenceType();
3397 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3398 // decides how that's supposed to work.
3399 auto *BD = cast<BindingDecl>(VD);
3400 if (BD->getDeclContext() != CurContext && !isUnevaluatedContext()) {
3401 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3402 if (DD && DD->hasLocalStorage())
3403 diagnoseUncapturableValueReference(*this, Loc, BD);
3404 }
3405 break;
3406 }
3407
3408 case Decl::Function: {
3409 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3410 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3411 type = Context.BuiltinFnTy;
3412 valueKind = VK_PRValue;
3413 break;
3414 }
3415 }
3416
3417 const FunctionType *fty = type->castAs<FunctionType>();
3418
3419 // If we're referring to a function with an __unknown_anytype
3420 // result type, make the entire expression __unknown_anytype.
3421 if (fty->getReturnType() == Context.UnknownAnyTy) {
3422 type = Context.UnknownAnyTy;
3423 valueKind = VK_PRValue;
3424 break;
3425 }
3426
3427 // Functions are l-values in C++.
3428 if (getLangOpts().CPlusPlus) {
3429 valueKind = VK_LValue;
3430 break;
3431 }
3432
3433 // C99 DR 316 says that, if a function type comes from a
3434 // function definition (without a prototype), that type is only
3435 // used for checking compatibility. Therefore, when referencing
3436 // the function, we pretend that we don't have the full function
3437 // type.
3438 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3439 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3440 fty->getExtInfo());
3441
3442 // Functions are r-values in C.
3443 valueKind = VK_PRValue;
3444 break;
3445 }
3446
3447 case Decl::CXXDeductionGuide:
3448 llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide"
, "clang/lib/Sema/SemaExpr.cpp", 3448)
;
3449
3450 case Decl::MSProperty:
3451 case Decl::MSGuid:
3452 case Decl::TemplateParamObject:
3453 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3454 // capture in OpenMP, or duplicated between host and device?
3455 valueKind = VK_LValue;
3456 break;
3457
3458 case Decl::UnnamedGlobalConstant:
3459 valueKind = VK_LValue;
3460 break;
3461
3462 case Decl::CXXMethod:
3463 // If we're referring to a method with an __unknown_anytype
3464 // result type, make the entire expression __unknown_anytype.
3465 // This should only be possible with a type written directly.
3466 if (const FunctionProtoType *proto =
3467 dyn_cast<FunctionProtoType>(VD->getType()))
3468 if (proto->getReturnType() == Context.UnknownAnyTy) {
3469 type = Context.UnknownAnyTy;
3470 valueKind = VK_PRValue;
3471 break;
3472 }
3473
3474 // C++ methods are l-values if static, r-values if non-static.
3475 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3476 valueKind = VK_LValue;
3477 break;
3478 }
3479 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3480
3481 case Decl::CXXConversion:
3482 case Decl::CXXDestructor:
3483 case Decl::CXXConstructor:
3484 valueKind = VK_PRValue;
3485 break;
3486 }
3487
3488 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3489 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3490 TemplateArgs);
3491}
3492
3493static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3494 SmallString<32> &Target) {
3495 Target.resize(CharByteWidth * (Source.size() + 1));
3496 char *ResultPtr = &Target[0];
3497 const llvm::UTF8 *ErrorPtr;
3498 bool success =
3499 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3500 (void)success;
3501 assert(success)(static_cast <bool> (success) ? void (0) : __assert_fail
("success", "clang/lib/Sema/SemaExpr.cpp", 3501, __extension__
__PRETTY_FUNCTION__))
;
3502 Target.resize(ResultPtr - &Target[0]);
3503}
3504
3505ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3506 PredefinedExpr::IdentKind IK) {
3507 // Pick the current block, lambda, captured statement or function.
3508 Decl *currentDecl = nullptr;
3509 if (const BlockScopeInfo *BSI = getCurBlock())
3510 currentDecl = BSI->TheDecl;
3511 else if (const LambdaScopeInfo *LSI = getCurLambda())
3512 currentDecl = LSI->CallOperator;
3513 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3514 currentDecl = CSI->TheCapturedDecl;
3515 else
3516 currentDecl = getCurFunctionOrMethodDecl();
3517
3518 if (!currentDecl) {
3519 Diag(Loc, diag::ext_predef_outside_function);
3520 currentDecl = Context.getTranslationUnitDecl();
3521 }
3522
3523 QualType ResTy;
3524 StringLiteral *SL = nullptr;
3525 if (cast<DeclContext>(currentDecl)->isDependentContext())
3526 ResTy = Context.DependentTy;
3527 else {
3528 // Pre-defined identifiers are of type char[x], where x is the length of
3529 // the string.
3530 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3531 unsigned Length = Str.length();
3532
3533 llvm::APInt LengthI(32, Length + 1);
3534 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3535 ResTy =
3536 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3537 SmallString<32> RawChars;
3538 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3539 Str, RawChars);
3540 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3541 ArrayType::Normal,
3542 /*IndexTypeQuals*/ 0);
3543 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3544 /*Pascal*/ false, ResTy, Loc);
3545 } else {
3546 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3547 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3548 ArrayType::Normal,
3549 /*IndexTypeQuals*/ 0);
3550 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3551 /*Pascal*/ false, ResTy, Loc);
3552 }
3553 }
3554
3555 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3556}
3557
3558ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3559 SourceLocation LParen,
3560 SourceLocation RParen,
3561 TypeSourceInfo *TSI) {
3562 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3563}
3564
3565ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3566 SourceLocation LParen,
3567 SourceLocation RParen,
3568 ParsedType ParsedTy) {
3569 TypeSourceInfo *TSI = nullptr;
3570 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3571
3572 if (Ty.isNull())
3573 return ExprError();
3574 if (!TSI)
3575 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3576
3577 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3578}
3579
3580ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3581 PredefinedExpr::IdentKind IK;
3582
3583 switch (Kind) {
3584 default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!"
, "clang/lib/Sema/SemaExpr.cpp", 3584)
;
3585 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3586 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3587 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3588 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3589 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3590 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3591 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3592 }
3593
3594 return BuildPredefinedExpr(Loc, IK);
3595}
3596
3597ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3598 SmallString<16> CharBuffer;
3599 bool Invalid = false;
3600 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3601 if (Invalid)
3602 return ExprError();
3603
3604 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3605 PP, Tok.getKind());
3606 if (Literal.hadError())
3607 return ExprError();
3608
3609 QualType Ty;
3610 if (Literal.isWide())
3611 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3612 else if (Literal.isUTF8() && getLangOpts().C2x)
3613 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3614 else if (Literal.isUTF8() && getLangOpts().Char8)
3615 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3616 else if (Literal.isUTF16())
3617 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3618 else if (Literal.isUTF32())
3619 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3620 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3621 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3622 else
3623 Ty = Context.CharTy; // 'x' -> char in C++;
3624 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3625
3626 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3627 if (Literal.isWide())
3628 Kind = CharacterLiteral::Wide;
3629 else if (Literal.isUTF16())
3630 Kind = CharacterLiteral::UTF16;
3631 else if (Literal.isUTF32())
3632 Kind = CharacterLiteral::UTF32;
3633 else if (Literal.isUTF8())
3634 Kind = CharacterLiteral::UTF8;
3635
3636 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3637 Tok.getLocation());
3638
3639 if (Literal.getUDSuffix().empty())
3640 return Lit;
3641
3642 // We're building a user-defined literal.
3643 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3644 SourceLocation UDSuffixLoc =
3645 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3646
3647 // Make sure we're allowed user-defined literals here.
3648 if (!UDLScope)
3649 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3650
3651 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3652 // operator "" X (ch)
3653 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3654 Lit, Tok.getLocation());
3655}
3656
3657ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3658 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3659 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3660 Context.IntTy, Loc);
3661}
3662
3663static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3664 QualType Ty, SourceLocation Loc) {
3665 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3666
3667 using llvm::APFloat;
3668 APFloat Val(Format);
3669
3670 APFloat::opStatus result = Literal.GetFloatValue(Val);
3671
3672 // Overflow is always an error, but underflow is only an error if
3673 // we underflowed to zero (APFloat reports denormals as underflow).
3674 if ((result & APFloat::opOverflow) ||
3675 ((result & APFloat::opUnderflow) && Val.isZero())) {
3676 unsigned diagnostic;
3677 SmallString<20> buffer;
3678 if (result & APFloat::opOverflow) {
3679 diagnostic = diag::warn_float_overflow;
3680 APFloat::getLargest(Format).toString(buffer);
3681 } else {
3682 diagnostic = diag::warn_float_underflow;
3683 APFloat::getSmallest(Format).toString(buffer);
3684 }
3685
3686 S.Diag(Loc, diagnostic)
3687 << Ty
3688 << StringRef(buffer.data(), buffer.size());
3689 }
3690
3691 bool isExact = (result == APFloat::opOK);
3692 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3693}
3694
3695bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3696 assert(E && "Invalid expression")(static_cast <bool> (E && "Invalid expression")
? void (0) : __assert_fail ("E && \"Invalid expression\""
, "clang/lib/Sema/SemaExpr.cpp", 3696, __extension__ __PRETTY_FUNCTION__
))
;
3697
3698 if (E->isValueDependent())
3699 return false;
3700
3701 QualType QT = E->getType();
3702 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3703 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3704 return true;
3705 }
3706
3707 llvm::APSInt ValueAPS;
3708 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3709
3710 if (R.isInvalid())
3711 return true;
3712
3713 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3714 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3715 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3716 << toString(ValueAPS, 10) << ValueIsPositive;
3717 return true;
3718 }
3719
3720 return false;
3721}
3722
3723ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3724 // Fast path for a single digit (which is quite common). A single digit
3725 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3726 if (Tok.getLength() == 1) {
3727 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3728 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3729 }
3730
3731 SmallString<128> SpellingBuffer;
3732 // NumericLiteralParser wants to overread by one character. Add padding to
3733 // the buffer in case the token is copied to the buffer. If getSpelling()
3734 // returns a StringRef to the memory buffer, it should have a null char at
3735 // the EOF, so it is also safe.
3736 SpellingBuffer.resize(Tok.getLength() + 1);
3737
3738 // Get the spelling of the token, which eliminates trigraphs, etc.
3739 bool Invalid = false;
3740 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3741 if (Invalid)
3742 return ExprError();
3743
3744 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3745 PP.getSourceManager(), PP.getLangOpts(),
3746 PP.getTargetInfo(), PP.getDiagnostics());
3747 if (Literal.hadError)
3748 return ExprError();
3749
3750 if (Literal.hasUDSuffix()) {
3751 // We're building a user-defined literal.
3752 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3753 SourceLocation UDSuffixLoc =
3754 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3755
3756 // Make sure we're allowed user-defined literals here.
3757 if (!UDLScope)
3758 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3759
3760 QualType CookedTy;
3761 if (Literal.isFloatingLiteral()) {
3762 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3763 // long double, the literal is treated as a call of the form
3764 // operator "" X (f L)
3765 CookedTy = Context.LongDoubleTy;
3766 } else {
3767 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3768 // unsigned long long, the literal is treated as a call of the form
3769 // operator "" X (n ULL)
3770 CookedTy = Context.UnsignedLongLongTy;
3771 }
3772
3773 DeclarationName OpName =
3774 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3775 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3776 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3777
3778 SourceLocation TokLoc = Tok.getLocation();
3779
3780 // Perform literal operator lookup to determine if we're building a raw
3781 // literal or a cooked one.
3782 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3783 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3784 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3785 /*AllowStringTemplatePack*/ false,
3786 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3787 case LOLR_ErrorNoDiagnostic:
3788 // Lookup failure for imaginary constants isn't fatal, there's still the
3789 // GNU extension producing _Complex types.
3790 break;
3791 case LOLR_Error:
3792 return ExprError();
3793 case LOLR_Cooked: {
3794 Expr *Lit;
3795 if (Literal.isFloatingLiteral()) {
3796 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3797 } else {
3798 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3799 if (Literal.GetIntegerValue(ResultVal))
3800 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3801 << /* Unsigned */ 1;
3802 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3803 Tok.getLocation());
3804 }
3805 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3806 }
3807
3808 case LOLR_Raw: {
3809 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3810 // literal is treated as a call of the form
3811 // operator "" X ("n")
3812 unsigned Length = Literal.getUDSuffixOffset();
3813 QualType StrTy = Context.getConstantArrayType(
3814 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3815 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3816 Expr *Lit = StringLiteral::Create(
3817 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3818 /*Pascal*/false, StrTy, &TokLoc, 1);
3819 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3820 }
3821
3822 case LOLR_Template: {
3823 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3824 // template), L is treated as a call fo the form
3825 // operator "" X <'c1', 'c2', ... 'ck'>()
3826 // where n is the source character sequence c1 c2 ... ck.
3827 TemplateArgumentListInfo ExplicitArgs;
3828 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3829 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3830 llvm::APSInt Value(CharBits, CharIsUnsigned);
3831 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3832 Value = TokSpelling[I];
3833 TemplateArgument Arg(Context, Value, Context.CharTy);
3834 TemplateArgumentLocInfo ArgInfo;
3835 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3836 }
3837 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3838 &ExplicitArgs);
3839 }
3840 case LOLR_StringTemplatePack:
3841 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 3841)
;
3842 }
3843 }
3844
3845 Expr *Res;
3846
3847 if (Literal.isFixedPointLiteral()) {
3848 QualType Ty;
3849
3850 if (Literal.isAccum) {
3851 if (Literal.isHalf) {
3852 Ty = Context.ShortAccumTy;
3853 } else if (Literal.isLong) {
3854 Ty = Context.LongAccumTy;
3855 } else {
3856 Ty = Context.AccumTy;
3857 }
3858 } else if (Literal.isFract) {
3859 if (Literal.isHalf) {
3860 Ty = Context.ShortFractTy;
3861 } else if (Literal.isLong) {
3862 Ty = Context.LongFractTy;
3863 } else {
3864 Ty = Context.FractTy;
3865 }
3866 }
3867
3868 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3869
3870 bool isSigned = !Literal.isUnsigned;
3871 unsigned scale = Context.getFixedPointScale(Ty);
3872 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3873
3874 llvm::APInt Val(bit_width, 0, isSigned);
3875 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3876 bool ValIsZero = Val.isZero() && !Overflowed;
3877
3878 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3879 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3880 // Clause 6.4.4 - The value of a constant shall be in the range of
3881 // representable values for its type, with exception for constants of a
3882 // fract type with a value of exactly 1; such a constant shall denote
3883 // the maximal value for the type.
3884 --Val;
3885 else if (Val.ugt(MaxVal) || Overflowed)
3886 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3887
3888 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3889 Tok.getLocation(), scale);
3890 } else if (Literal.isFloatingLiteral()) {
3891 QualType Ty;
3892 if (Literal.isHalf){
3893 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3894 Ty = Context.HalfTy;
3895 else {
3896 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3897 return ExprError();
3898 }
3899 } else if (Literal.isFloat)
3900 Ty = Context.FloatTy;
3901 else if (Literal.isLong)
3902 Ty = Context.LongDoubleTy;
3903 else if (Literal.isFloat16)
3904 Ty = Context.Float16Ty;
3905 else if (Literal.isFloat128)
3906 Ty = Context.Float128Ty;
3907 else
3908 Ty = Context.DoubleTy;
3909
3910 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3911
3912 if (Ty == Context.DoubleTy) {
3913 if (getLangOpts().SinglePrecisionConstants) {
3914 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3915 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3916 }
3917 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3918 "cl_khr_fp64", getLangOpts())) {
3919 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3920 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3921 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3922 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3923 }
3924 }
3925 } else if (!Literal.isIntegerLiteral()) {
3926 return ExprError();
3927 } else {
3928 QualType Ty;
3929
3930 // 'long long' is a C99 or C++11 feature.
3931 if (!getLangOpts().C99 && Literal.isLongLong) {
3932 if (getLangOpts().CPlusPlus)
3933 Diag(Tok.getLocation(),
3934 getLangOpts().CPlusPlus11 ?
3935 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3936 else
3937 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3938 }
3939
3940 // 'z/uz' literals are a C++2b feature.
3941 if (Literal.isSizeT)
3942 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3943 ? getLangOpts().CPlusPlus2b
3944 ? diag::warn_cxx20_compat_size_t_suffix
3945 : diag::ext_cxx2b_size_t_suffix
3946 : diag::err_cxx2b_size_t_suffix);
3947
3948 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3949 // but we do not currently support the suffix in C++ mode because it's not
3950 // entirely clear whether WG21 will prefer this suffix to return a library
3951 // type such as std::bit_int instead of returning a _BitInt.
3952 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3953 PP.Diag(Tok.getLocation(), getLangOpts().C2x
3954 ? diag::warn_c2x_compat_bitint_suffix
3955 : diag::ext_c2x_bitint_suffix);
3956
3957 // Get the value in the widest-possible width. What is "widest" depends on
3958 // whether the literal is a bit-precise integer or not. For a bit-precise
3959 // integer type, try to scan the source to determine how many bits are
3960 // needed to represent the value. This may seem a bit expensive, but trying
3961 // to get the integer value from an overly-wide APInt is *extremely*
3962 // expensive, so the naive approach of assuming
3963 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3964 unsigned BitsNeeded =
3965 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3966 Literal.getLiteralDigits(), Literal.getRadix())
3967 : Context.getTargetInfo().getIntMaxTWidth();
3968 llvm::APInt ResultVal(BitsNeeded, 0);
3969
3970 if (Literal.GetIntegerValue(ResultVal)) {
3971 // If this value didn't fit into uintmax_t, error and force to ull.
3972 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3973 << /* Unsigned */ 1;
3974 Ty = Context.UnsignedLongLongTy;
3975 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", 3976, __extension__ __PRETTY_FUNCTION__
))
3976 "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", 3976, __extension__ __PRETTY_FUNCTION__
))
;
3977 } else {
3978 // If this value fits into a ULL, try to figure out what else it fits into
3979 // according to the rules of C99 6.4.4.1p5.
3980
3981 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3982 // be an unsigned int.
3983 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3984
3985 // Check from smallest to largest, picking the smallest type we can.
3986 unsigned Width = 0;
3987
3988 // Microsoft specific integer suffixes are explicitly sized.
3989 if (Literal.MicrosoftInteger) {
3990 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3991 Width = 8;
3992 Ty = Context.CharTy;
3993 } else {
3994 Width = Literal.MicrosoftInteger;
3995 Ty = Context.getIntTypeForBitwidth(Width,
3996 /*Signed=*/!Literal.isUnsigned);
3997 }
3998 }
3999
4000 // Bit-precise integer literals are automagically-sized based on the
4001 // width required by the literal.
4002 if (Literal.isBitInt) {
4003 // The signed version has one more bit for the sign value. There are no
4004 // zero-width bit-precise integers, even if the literal value is 0.
4005 Width = std::max(ResultVal.getActiveBits(), 1u) +
4006 (Literal.isUnsigned ? 0u : 1u);
4007
4008 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4009 // and reset the type to the largest supported width.
4010 unsigned int MaxBitIntWidth =
4011 Context.getTargetInfo().getMaxBitIntWidth();
4012 if (Width > MaxBitIntWidth) {
4013 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4014 << Literal.isUnsigned;
4015 Width = MaxBitIntWidth;
4016 }
4017
4018 // Reset the result value to the smaller APInt and select the correct
4019 // type to be used. Note, we zext even for signed values because the
4020 // literal itself is always an unsigned value (a preceeding - is a
4021 // unary operator, not part of the literal).
4022 ResultVal = ResultVal.zextOrTrunc(Width);
4023 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4024 }
4025
4026 // Check C++2b size_t literals.
4027 if (Literal.isSizeT) {
4028 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", 4029, __extension__ __PRETTY_FUNCTION__
))
4029 "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", 4029, __extension__ __PRETTY_FUNCTION__
))
;
4030 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4031 Context.getTargetInfo().getSizeType());
4032
4033 // Does it fit in size_t?
4034 if (ResultVal.isIntN(SizeTSize)) {
4035 // Does it fit in ssize_t?
4036 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4037 Ty = Context.getSignedSizeType();
4038 else if (AllowUnsigned)
4039 Ty = Context.getSizeType();
4040 Width = SizeTSize;
4041 }
4042 }
4043
4044 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4045 !Literal.isSizeT) {
4046 // Are int/unsigned possibilities?
4047 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4048
4049 // Does it fit in a unsigned int?
4050 if (ResultVal.isIntN(IntSize)) {
4051 // Does it fit in a signed int?
4052 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4053 Ty = Context.IntTy;
4054 else if (AllowUnsigned)
4055 Ty = Context.UnsignedIntTy;
4056 Width = IntSize;
4057 }
4058 }
4059
4060 // Are long/unsigned long possibilities?
4061 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4062 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4063
4064 // Does it fit in a unsigned long?
4065 if (ResultVal.isIntN(LongSize)) {
4066 // Does it fit in a signed long?
4067 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4068 Ty = Context.LongTy;
4069 else if (AllowUnsigned)
4070 Ty = Context.UnsignedLongTy;
4071 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4072 // is compatible.
4073 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4074 const unsigned LongLongSize =
4075 Context.getTargetInfo().getLongLongWidth();
4076 Diag(Tok.getLocation(),
4077 getLangOpts().CPlusPlus
4078 ? Literal.isLong
4079 ? diag::warn_old_implicitly_unsigned_long_cxx
4080 : /*C++98 UB*/ diag::
4081 ext_old_implicitly_unsigned_long_cxx
4082 : diag::warn_old_implicitly_unsigned_long)
4083 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4084 : /*will be ill-formed*/ 1);
4085 Ty = Context.UnsignedLongTy;
4086 }
4087 Width = LongSize;
4088 }
4089 }
4090
4091 // Check long long if needed.
4092 if (Ty.isNull() && !Literal.isSizeT) {
4093 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4094
4095 // Does it fit in a unsigned long long?
4096 if (ResultVal.isIntN(LongLongSize)) {
4097 // Does it fit in a signed long long?
4098 // To be compatible with MSVC, hex integer literals ending with the
4099 // LL or i64 suffix are always signed in Microsoft mode.
4100 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4101 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4102 Ty = Context.LongLongTy;
4103 else if (AllowUnsigned)
4104 Ty = Context.UnsignedLongLongTy;
4105 Width = LongLongSize;
4106 }
4107 }
4108
4109 // If we still couldn't decide a type, we either have 'size_t' literal
4110 // that is out of range, or a decimal literal that does not fit in a
4111 // signed long long and has no U suffix.
4112 if (Ty.isNull()) {
4113 if (Literal.isSizeT)
4114 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4115 << Literal.isUnsigned;
4116 else
4117 Diag(Tok.getLocation(),
4118 diag::ext_integer_literal_too_large_for_signed);
4119 Ty = Context.UnsignedLongLongTy;
4120 Width = Context.getTargetInfo().getLongLongWidth();
4121 }
4122
4123 if (ResultVal.getBitWidth() != Width)
4124 ResultVal = ResultVal.trunc(Width);
4125 }
4126 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4127 }
4128
4129 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4130 if (Literal.isImaginary) {
4131 Res = new (Context) ImaginaryLiteral(Res,
4132 Context.getComplexType(Res->getType()));
4133
4134 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4135 }
4136 return Res;
4137}
4138
4139ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4140 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", 4140, __extension__ __PRETTY_FUNCTION__
))
;
4141 QualType ExprTy = E->getType();
4142 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4143 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4144 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4145 return new (Context) ParenExpr(L, R, E);
4146}
4147
4148static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4149 SourceLocation Loc,
4150 SourceRange ArgRange) {
4151 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4152 // scalar or vector data type argument..."
4153 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4154 // type (C99 6.2.5p18) or void.
4155 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4156 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4157 << T << ArgRange;
4158 return true;
4159 }
4160
4161 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", 4162, __extension__ __PRETTY_FUNCTION__
))
4162 "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", 4162, __extension__ __PRETTY_FUNCTION__
))
;
4163 return false;
4164}
4165
4166static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4167 SourceLocation Loc,
4168 SourceRange ArgRange,
4169 UnaryExprOrTypeTrait TraitKind) {
4170 // Invalid types must be hard errors for SFINAE in C++.
4171 if (S.LangOpts.CPlusPlus)
4172 return true;
4173
4174 // C99 6.5.3.4p1:
4175 if (T->isFunctionType() &&
4176 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4177 TraitKind == UETT_PreferredAlignOf)) {
4178 // sizeof(function)/alignof(function) is allowed as an extension.
4179 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4180 << getTraitSpelling(TraitKind) << ArgRange;
4181 return false;
4182 }
4183
4184 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4185 // this is an error (OpenCL v1.1 s6.3.k)
4186 if (T->isVoidType()) {
4187 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4188 : diag::ext_sizeof_alignof_void_type;
4189 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4190 return false;
4191 }
4192
4193 return true;
4194}
4195
4196static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4197 SourceLocation Loc,
4198 SourceRange ArgRange,
4199 UnaryExprOrTypeTrait TraitKind) {
4200 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4201 // runtime doesn't allow it.
4202 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4203 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4204 << T << (TraitKind == UETT_SizeOf)
4205 << ArgRange;
4206 return true;
4207 }
4208
4209 return false;
4210}
4211
4212/// Check whether E is a pointer from a decayed array type (the decayed
4213/// pointer type is equal to T) and emit a warning if it is.
4214static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4215 Expr *E) {
4216 // Don't warn if the operation changed the type.
4217 if (T != E->getType())
4218 return;
4219
4220 // Now look for array decays.
4221 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4222 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4223 return;
4224
4225 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4226 << ICE->getType()
4227 << ICE->getSubExpr()->getType();
4228}
4229
4230/// Check the constraints on expression operands to unary type expression
4231/// and type traits.
4232///
4233/// Completes any types necessary and validates the constraints on the operand
4234/// expression. The logic mostly mirrors the type-based overload, but may modify
4235/// the expression as it completes the type for that expression through template
4236/// instantiation, etc.
4237bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4238 UnaryExprOrTypeTrait ExprKind) {
4239 QualType ExprTy = E->getType();
4240 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp"
, 4240, __extension__ __PRETTY_FUNCTION__))
;
4241
4242 bool IsUnevaluatedOperand =
4243 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4244 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4245 if (IsUnevaluatedOperand) {
4246 ExprResult Result = CheckUnevaluatedOperand(E);
4247 if (Result.isInvalid())
4248 return true;
4249 E = Result.get();
4250 }
4251
4252 // The operand for sizeof and alignof is in an unevaluated expression context,
4253 // so side effects could result in unintended consequences.
4254 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4255 // used to build SFINAE gadgets.
4256 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4257 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4258 !E->isInstantiationDependent() &&
4259 E->HasSideEffects(Context, false))
4260 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4261
4262 if (ExprKind == UETT_VecStep)
4263 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4264 E->getSourceRange());
4265
4266 // Explicitly list some types as extensions.
4267 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4268 E->getSourceRange(), ExprKind))
4269 return false;
4270
4271 // 'alignof' applied to an expression only requires the base element type of
4272 // the expression to be complete. 'sizeof' requires the expression's type to
4273 // be complete (and will attempt to complete it if it's an array of unknown
4274 // bound).
4275 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4276 if (RequireCompleteSizedType(
4277 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4278 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4279 getTraitSpelling(ExprKind), E->getSourceRange()))
4280 return true;
4281 } else {
4282 if (RequireCompleteSizedExprType(
4283 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4284 getTraitSpelling(ExprKind), E->getSourceRange()))
4285 return true;
4286 }
4287
4288 // Completing the expression's type may have changed it.
4289 ExprTy = E->getType();
4290 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp"
, 4290, __extension__ __PRETTY_FUNCTION__))
;
4291
4292 if (ExprTy->isFunctionType()) {
4293 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4294 << getTraitSpelling(ExprKind) << E->getSourceRange();
4295 return true;
4296 }
4297
4298 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4299 E->getSourceRange(), ExprKind))
4300 return true;
4301
4302 if (ExprKind == UETT_SizeOf) {
4303 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4304 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4305 QualType OType = PVD->getOriginalType();
4306 QualType Type = PVD->getType();
4307 if (Type->isPointerType() && OType->isArrayType()) {
4308 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4309 << Type << OType;
4310 Diag(PVD->getLocation(), diag::note_declared_at);
4311 }
4312 }
4313 }
4314
4315 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4316 // decays into a pointer and returns an unintended result. This is most
4317 // likely a typo for "sizeof(array) op x".
4318 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4319 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4320 BO->getLHS());
4321 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4322 BO->getRHS());
4323 }
4324 }
4325
4326 return false;
4327}
4328
4329/// Check the constraints on operands to unary expression and type
4330/// traits.
4331///
4332/// This will complete any types necessary, and validate the various constraints
4333/// on those operands.
4334///
4335/// The UsualUnaryConversions() function is *not* called by this routine.
4336/// C99 6.3.2.1p[2-4] all state:
4337/// Except when it is the operand of the sizeof operator ...
4338///
4339/// C++ [expr.sizeof]p4
4340/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4341/// standard conversions are not applied to the operand of sizeof.
4342///
4343/// This policy is followed for all of the unary trait expressions.
4344bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4345 SourceLocation OpLoc,
4346 SourceRange ExprRange,
4347 UnaryExprOrTypeTrait ExprKind) {
4348 if (ExprType->isDependentType())
4349 return false;
4350
4351 // C++ [expr.sizeof]p2:
4352 // When applied to a reference or a reference type, the result
4353 // is the size of the referenced type.
4354 // C++11 [expr.alignof]p3:
4355 // When alignof is applied to a reference type, the result
4356 // shall be the alignment of the referenced type.
4357 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4358 ExprType = Ref->getPointeeType();
4359
4360 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4361 // When alignof or _Alignof is applied to an array type, the result
4362 // is the alignment of the element type.
4363 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4364 ExprKind == UETT_OpenMPRequiredSimdAlign)
4365 ExprType = Context.getBaseElementType(ExprType);
4366
4367 if (ExprKind == UETT_VecStep)
4368 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4369
4370 // Explicitly list some types as extensions.
4371 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4372 ExprKind))
4373 return false;
4374
4375 if (RequireCompleteSizedType(
4376 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4377 getTraitSpelling(ExprKind), ExprRange))
4378 return true;
4379
4380 if (ExprType->isFunctionType()) {
4381 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4382 << getTraitSpelling(ExprKind) << ExprRange;
4383 return true;
4384 }
4385
4386 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4387 ExprKind))
4388 return true;
4389
4390 return false;
4391}
4392
4393static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4394 // Cannot know anything else if the expression is dependent.
4395 if (E->isTypeDependent())
4396 return false;
4397
4398 if (E->getObjectKind() == OK_BitField) {
4399 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4400 << 1 << E->getSourceRange();
4401 return true;
4402 }
4403
4404 ValueDecl *D = nullptr;
4405 Expr *Inner = E->IgnoreParens();
4406 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4407 D = DRE->getDecl();
4408 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4409 D = ME->getMemberDecl();
4410 }
4411
4412 // If it's a field, require the containing struct to have a
4413 // complete definition so that we can compute the layout.
4414 //
4415 // This can happen in C++11 onwards, either by naming the member
4416 // in a way that is not transformed into a member access expression
4417 // (in an unevaluated operand, for instance), or by naming the member
4418 // in a trailing-return-type.
4419 //
4420 // For the record, since __alignof__ on expressions is a GCC
4421 // extension, GCC seems to permit this but always gives the
4422 // nonsensical answer 0.
4423 //
4424 // We don't really need the layout here --- we could instead just
4425 // directly check for all the appropriate alignment-lowing
4426 // attributes --- but that would require duplicating a lot of
4427 // logic that just isn't worth duplicating for such a marginal
4428 // use-case.
4429 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4430 // Fast path this check, since we at least know the record has a
4431 // definition if we can find a member of it.
4432 if (!FD->getParent()->isCompleteDefinition()) {
4433 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4434 << E->getSourceRange();
4435 return true;
4436 }
4437
4438 // Otherwise, if it's a field, and the field doesn't have
4439 // reference type, then it must have a complete type (or be a
4440 // flexible array member, which we explicitly want to
4441 // white-list anyway), which makes the following checks trivial.
4442 if (!FD->getType()->isReferenceType())
4443 return false;
4444 }
4445
4446 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4447}
4448
4449bool Sema::CheckVecStepExpr(Expr *E) {
4450 E = E->IgnoreParens();
4451
4452 // Cannot know anything else if the expression is dependent.
4453 if (E->isTypeDependent())
4454 return false;
4455
4456 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4457}
4458
4459static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4460 CapturingScopeInfo *CSI) {
4461 assert(T->isVariablyModifiedType())(static_cast <bool> (T->isVariablyModifiedType()) ? void
(0) : __assert_fail ("T->isVariablyModifiedType()", "clang/lib/Sema/SemaExpr.cpp"
, 4461, __extension__ __PRETTY_FUNCTION__))
;
4462 assert(CSI != nullptr)(static_cast <bool> (CSI != nullptr) ? void (0) : __assert_fail
("CSI != nullptr", "clang/lib/Sema/SemaExpr.cpp", 4462, __extension__
__PRETTY_FUNCTION__))
;
4463
4464 // We're going to walk down into the type and look for VLA expressions.
4465 do {
4466 const Type *Ty = T.getTypePtr();
4467 switch (Ty->getTypeClass()) {
4468#define TYPE(Class, Base)
4469#define ABSTRACT_TYPE(Class, Base)
4470#define NON_CANONICAL_TYPE(Class, Base)
4471#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4472#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4473#include "clang/AST/TypeNodes.inc"
4474 T = QualType();
4475 break;
4476 // These types are never variably-modified.
4477 case Type::Builtin:
4478 case Type::Complex:
4479 case Type::Vector:
4480 case Type::ExtVector:
4481 case Type::ConstantMatrix:
4482 case Type::Record:
4483 case Type::Enum:
4484 case Type::Elaborated:
4485 case Type::TemplateSpecialization:
4486 case Type::ObjCObject:
4487 case Type::ObjCInterface:
4488 case Type::ObjCObjectPointer:
4489 case Type::ObjCTypeParam:
4490 case Type::Pipe:
4491 case Type::BitInt:
4492 llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!"
, "clang/lib/Sema/SemaExpr.cpp", 4492)
;
4493 case Type::Adjusted:
4494 T = cast<AdjustedType>(Ty)->getOriginalType();
4495 break;
4496 case Type::Decayed:
4497 T = cast<DecayedType>(Ty)->getPointeeType();
4498 break;
4499 case Type::Pointer:
4500 T = cast<PointerType>(Ty)->getPointeeType();
4501 break;
4502 case Type::BlockPointer:
4503 T = cast<BlockPointerType>(Ty)->getPointeeType();
4504 break;
4505 case Type::LValueReference:
4506 case Type::RValueReference:
4507 T = cast<ReferenceType>(Ty)->getPointeeType();
4508 break;
4509 case Type::MemberPointer:
4510 T = cast<MemberPointerType>(Ty)->getPointeeType();
4511 break;
4512 case Type::ConstantArray:
4513 case Type::IncompleteArray:
4514 // Losing element qualification here is fine.
4515 T = cast<ArrayType>(Ty)->getElementType();
4516 break;
4517 case Type::VariableArray: {
4518 // Losing element qualification here is fine.
4519 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4520
4521 // Unknown size indication requires no size computation.
4522 // Otherwise, evaluate and record it.
4523 auto Size = VAT->getSizeExpr();
4524 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4525 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4526 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4527
4528 T = VAT->getElementType();
4529 break;
4530 }
4531 case Type::FunctionProto:
4532 case Type::FunctionNoProto:
4533 T = cast<FunctionType>(Ty)->getReturnType();
4534 break;
4535 case Type::Paren:
4536 case Type::TypeOf:
4537 case Type::UnaryTransform:
4538 case Type::Attributed:
4539 case Type::BTFTagAttributed:
4540 case Type::SubstTemplateTypeParm:
4541 case Type::MacroQualified:
4542 // Keep walking after single level desugaring.
4543 T = T.getSingleStepDesugaredType(Context);
4544 break;
4545 case Type::Typedef:
4546 T = cast<TypedefType>(Ty)->desugar();
4547 break;
4548 case Type::Decltype:
4549 T = cast<DecltypeType>(Ty)->desugar();
4550 break;
4551 case Type::Using:
4552 T = cast<UsingType>(Ty)->desugar();
4553 break;
4554 case Type::Auto:
4555 case Type::DeducedTemplateSpecialization:
4556 T = cast<DeducedType>(Ty)->getDeducedType();
4557 break;
4558 case Type::TypeOfExpr:
4559 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4560 break;
4561 case Type::Atomic:
4562 T = cast<AtomicType>(Ty)->getValueType();
4563 break;
4564 }
4565 } while (!T.isNull() && T->isVariablyModifiedType());
4566}
4567
4568/// Build a sizeof or alignof expression given a type operand.
4569ExprResult
4570Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4571 SourceLocation OpLoc,
4572 UnaryExprOrTypeTrait ExprKind,
4573 SourceRange R) {
4574 if (!TInfo)
4575 return ExprError();
4576
4577 QualType T = TInfo->getType();
4578
4579 if (!T->isDependentType() &&
4580 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4581 return ExprError();
4582
4583 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4584 if (auto *TT = T->getAs<TypedefType>()) {
4585 for (auto I = FunctionScopes.rbegin(),
4586 E = std::prev(FunctionScopes.rend());
4587 I != E; ++I) {
4588 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4589 if (CSI == nullptr)
4590 break;
4591 DeclContext *DC = nullptr;
4592 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4593 DC = LSI->CallOperator;
4594 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4595 DC = CRSI->TheCapturedDecl;
4596 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4597 DC = BSI->TheDecl;
4598 if (DC) {
4599 if (DC->containsDecl(TT->getDecl()))
4600 break;
4601 captureVariablyModifiedType(Context, T, CSI);
4602 }
4603 }
4604 }
4605 }
4606
4607 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4608 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4609 TInfo->getType()->isVariablyModifiedType())
4610 TInfo = TransformToPotentiallyEvaluated(TInfo);
4611
4612 return new (Context) UnaryExprOrTypeTraitExpr(
4613 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4614}
4615
4616/// Build a sizeof or alignof expression given an expression
4617/// operand.
4618ExprResult
4619Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4620 UnaryExprOrTypeTrait ExprKind) {
4621 ExprResult PE = CheckPlaceholderExpr(E);
4622 if (PE.isInvalid())
4623 return ExprError();
4624
4625 E = PE.get();
4626
4627 // Verify that the operand is valid.
4628 bool isInvalid = false;
4629 if (E->isTypeDependent()) {
4630 // Delay type-checking for type-dependent expressions.
4631 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4632 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4633 } else if (ExprKind == UETT_VecStep) {
4634 isInvalid = CheckVecStepExpr(E);
4635 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4636 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4637 isInvalid = true;
4638 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4639 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4640 isInvalid = true;
4641 } else {
4642 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4643 }
4644
4645 if (isInvalid)
4646 return ExprError();
4647
4648 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4649 PE = TransformToPotentiallyEvaluated(E);
4650 if (PE.isInvalid()) return ExprError();
4651 E = PE.get();
4652 }
4653
4654 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4655 return new (Context) UnaryExprOrTypeTraitExpr(
4656 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4657}
4658
4659/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4660/// expr and the same for @c alignof and @c __alignof
4661/// Note that the ArgRange is invalid if isType is false.
4662ExprResult
4663Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4664 UnaryExprOrTypeTrait ExprKind, bool IsType,
4665 void *TyOrEx, SourceRange ArgRange) {
4666 // If error parsing type, ignore.
4667 if (!TyOrEx) return ExprError();
4668
4669 if (IsType) {
4670 TypeSourceInfo *TInfo;
4671 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4672 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4673 }
4674
4675 Expr *ArgEx = (Expr *)TyOrEx;
4676 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4677 return Result;
4678}
4679
4680static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4681 bool IsReal) {
4682 if (V.get()->isTypeDependent())
4683 return S.Context.DependentTy;
4684
4685 // _Real and _Imag are only l-values for normal l-values.
4686 if (V.get()->getObjectKind() != OK_Ordinary) {
4687 V = S.DefaultLvalueConversion(V.get());
4688 if (V.isInvalid())
4689 return QualType();
4690 }
4691
4692 // These operators return the element type of a complex type.
4693 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4694 return CT->getElementType();
4695
4696 // Otherwise they pass through real integer and floating point types here.
4697 if (V.get()->getType()->isArithmeticType())
4698 return V.get()->getType();
4699
4700 // Test for placeholders.
4701 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4702 if (PR.isInvalid()) return QualType();
4703 if (PR.get() != V.get()) {
4704 V = PR;
4705 return CheckRealImagOperand(S, V, Loc, IsReal);
4706 }
4707
4708 // Reject anything else.
4709 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4710 << (IsReal ? "__real" : "__imag");
4711 return QualType();
4712}
4713
4714
4715
4716ExprResult
4717Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4718 tok::TokenKind Kind, Expr *Input) {
4719 UnaryOperatorKind Opc;
4720 switch (Kind) {
4721 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp"
, 4721)
;
4722 case tok::plusplus: Opc = UO_PostInc; break;
4723 case tok::minusminus: Opc = UO_PostDec; break;
4724 }
4725
4726 // Since this might is a postfix expression, get rid of ParenListExprs.
4727 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4728 if (Result.isInvalid()) return ExprError();
4729 Input = Result.get();
4730
4731 return BuildUnaryOp(S, OpLoc, Opc, Input);
4732}
4733
4734/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4735///
4736/// \return true on error
4737static bool checkArithmeticOnObjCPointer(Sema &S,
4738 SourceLocation opLoc,
4739 Expr *op) {
4740 assert(op->getType()->isObjCObjectPointerType())(static_cast <bool> (op->getType()->isObjCObjectPointerType
()) ? void (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 4740, __extension__ __PRETTY_FUNCTION__
))
;
4741 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4742 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4743 return false;
4744
4745 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4746 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4747 << op->getSourceRange();
4748 return true;
4749}
4750
4751static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4752 auto *BaseNoParens = Base->IgnoreParens();
4753 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4754 return MSProp->getPropertyDecl()->getType()->isArrayType();
4755 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4756}
4757
4758// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4759// Typically this is DependentTy, but can sometimes be more precise.
4760//
4761// There are cases when we could determine a non-dependent type:
4762// - LHS and RHS may have non-dependent types despite being type-dependent
4763// (e.g. unbounded array static members of the current instantiation)
4764// - one may be a dependent-sized array with known element type
4765// - one may be a dependent-typed valid index (enum in current instantiation)
4766//
4767// We *always* return a dependent type, in such cases it is DependentTy.
4768// This avoids creating type-dependent expressions with non-dependent types.
4769// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4770static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4771 const ASTContext &Ctx) {
4772 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", 4772, __extension__ __PRETTY_FUNCTION__
))
;
4773 QualType LTy = LHS->getType(), RTy = RHS->getType();
4774 QualType Result = Ctx.DependentTy;
4775 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4776 if (const PointerType *PT = LTy->getAs<PointerType>())
4777 Result = PT->getPointeeType();
4778 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4779 Result = AT->getElementType();
4780 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4781 if (const PointerType *PT = RTy->getAs<PointerType>())
4782 Result = PT->getPointeeType();
4783 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4784 Result = AT->getElementType();
4785 }
4786 // Ensure we return a dependent type.
4787 return Result->isDependentType() ? Result : Ctx.DependentTy;
4788}
4789
4790static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4791
4792ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4793 SourceLocation lbLoc,
4794 MultiExprArg ArgExprs,
4795 SourceLocation rbLoc) {
4796
4797 if (base && !base->getType().isNull() &&
12
Assuming 'base' is non-null
13
Taking false branch
4798 base->hasPlaceholderType(BuiltinType::OMPArraySection))
4799 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4800 SourceLocation(), /*Length*/ nullptr,
4801 /*Stride=*/nullptr, rbLoc);
4802
4803 // Since this might be a postfix expression, get rid of ParenListExprs.
4804 if (isa<ParenListExpr>(base)) {
14
Assuming 'base' is not a 'ParenListExpr'
15
Taking false branch
4805 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4806 if (result.isInvalid())
4807 return ExprError();
4808 base = result.get();
4809 }
4810
4811 // Check if base and idx form a MatrixSubscriptExpr.
4812 //
4813 // Helper to check for comma expressions, which are not allowed as indices for
4814 // matrix subscript expressions.
4815 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4816 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4817 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4818 << SourceRange(base->getBeginLoc(), rbLoc);
4819 return true;
4820 }
4821 return false;
4822 };
4823 // The matrix subscript operator ([][])is considered a single operator.
4824 // Separating the index expressions by parenthesis is not allowed.
4825 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4826 !isa<MatrixSubscriptExpr>(base)) {
4827 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4828 << SourceRange(base->getBeginLoc(), rbLoc);
4829 return ExprError();
4830 }
4831 // If the base is a MatrixSubscriptExpr, try to create a new
4832 // MatrixSubscriptExpr.
4833 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
16
Assuming 'base' is a 'MatrixSubscriptExpr'
4834 if (matSubscriptE
16.1
'matSubscriptE' is non-null
16.1
'matSubscriptE' is non-null
) {
17
Taking true branch
4835 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4835, __extension__ __PRETTY_FUNCTION__))
;
18
Assuming the condition is true
19
'?' condition is true
4836 if (CheckAndReportCommaError(ArgExprs.front()))
4837 return ExprError();
4838
4839 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", 4840, __extension__ __PRETTY_FUNCTION__
))
20
Taking false branch
21
'?' condition is true
4840 "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", 4840, __extension__ __PRETTY_FUNCTION__
))
;
4841 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
22
Calling 'Sema::CreateBuiltinMatrixSubscriptExpr'
4842 matSubscriptE->getRowIdx(),
4843 ArgExprs.front(), rbLoc);
4844 }
4845
4846 // Handle any non-overload placeholder types in the base and index
4847 // expressions. We can't handle overloads here because the other
4848 // operand might be an overloadable type, in which case the overload
4849 // resolution for the operator overload should get the first crack
4850 // at the overload.
4851 bool IsMSPropertySubscript = false;
4852 if (base->getType()->isNonOverloadPlaceholderType()) {
4853 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4854 if (!IsMSPropertySubscript) {
4855 ExprResult result = CheckPlaceholderExpr(base);
4856 if (result.isInvalid())
4857 return ExprError();
4858 base = result.get();
4859 }
4860 }
4861
4862 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4863 if (base->getType()->isMatrixType()) {
4864 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4864, __extension__ __PRETTY_FUNCTION__))
;
4865 if (CheckAndReportCommaError(ArgExprs.front()))
4866 return ExprError();
4867
4868 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4869 rbLoc);
4870 }
4871
4872 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4873 Expr *idx = ArgExprs[0];
4874 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4875 (isa<CXXOperatorCallExpr>(idx) &&
4876 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4877 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4878 << SourceRange(base->getBeginLoc(), rbLoc);
4879 }
4880 }
4881
4882 if (ArgExprs.size() == 1 &&
4883 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4884 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4885 if (result.isInvalid())
4886 return ExprError();
4887 ArgExprs[0] = result.get();
4888 } else {
4889 if (checkArgsForPlaceholders(*this, ArgExprs))
4890 return ExprError();
4891 }
4892
4893 // Build an unanalyzed expression if either operand is type-dependent.
4894 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4895 (base->isTypeDependent() ||
4896 Expr::hasAnyTypeDependentArguments(ArgExprs))) {
4897 return new (Context) ArraySubscriptExpr(
4898 base, ArgExprs.front(),
4899 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4900 VK_LValue, OK_Ordinary, rbLoc);
4901 }
4902
4903 // MSDN, property (C++)
4904 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4905 // This attribute can also be used in the declaration of an empty array in a
4906 // class or structure definition. For example:
4907 // __declspec(property(get=GetX, put=PutX)) int x[];
4908 // The above statement indicates that x[] can be used with one or more array
4909 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4910 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4911 if (IsMSPropertySubscript) {
4912 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4912, __extension__ __PRETTY_FUNCTION__))
;
4913 // Build MS property subscript expression if base is MS property reference
4914 // or MS property subscript.
4915 return new (Context)
4916 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4917 VK_LValue, OK_Ordinary, rbLoc);
4918 }
4919
4920 // Use C++ overloaded-operator rules if either operand has record
4921 // type. The spec says to do this if either type is *overloadable*,
4922 // but enum types can't declare subscript operators or conversion
4923 // operators, so there's nothing interesting for overload resolution
4924 // to do if there aren't any record types involved.
4925 //
4926 // ObjC pointers have their own subscripting logic that is not tied
4927 // to overload resolution and so should not take this path.
4928 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4929 ((base->getType()->isRecordType() ||
4930 (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4931 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4932 }
4933
4934 ExprResult Res =
4935 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4936
4937 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4938 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4939
4940 return Res;
4941}
4942
4943ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4944 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4945 InitializationKind Kind =
4946 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4947 InitializationSequence InitSeq(*this, Entity, Kind, E);
4948 return InitSeq.Perform(*this, Entity, Kind, E);
4949}
4950
4951ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4952 Expr *ColumnIdx,
4953 SourceLocation RBLoc) {
4954 ExprResult BaseR = CheckPlaceholderExpr(Base);
4955 if (BaseR.isInvalid())
23
Assuming the condition is false
24
Taking false branch
4956 return BaseR;
4957 Base = BaseR.get();
4958
4959 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4960 if (RowR.isInvalid())
25
Assuming the condition is false
26
Taking false branch
4961 return RowR;
4962 RowIdx = RowR.get();
4963
4964 if (!ColumnIdx)
27
Assuming 'ColumnIdx' is non-null
4965 return new (Context) MatrixSubscriptExpr(
4966 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4967
4968 // Build an unanalyzed expression if any of the operands is type-dependent.
4969 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
28
Assuming the condition is false
29
Assuming the condition is false
31
Taking false branch
4970 ColumnIdx->isTypeDependent())
30
Assuming the condition is false
4971 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4972 Context.DependentTy, RBLoc);
4973
4974 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4975 if (ColumnR.isInvalid())
32
Assuming the condition is false
33
Taking false branch
4976 return ColumnR;
4977 ColumnIdx = ColumnR.get();
4978
4979 // Check that IndexExpr is an integer expression. If it is a constant
4980 // expression, check that it is less than Dim (= the number of elements in the
4981 // corresponding dimension).
4982 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4983 bool IsColumnIdx) -> Expr * {
4984 if (!IndexExpr->getType()->isIntegerType() &&
4985 !IndexExpr->isTypeDependent()) {
4986 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4987 << IsColumnIdx;
4988 return nullptr;
4989 }
4990
4991 if (Optional<llvm::APSInt> Idx =
4992 IndexExpr->getIntegerConstantExpr(Context)) {
4993 if ((*Idx < 0 || *Idx >= Dim)) {
4994 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4995 << IsColumnIdx << Dim;
4996 return nullptr;
4997 }
4998 }
4999
5000 ExprResult ConvExpr =
5001 tryConvertExprToType(IndexExpr, Context.getSizeType());
5002 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", 5003, __extension__ __PRETTY_FUNCTION__
))
5003 "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", 5003, __extension__ __PRETTY_FUNCTION__
))
;
5004 return ConvExpr.get();
5005 };
5006
5007 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
34
Assuming the object is not a 'ConstantMatrixType'
35
'MTy' initialized to a null pointer value
5008 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
36
Called C++ object pointer is null
5009 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5010 if (!RowIdx || !ColumnIdx)
5011 return ExprError();
5012
5013 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5014 MTy->getElementType(), RBLoc);
5015}
5016
5017void Sema::CheckAddressOfNoDeref(const Expr *E) {
5018 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5019 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5020
5021 // For expressions like `&(*s).b`, the base is recorded and what should be
5022 // checked.
5023 const MemberExpr *Member = nullptr;
5024 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5025 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5026
5027 LastRecord.PossibleDerefs.erase(StrippedExpr);
5028}
5029
5030void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5031 if (isUnevaluatedContext())
5032 return;
5033
5034 QualType ResultTy = E->getType();
5035 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5036
5037 // Bail if the element is an array since it is not memory access.
5038 if (isa<ArrayType>(ResultTy))
5039 return;
5040
5041 if (ResultTy->hasAttr(attr::NoDeref)) {
5042 LastRecord.PossibleDerefs.insert(E);
5043 return;
5044 }
5045
5046 // Check if the base type is a pointer to a member access of a struct
5047 // marked with noderef.
5048 const Expr *Base = E->getBase();
5049 QualType BaseTy = Base->getType();
5050 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5051 // Not a pointer access
5052 return;
5053
5054 const MemberExpr *Member = nullptr;
5055 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5056 Member->isArrow())
5057 Base = Member->getBase();
5058
5059 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5060 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5061 LastRecord.PossibleDerefs.insert(E);
5062 }
5063}
5064
5065ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5066 Expr *LowerBound,
5067 SourceLocation ColonLocFirst,
5068 SourceLocation ColonLocSecond,
5069 Expr *Length, Expr *Stride,
5070 SourceLocation RBLoc) {
5071 if (Base->hasPlaceholderType() &&
5072 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5073 ExprResult Result = CheckPlaceholderExpr(Base);
5074 if (Result.isInvalid())
5075 return ExprError();
5076 Base = Result.get();
5077 }
5078 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5079 ExprResult Result = CheckPlaceholderExpr(LowerBound);
5080 if (Result.isInvalid())
5081 return ExprError();
5082 Result = DefaultLvalueConversion(Result.get());
5083 if (Result.isInvalid())
5084 return ExprError();
5085 LowerBound = Result.get();
5086 }
5087 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5088 ExprResult Result = CheckPlaceholderExpr(Length);
5089 if (Result.isInvalid())
5090 return ExprError();
5091 Result = DefaultLvalueConversion(Result.get());
5092 if (Result.isInvalid())
5093 return ExprError();
5094 Length = Result.get();
5095 }
5096 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5097 ExprResult Result = CheckPlaceholderExpr(Stride);
5098 if (Result.isInvalid())
5099 return ExprError();
5100 Result = DefaultLvalueConversion(Result.get());
5101 if (Result.isInvalid())
5102 return ExprError();
5103 Stride = Result.get();
5104 }
5105
5106 // Build an unanalyzed expression if either operand is type-dependent.
5107 if (Base->isTypeDependent() ||
5108 (LowerBound &&
5109 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5110 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5111 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5112 return new (Context) OMPArraySectionExpr(
5113 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5114 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5115 }
5116
5117 // Perform default conversions.
5118 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5119 QualType ResultTy;
5120 if (OriginalTy->isAnyPointerType()) {
5121 ResultTy = OriginalTy->getPointeeType();
5122 } else if (OriginalTy->isArrayType()) {
5123 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5124 } else {
5125 return ExprError(
5126 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5127 << Base->getSourceRange());
5128 }
5129 // C99 6.5.2.1p1
5130 if (LowerBound) {
5131 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5132 LowerBound);
5133 if (Res.isInvalid())
5134 return ExprError(Diag(LowerBound->getExprLoc(),
5135 diag::err_omp_typecheck_section_not_integer)
5136 << 0 << LowerBound->getSourceRange());
5137 LowerBound = Res.get();
5138
5139 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5140 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5141 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5142 << 0 << LowerBound->getSourceRange();
5143 }
5144 if (Length) {
5145 auto Res =
5146 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5147 if (Res.isInvalid())
5148 return ExprError(Diag(Length->getExprLoc(),
5149 diag::err_omp_typecheck_section_not_integer)
5150 << 1 << Length->getSourceRange());
5151 Length = Res.get();
5152
5153 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5154 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5155 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5156 << 1 << Length->getSourceRange();
5157 }
5158 if (Stride) {
5159 ExprResult Res =
5160 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5161 if (Res.isInvalid())
5162 return ExprError(Diag(Stride->getExprLoc(),
5163 diag::err_omp_typecheck_section_not_integer)
5164 << 1 << Stride->getSourceRange());
5165 Stride = Res.get();
5166
5167 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5168 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5169 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5170 << 1 << Stride->getSourceRange();
5171 }
5172
5173 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5174 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5175 // type. Note that functions are not objects, and that (in C99 parlance)
5176 // incomplete types are not object types.
5177 if (ResultTy->isFunctionType()) {
5178 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5179 << ResultTy << Base->getSourceRange();
5180 return ExprError();
5181 }
5182
5183 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5184 diag::err_omp_section_incomplete_type, Base))
5185 return ExprError();
5186
5187 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5188 Expr::EvalResult Result;
5189 if (LowerBound->EvaluateAsInt(Result, Context)) {
5190 // OpenMP 5.0, [2.1.5 Array Sections]
5191 // The array section must be a subset of the original array.
5192 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5193 if (LowerBoundValue.isNegative()) {
5194 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5195 << LowerBound->getSourceRange();
5196 return ExprError();
5197 }
5198 }
5199 }
5200
5201 if (Length) {
5202 Expr::EvalResult Result;
5203 if (Length->EvaluateAsInt(Result, Context)) {
5204 // OpenMP 5.0, [2.1.5 Array Sections]
5205 // The length must evaluate to non-negative integers.
5206 llvm::APSInt LengthValue = Result.Val.getInt();
5207 if (LengthValue.isNegative()) {
5208 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5209 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5210 << Length->getSourceRange();
5211 return ExprError();
5212 }
5213 }
5214 } else if (ColonLocFirst.isValid() &&
5215 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5216 !OriginalTy->isVariableArrayType()))) {
5217 // OpenMP 5.0, [2.1.5 Array Sections]
5218 // When the size of the array dimension is not known, the length must be
5219 // specified explicitly.
5220 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5221 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5222 return ExprError();
5223 }
5224
5225 if (Stride) {
5226 Expr::EvalResult Result;
5227 if (Stride->EvaluateAsInt(Result, Context)) {
5228 // OpenMP 5.0, [2.1.5 Array Sections]
5229 // The stride must evaluate to a positive integer.
5230 llvm::APSInt StrideValue = Result.Val.getInt();
5231 if (!StrideValue.isStrictlyPositive()) {
5232 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5233 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5234 << Stride->getSourceRange();
5235 return ExprError();
5236 }
5237 }
5238 }
5239
5240 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5241 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5242 if (Result.isInvalid())
5243 return ExprError();
5244 Base = Result.get();
5245 }
5246 return new (Context) OMPArraySectionExpr(
5247 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5248 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5249}
5250
5251ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5252 SourceLocation RParenLoc,
5253 ArrayRef<Expr *> Dims,
5254 ArrayRef<SourceRange> Brackets) {
5255 if (Base->hasPlaceholderType()) {
5256 ExprResult Result = CheckPlaceholderExpr(Base);
5257 if (Result.isInvalid())
5258 return ExprError();
5259 Result = DefaultLvalueConversion(Result.get());
5260 if (Result.isInvalid())
5261 return ExprError();
5262 Base = Result.get();
5263 }
5264 QualType BaseTy = Base->getType();
5265 // Delay analysis of the types/expressions if instantiation/specialization is
5266 // required.
5267 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5268 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5269 LParenLoc, RParenLoc, Dims, Brackets);
5270 if (!BaseTy->isPointerType() ||
5271 (!Base->isTypeDependent() &&
5272 BaseTy->getPointeeType()->isIncompleteType()))
5273 return ExprError(Diag(Base->getExprLoc(),
5274 diag::err_omp_non_pointer_type_array_shaping_base)
5275 << Base->getSourceRange());
5276
5277 SmallVector<Expr *, 4> NewDims;
5278 bool ErrorFound = false;
5279 for (Expr *Dim : Dims) {
5280 if (Dim->hasPlaceholderType()) {
5281 ExprResult Result = CheckPlaceholderExpr(Dim);
5282 if (Result.isInvalid()) {
5283 ErrorFound = true;
5284 continue;
5285 }
5286 Result = DefaultLvalueConversion(Result.get());
5287 if (Result.isInvalid()) {
5288 ErrorFound = true;
5289 continue;
5290 }
5291 Dim = Result.get();
5292 }
5293 if (!Dim->isTypeDependent()) {
5294 ExprResult Result =
5295 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5296 if (Result.isInvalid()) {
5297 ErrorFound = true;
5298 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5299 << Dim->getSourceRange();
5300 continue;
5301 }
5302 Dim = Result.get();
5303 Expr::EvalResult EvResult;
5304 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5305 // OpenMP 5.0, [2.1.4 Array Shaping]
5306 // Each si is an integral type expression that must evaluate to a
5307 // positive integer.
5308 llvm::APSInt Value = EvResult.Val.getInt();
5309 if (!Value.isStrictlyPositive()) {
5310 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5311 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5312 << Dim->getSourceRange();
5313 ErrorFound = true;
5314 continue;
5315 }
5316 }
5317 }
5318 NewDims.push_back(Dim);
5319 }
5320 if (ErrorFound)
5321 return ExprError();
5322 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5323 LParenLoc, RParenLoc, NewDims, Brackets);
5324}
5325
5326ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5327 SourceLocation LLoc, SourceLocation RLoc,
5328 ArrayRef<OMPIteratorData> Data) {
5329 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5330 bool IsCorrect = true;
5331 for (const OMPIteratorData &D : Data) {
5332 TypeSourceInfo *TInfo = nullptr;
5333 SourceLocation StartLoc;
5334 QualType DeclTy;
5335 if (!D.Type.getAsOpaquePtr()) {
5336 // OpenMP 5.0, 2.1.6 Iterators
5337 // In an iterator-specifier, if the iterator-type is not specified then
5338 // the type of that iterator is of int type.
5339 DeclTy = Context.IntTy;
5340 StartLoc = D.DeclIdentLoc;
5341 } else {
5342 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5343 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5344 }
5345
5346 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5347 DeclTy->containsUnexpandedParameterPack() ||
5348 DeclTy->isInstantiationDependentType();
5349 if (!IsDeclTyDependent) {
5350 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5351 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5352 // The iterator-type must be an integral or pointer type.
5353 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5354 << DeclTy;
5355 IsCorrect = false;
5356 continue;
5357 }
5358 if (DeclTy.isConstant(Context)) {
5359 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5360 // The iterator-type must not be const qualified.
5361 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5362 << DeclTy;
5363 IsCorrect = false;
5364 continue;
5365 }
5366 }
5367
5368 // Iterator declaration.
5369 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", 5369, __extension__ __PRETTY_FUNCTION__
))
;
5370 // Always try to create iterator declarator to avoid extra error messages
5371 // about unknown declarations use.
5372 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5373 D.DeclIdent, DeclTy, TInfo, SC_None);
5374 VD->setImplicit();
5375 if (S) {
5376 // Check for conflicting previous declaration.
5377 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5378 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5379 ForVisibleRedeclaration);
5380 Previous.suppressDiagnostics();
5381 LookupName(Previous, S);
5382
5383 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5384 /*AllowInlineNamespace=*/false);
5385 if (!Previous.empty()) {
5386 NamedDecl *Old = Previous.getRepresentativeDecl();
5387 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5388 Diag(Old->getLocation(), diag::note_previous_definition);
5389 } else {
5390 PushOnScopeChains(VD, S);
5391 }
5392 } else {
5393 CurContext->addDecl(VD);
5394 }
5395 Expr *Begin = D.Range.Begin;
5396 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5397 ExprResult BeginRes =
5398 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5399 Begin = BeginRes.get();
5400 }
5401 Expr *End = D.Range.End;
5402 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5403 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5404 End = EndRes.get();
5405 }
5406 Expr *Step = D.Range.Step;
5407 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5408 if (!Step->getType()->isIntegralType(Context)) {
5409 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5410 << Step << Step->getSourceRange();
5411 IsCorrect = false;
5412 continue;
5413 }
5414 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5415 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5416 // If the step expression of a range-specification equals zero, the
5417 // behavior is unspecified.
5418 if (Result && Result->isZero()) {
5419 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5420 << Step << Step->getSourceRange();
5421 IsCorrect = false;
5422 continue;
5423 }
5424 }
5425 if (!Begin || !End || !IsCorrect) {
5426 IsCorrect = false;
5427 continue;
5428 }
5429 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5430 IDElem.IteratorDecl = VD;
5431 IDElem.AssignmentLoc = D.AssignLoc;
5432 IDElem.Range.Begin = Begin;
5433 IDElem.Range.End = End;
5434 IDElem.Range.Step = Step;
5435 IDElem.ColonLoc = D.ColonLoc;
5436 IDElem.SecondColonLoc = D.SecColonLoc;
5437 }
5438 if (!IsCorrect) {
5439 // Invalidate all created iterator declarations if error is found.
5440 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5441 if (Decl *ID = D.IteratorDecl)
5442 ID->setInvalidDecl();
5443 }
5444 return ExprError();
5445 }
5446 SmallVector<OMPIteratorHelperData, 4> Helpers;
5447 if (!CurContext->isDependentContext()) {
5448 // Build number of ityeration for each iteration range.
5449 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5450 // ((Begini-Stepi-1-Endi) / -Stepi);
5451 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5452 // (Endi - Begini)
5453 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5454 D.Range.Begin);
5455 if(!Res.isUsable()) {
5456 IsCorrect = false;
5457 continue;
5458 }
5459 ExprResult St, St1;
5460 if (D.Range.Step) {
5461 St = D.Range.Step;
5462 // (Endi - Begini) + Stepi
5463 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5464 if (!Res.isUsable()) {
5465 IsCorrect = false;
5466 continue;
5467 }
5468 // (Endi - Begini) + Stepi - 1
5469 Res =
5470 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5471 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5472 if (!Res.isUsable()) {
5473 IsCorrect = false;
5474 continue;
5475 }
5476 // ((Endi - Begini) + Stepi - 1) / Stepi
5477 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5478 if (!Res.isUsable()) {
5479 IsCorrect = false;
5480 continue;
5481 }
5482 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5483 // (Begini - Endi)
5484 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5485 D.Range.Begin, D.Range.End);
5486 if (!Res1.isUsable()) {
5487 IsCorrect = false;
5488 continue;
5489 }
5490 // (Begini - Endi) - Stepi
5491 Res1 =
5492 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5493 if (!Res1.isUsable()) {
5494 IsCorrect = false;
5495 continue;
5496 }
5497 // (Begini - Endi) - Stepi - 1
5498 Res1 =
5499 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5500 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5501 if (!Res1.isUsable()) {
5502 IsCorrect = false;
5503 continue;
5504 }
5505 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5506 Res1 =
5507 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5508 if (!Res1.isUsable()) {
5509 IsCorrect = false;
5510 continue;
5511 }
5512 // Stepi > 0.
5513 ExprResult CmpRes =
5514 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5515 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5516 if (!CmpRes.isUsable()) {
5517 IsCorrect = false;
5518 continue;
5519 }
5520 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5521 Res.get(), Res1.get());
5522 if (!Res.isUsable()) {
5523 IsCorrect = false;
5524 continue;
5525 }
5526 }
5527 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5528 if (!Res.isUsable()) {
5529 IsCorrect = false;
5530 continue;
5531 }
5532
5533 // Build counter update.
5534 // Build counter.
5535 auto *CounterVD =
5536 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5537 D.IteratorDecl->getBeginLoc(), nullptr,
5538 Res.get()->getType(), nullptr, SC_None);
5539 CounterVD->setImplicit();
5540 ExprResult RefRes =
5541 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5542 D.IteratorDecl->getBeginLoc());
5543 // Build counter update.
5544 // I = Begini + counter * Stepi;
5545 ExprResult UpdateRes;
5546 if (D.Range.Step) {
5547 UpdateRes = CreateBuiltinBinOp(
5548 D.AssignmentLoc, BO_Mul,
5549 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5550 } else {
5551 UpdateRes = DefaultLvalueConversion(RefRes.get());
5552 }
5553 if (!UpdateRes.isUsable()) {
5554 IsCorrect = false;
5555 continue;
5556 }
5557 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5558 UpdateRes.get());
5559 if (!UpdateRes.isUsable()) {
5560 IsCorrect = false;
5561 continue;
5562 }
5563 ExprResult VDRes =
5564 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5565 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5566 D.IteratorDecl->getBeginLoc());
5567 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5568 UpdateRes.get());
5569 if (!UpdateRes.isUsable()) {
5570 IsCorrect = false;
5571 continue;
5572 }
5573 UpdateRes =
5574 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5575 if (!UpdateRes.isUsable()) {
5576 IsCorrect = false;
5577 continue;
5578 }
5579 ExprResult CounterUpdateRes =
5580 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5581 if (!CounterUpdateRes.isUsable()) {
5582 IsCorrect = false;
5583 continue;
5584 }
5585 CounterUpdateRes =
5586 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5587 if (!CounterUpdateRes.isUsable()) {
5588 IsCorrect = false;
5589 continue;
5590 }
5591 OMPIteratorHelperData &HD = Helpers.emplace_back();
5592 HD.CounterVD = CounterVD;
5593 HD.Upper = Res.get();
5594 HD.Update = UpdateRes.get();
5595 HD.CounterUpdate = CounterUpdateRes.get();
5596 }
5597 } else {
5598 Helpers.assign(ID.size(), {});
5599 }
5600 if (!IsCorrect) {
5601 // Invalidate all created iterator declarations if error is found.
5602 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5603 if (Decl *ID = D.IteratorDecl)
5604 ID->setInvalidDecl();
5605 }
5606 return ExprError();
5607 }
5608 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5609 LLoc, RLoc, ID, Helpers);
5610}
5611
5612ExprResult
5613Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5614 Expr *Idx, SourceLocation RLoc) {
5615 Expr *LHSExp = Base;
5616 Expr *RHSExp = Idx;
5617
5618 ExprValueKind VK = VK_LValue;
5619 ExprObjectKind OK = OK_Ordinary;
5620
5621 // Per C++ core issue 1213, the result is an xvalue if either operand is
5622 // a non-lvalue array, and an lvalue otherwise.
5623 if (getLangOpts().CPlusPlus11) {
5624 for (auto *Op : {LHSExp, RHSExp}) {
5625 Op = Op->IgnoreImplicit();
5626 if (Op->getType()->isArrayType() && !Op->isLValue())
5627 VK = VK_XValue;
5628 }
5629 }
5630
5631 // Perform default conversions.
5632 if (!LHSExp->getType()->getAs<VectorType>()) {
5633 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5634 if (Result.isInvalid())
5635 return ExprError();
5636 LHSExp = Result.get();
5637 }
5638 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5639 if (Result.isInvalid())
5640 return ExprError();
5641 RHSExp = Result.get();
5642
5643 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5644
5645 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5646 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5647 // in the subscript position. As a result, we need to derive the array base
5648 // and index from the expression types.
5649 Expr *BaseExpr, *IndexExpr;
5650 QualType ResultType;
5651 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5652 BaseExpr = LHSExp;
5653 IndexExpr = RHSExp;
5654 ResultType =
5655 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5656 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5657 BaseExpr = LHSExp;
5658 IndexExpr = RHSExp;
5659 ResultType = PTy->getPointeeType();
5660 } else if (const ObjCObjectPointerType *PTy =
5661 LHSTy->getAs<ObjCObjectPointerType>()) {
5662 BaseExpr = LHSExp;
5663 IndexExpr = RHSExp;
5664
5665 // Use custom logic if this should be the pseudo-object subscript
5666 // expression.
5667 if (!LangOpts.isSubscriptPointerArithmetic())
5668 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5669 nullptr);
5670
5671 ResultType = PTy->getPointeeType();
5672 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5673 // Handle the uncommon case of "123[Ptr]".
5674 BaseExpr = RHSExp;
5675 IndexExpr = LHSExp;
5676 ResultType = PTy->getPointeeType();
5677 } else if (const ObjCObjectPointerType *PTy =
5678 RHSTy->getAs<ObjCObjectPointerType>()) {
5679 // Handle the uncommon case of "123[Ptr]".
5680 BaseExpr = RHSExp;
5681 IndexExpr = LHSExp;
5682 ResultType = PTy->getPointeeType();
5683 if (!LangOpts.isSubscriptPointerArithmetic()) {
5684 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5685 << ResultType << BaseExpr->getSourceRange();
5686 return ExprError();
5687 }
5688 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5689 BaseExpr = LHSExp; // vectors: V[123]
5690 IndexExpr = RHSExp;
5691 // We apply C++ DR1213 to vector subscripting too.
5692 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5693 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5694 if (Materialized.isInvalid())
5695 return ExprError();
5696 LHSExp = Materialized.get();
5697 }
5698 VK = LHSExp->getValueKind();
5699 if (VK != VK_PRValue)
5700 OK = OK_VectorComponent;
5701
5702 ResultType = VTy->getElementType();
5703 QualType BaseType = BaseExpr->getType();
5704 Qualifiers BaseQuals = BaseType.getQualifiers();
5705 Qualifiers MemberQuals = ResultType.getQualifiers();
5706 Qualifiers Combined = BaseQuals + MemberQuals;
5707 if (Combined != MemberQuals)
5708 ResultType = Context.getQualifiedType(ResultType, Combined);
5709 } else if (LHSTy->isBuiltinType() &&
5710 LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) {
5711 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5712 if (BTy->isSVEBool())
5713 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5714 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5715
5716 BaseExpr = LHSExp;
5717 IndexExpr = RHSExp;
5718 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5719 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5720 if (Materialized.isInvalid())
5721 return ExprError();
5722 LHSExp = Materialized.get();
5723 }
5724 VK = LHSExp->getValueKind();
5725 if (VK != VK_PRValue)
5726 OK = OK_VectorComponent;
5727
5728 ResultType = BTy->getSveEltType(Context);
5729
5730 QualType BaseType = BaseExpr->getType();
5731 Qualifiers BaseQuals = BaseType.getQualifiers();
5732 Qualifiers MemberQuals = ResultType.getQualifiers();
5733 Qualifiers Combined = BaseQuals + MemberQuals;
5734 if (Combined != MemberQuals)
5735 ResultType = Context.getQualifiedType(ResultType, Combined);
5736 } else if (LHSTy->isArrayType()) {
5737 // If we see an array that wasn't promoted by
5738 // DefaultFunctionArrayLvalueConversion, it must be an array that
5739 // wasn't promoted because of the C90 rule that doesn't
5740 // allow promoting non-lvalue arrays. Warn, then
5741 // force the promotion here.
5742 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5743 << LHSExp->getSourceRange();
5744 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5745 CK_ArrayToPointerDecay).get();
5746 LHSTy = LHSExp->getType();
5747
5748 BaseExpr = LHSExp;
5749 IndexExpr = RHSExp;
5750 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5751 } else if (RHSTy->isArrayType()) {
5752 // Same as previous, except for 123[f().a] case
5753 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5754 << RHSExp->getSourceRange();
5755 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5756 CK_ArrayToPointerDecay).get();
5757 RHSTy = RHSExp->getType();
5758
5759 BaseExpr = RHSExp;
5760 IndexExpr = LHSExp;
5761 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5762 } else {
5763 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5764 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5765 }
5766 // C99 6.5.2.1p1
5767 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5768 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5769 << IndexExpr->getSourceRange());
5770
5771 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5772 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5773 && !IndexExpr->isTypeDependent())
5774 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5775
5776 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5777 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5778 // type. Note that Functions are not objects, and that (in C99 parlance)
5779 // incomplete types are not object types.
5780 if (ResultType->isFunctionType()) {
5781 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5782 << ResultType << BaseExpr->getSourceRange();
5783 return ExprError();
5784 }
5785
5786 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5787 // GNU extension: subscripting on pointer to void
5788 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5789 << BaseExpr->getSourceRange();
5790
5791 // C forbids expressions of unqualified void type from being l-values.
5792 // See IsCForbiddenLValueType.
5793 if (!ResultType.hasQualifiers())
5794 VK = VK_PRValue;
5795 } else if (!ResultType->isDependentType() &&
5796 RequireCompleteSizedType(
5797 LLoc, ResultType,
5798 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5799 return ExprError();
5800
5801 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", 5802, __extension__ __PRETTY_FUNCTION__
))
5802 !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", 5802, __extension__ __PRETTY_FUNCTION__
))
;
5803
5804 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5805 FunctionScopes.size() > 1) {
5806 if (auto *TT =
5807 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5808 for (auto I = FunctionScopes.rbegin(),
5809 E = std::prev(FunctionScopes.rend());
5810 I != E; ++I) {
5811 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5812 if (CSI == nullptr)
5813 break;
5814 DeclContext *DC = nullptr;
5815 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5816 DC = LSI->CallOperator;
5817 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5818 DC = CRSI->TheCapturedDecl;
5819 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5820 DC = BSI->TheDecl;
5821 if (DC) {
5822 if (DC->containsDecl(TT->getDecl()))
5823 break;
5824 captureVariablyModifiedType(
5825 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5826 }
5827 }
5828 }
5829 }
5830
5831 return new (Context)
5832 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5833}
5834
5835bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5836 ParmVarDecl *Param) {
5837 if (Param->hasUnparsedDefaultArg()) {
5838 // If we've already cleared out the location for the default argument,
5839 // that means we're parsing it right now.
5840 if (!UnparsedDefaultArgLocs.count(Param)) {
5841 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5842 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5843 Param->setInvalidDecl();
5844 return true;
5845 }
5846
5847 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5848 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5849 Diag(UnparsedDefaultArgLocs[Param],
5850 diag::note_default_argument_declared_here);
5851 return true;
5852 }
5853
5854 if (Param->hasUninstantiatedDefaultArg() &&
5855 InstantiateDefaultArgument(CallLoc, FD, Param))
5856 return true;
5857
5858 assert(Param->hasInit() && "default argument but no initializer?")(static_cast <bool> (Param->hasInit() && "default argument but no initializer?"
) ? void (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\""
, "clang/lib/Sema/SemaExpr.cpp", 5858, __extension__ __PRETTY_FUNCTION__
))
;
5859
5860 // If the default expression creates temporaries, we need to
5861 // push them to the current stack of expression temporaries so they'll
5862 // be properly destroyed.
5863 // FIXME: We should really be rebuilding the default argument with new
5864 // bound temporaries; see the comment in PR5810.
5865 // We don't need to do that with block decls, though, because
5866 // blocks in default argument expression can never capture anything.
5867 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5868 // Set the "needs cleanups" bit regardless of whether there are
5869 // any explicit objects.
5870 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5871
5872 // Append all the objects to the cleanup list. Right now, this
5873 // should always be a no-op, because blocks in default argument
5874 // expressions should never be able to capture anything.
5875 assert(!Init->getNumObjects() &&(static_cast <bool> (!Init->getNumObjects() &&
"default argument expression has capturing blocks?") ? void (
0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "clang/lib/Sema/SemaExpr.cpp", 5876, __extension__ __PRETTY_FUNCTION__
))
5876 "default argument expression has capturing blocks?")(static_cast <bool> (!Init->getNumObjects() &&
"default argument expression has capturing blocks?") ? void (
0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "clang/lib/Sema/SemaExpr.cpp", 5876, __extension__ __PRETTY_FUNCTION__
))
;
5877 }
5878
5879 // We already type-checked the argument, so we know it works.
5880 // Just mark all of the declarations in this potentially-evaluated expression
5881 // as being "referenced".
5882 EnterExpressionEvaluationContext EvalContext(
5883 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5884 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5885 /*SkipLocalVariables=*/true);
5886 return false;
5887}
5888
5889ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5890 FunctionDecl *FD, ParmVarDecl *Param) {
5891 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", 5891, __extension__ __PRETTY_FUNCTION__
))
;
5892 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5893 return ExprError();
5894 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5895}
5896
5897Sema::VariadicCallType
5898Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5899 Expr *Fn) {
5900 if (Proto && Proto->isVariadic()) {
5901 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5902 return VariadicConstructor;
5903 else if (Fn && Fn->getType()->isBlockPointerType())
5904 return VariadicBlock;
5905 else if (FDecl) {
5906 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5907 if (Method->isInstance())
5908 return VariadicMethod;
5909 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5910 return VariadicMethod;
5911 return VariadicFunction;
5912 }
5913 return VariadicDoesNotApply;
5914}
5915
5916namespace {
5917class FunctionCallCCC final : public FunctionCallFilterCCC {
5918public:
5919 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5920 unsigned NumArgs, MemberExpr *ME)
5921 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5922 FunctionName(FuncName) {}
5923
5924 bool ValidateCandidate(const TypoCorrection &candidate) override {
5925 if (!candidate.getCorrectionSpecifier() ||
5926 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5927 return false;
5928 }
5929
5930 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5931 }
5932
5933 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5934 return std::make_unique<FunctionCallCCC>(*this);
5935 }
5936
5937private:
5938 const IdentifierInfo *const FunctionName;
5939};
5940}
5941
5942static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5943 FunctionDecl *FDecl,
5944 ArrayRef<Expr *> Args) {
5945 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5946 DeclarationName FuncName = FDecl->getDeclName();
5947 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5948
5949 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5950 if (TypoCorrection Corrected = S.CorrectTypo(
5951 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5952 S.getScopeForContext(S.CurContext), nullptr, CCC,
5953 Sema::CTK_ErrorRecovery)) {
5954 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5955 if (Corrected.isOverloaded()) {
5956 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5957 OverloadCandidateSet::iterator Best;
5958 for (NamedDecl *CD : Corrected) {
5959 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5960 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5961 OCS);
5962 }
5963 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5964 case OR_Success:
5965 ND = Best->FoundDecl;
5966 Corrected.setCorrectionDecl(ND);
5967 break;
5968 default:
5969 break;
5970 }
5971 }
5972 ND = ND->getUnderlyingDecl();
5973 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5974 return Corrected;
5975 }
5976 }
5977 return TypoCorrection();
5978}
5979
5980/// ConvertArgumentsForCall - Converts the arguments specified in
5981/// Args/NumArgs to the parameter types of the function FDecl with
5982/// function prototype Proto. Call is the call expression itself, and
5983/// Fn is the function expression. For a C++ member function, this
5984/// routine does not attempt to convert the object argument. Returns
5985/// true if the call is ill-formed.
5986bool
5987Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5988 FunctionDecl *FDecl,
5989 const FunctionProtoType *Proto,
5990 ArrayRef<Expr *> Args,
5991 SourceLocation RParenLoc,
5992 bool IsExecConfig) {
5993 // Bail out early if calling a builtin with custom typechecking.
5994 if (FDecl)
5995 if (unsigned ID = FDecl->getBuiltinID())
5996 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5997 return false;
5998
5999 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6000 // assignment, to the types of the corresponding parameter, ...
6001 unsigned NumParams = Proto->getNumParams();
6002 bool Invalid = false;
6003 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6004 unsigned FnKind = Fn->getType()->isBlockPointerType()
6005 ? 1 /* block */
6006 : (IsExecConfig ? 3 /* kernel function (exec config) */
6007 : 0 /* function */);
6008
6009 // If too few arguments are available (and we don't have default
6010 // arguments for the remaining parameters), don't make the call.
6011 if (Args.size() < NumParams) {
6012 if (Args.size() < MinArgs) {
6013 TypoCorrection TC;
6014 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6015 unsigned diag_id =
6016 MinArgs == NumParams && !Proto->isVariadic()
6017 ? diag::err_typecheck_call_too_few_args_suggest
6018 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6019 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
6020 << static_cast<unsigned>(Args.size())
6021 << TC.getCorrectionRange());
6022 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
6023 Diag(RParenLoc,
6024 MinArgs == NumParams && !Proto->isVariadic()
6025 ? diag::err_typecheck_call_too_few_args_one
6026 : diag::err_typecheck_call_too_few_args_at_least_one)
6027 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
6028 else
6029 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6030 ? diag::err_typecheck_call_too_few_args
6031 : diag::err_typecheck_call_too_few_args_at_least)
6032 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
6033 << Fn->getSourceRange();
6034
6035 // Emit the location of the prototype.
6036 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6037 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6038
6039 return true;
6040 }
6041 // We reserve space for the default arguments when we create
6042 // the call expression, before calling ConvertArgumentsForCall.
6043 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", 6044, __extension__ __PRETTY_FUNCTION__
))
6044 "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", 6044, __extension__ __PRETTY_FUNCTION__
))
;
6045 }
6046
6047 // If too many are passed and not variadic, error on the extras and drop
6048 // them.
6049 if (Args.size() > NumParams) {
6050 if (!Proto->isVariadic()) {
6051 TypoCorrection TC;
6052 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6053 unsigned diag_id =
6054 MinArgs == NumParams && !Proto->isVariadic()
6055 ? diag::err_typecheck_call_too_many_args_suggest
6056 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6057 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6058 << static_cast<unsigned>(Args.size())
6059 << TC.getCorrectionRange());
6060 } else if (NumParams == 1 && FDecl &&
6061 FDecl->getParamDecl(0)->getDeclName())
6062 Diag(Args[NumParams]->getBeginLoc(),
6063 MinArgs == NumParams
6064 ? diag::err_typecheck_call_too_many_args_one
6065 : diag::err_typecheck_call_too_many_args_at_most_one)
6066 << FnKind << FDecl->getParamDecl(0)
6067 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6068 << SourceRange(Args[NumParams]->getBeginLoc(),
6069 Args.back()->getEndLoc());
6070 else
6071 Diag(Args[NumParams]->getBeginLoc(),
6072 MinArgs == NumParams
6073 ? diag::err_typecheck_call_too_many_args
6074 : diag::err_typecheck_call_too_many_args_at_most)
6075 << FnKind << NumParams << static_cast<unsigned>(Args.size())
6076 << Fn->getSourceRange()
6077 << SourceRange(Args[NumParams]->getBeginLoc(),
6078 Args.back()->getEndLoc());
6079
6080 // Emit the location of the prototype.
6081 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6082 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6083
6084 // This deletes the extra arguments.
6085 Call->shrinkNumArgs(NumParams);
6086 return true;
6087 }
6088 }
6089 SmallVector<Expr *, 8> AllArgs;
6090 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6091
6092 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6093 AllArgs, CallType);
6094 if (Invalid)
6095 return true;
6096 unsigned TotalNumArgs = AllArgs.size();
6097 for (unsigned i = 0; i < TotalNumArgs; ++i)
6098 Call->setArg(i, AllArgs[i]);
6099
6100 Call->computeDependence();
6101 return false;
6102}
6103
6104bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6105 const FunctionProtoType *Proto,
6106 unsigned FirstParam, ArrayRef<Expr *> Args,
6107 SmallVectorImpl<Expr *> &AllArgs,
6108 VariadicCallType CallType, bool AllowExplicit,
6109 bool IsListInitialization) {
6110 unsigned NumParams = Proto->getNumParams();
6111 bool Invalid = false;
6112 size_t ArgIx = 0;
6113 // Continue to check argument types (even if we have too few/many args).
6114 for (unsigned i = FirstParam; i < NumParams; i++) {
6115 QualType ProtoArgType = Proto->getParamType(i);
6116
6117 Expr *Arg;
6118 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6119 if (ArgIx < Args.size()) {
6120 Arg = Args[ArgIx++];
6121
6122 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6123 diag::err_call_incomplete_argument, Arg))
6124 return true;
6125
6126 // Strip the unbridged-cast placeholder expression off, if applicable.
6127 bool CFAudited = false;
6128 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6129 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6130 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6131 Arg = stripARCUnbridgedCast(Arg);
6132 else if (getLangOpts().ObjCAutoRefCount &&
6133 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6134 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6135 CFAudited = true;
6136
6137 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6138 ProtoArgType->isBlockPointerType())
6139 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6140 BE->getBlockDecl()->setDoesNotEscape();
6141
6142 InitializedEntity Entity =
6143 Param ? InitializedEntity::InitializeParameter(Context, Param,
6144 ProtoArgType)
6145 : InitializedEntity::InitializeParameter(
6146 Context, ProtoArgType, Proto->isParamConsumed(i));
6147
6148 // Remember that parameter belongs to a CF audited API.
6149 if (CFAudited)
6150 Entity.setParameterCFAudited();
6151
6152 ExprResult ArgE = PerformCopyInitialization(
6153 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6154 if (ArgE.isInvalid())
6155 return true;
6156
6157 Arg = ArgE.getAs<Expr>();
6158 } else {
6159 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", 6159, __extension__ __PRETTY_FUNCTION__
))
;
6160
6161 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6162 if (ArgExpr.isInvalid())
6163 return true;
6164
6165 Arg = ArgExpr.getAs<Expr>();
6166 }
6167
6168 // Check for array bounds violations for each argument to the call. This
6169 // check only triggers warnings when the argument isn't a more complex Expr
6170 // with its own checking, such as a BinaryOperator.
6171 CheckArrayAccess(Arg);
6172
6173 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6174 CheckStaticArrayArgument(CallLoc, Param, Arg);
6175
6176 AllArgs.push_back(Arg);
6177 }
6178
6179 // If this is a variadic call, handle args passed through "...".
6180 if (CallType != VariadicDoesNotApply) {
6181 // Assume that extern "C" functions with variadic arguments that
6182 // return __unknown_anytype aren't *really* variadic.
6183 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6184 FDecl->isExternC()) {
6185 for (Expr *A : Args.slice(ArgIx)) {
6186 QualType paramType; // ignored
6187 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6188 Invalid |= arg.isInvalid();
6189 AllArgs.push_back(arg.get());
6190 }
6191
6192 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6193 } else {
6194 for (Expr *A : Args.slice(ArgIx)) {
6195 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6196 Invalid |= Arg.isInvalid();
6197 AllArgs.push_back(Arg.get());
6198 }
6199 }
6200
6201 // Check for array bounds violations.
6202 for (Expr *A : Args.slice(ArgIx))
6203 CheckArrayAccess(A);
6204 }
6205 return Invalid;
6206}
6207
6208static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6209 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6210 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6211 TL = DTL.getOriginalLoc();
6212 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6213 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6214 << ATL.getLocalSourceRange();
6215}
6216
6217/// CheckStaticArrayArgument - If the given argument corresponds to a static
6218/// array parameter, check that it is non-null, and that if it is formed by
6219/// array-to-pointer decay, the underlying array is sufficiently large.
6220///
6221/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6222/// array type derivation, then for each call to the function, the value of the
6223/// corresponding actual argument shall provide access to the first element of
6224/// an array with at least as many elements as specified by the size expression.
6225void
6226Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6227 ParmVarDecl *Param,
6228 const Expr *ArgExpr) {
6229 // Static array parameters are not supported in C++.
6230 if (!Param || getLangOpts().CPlusPlus)
6231 return;
6232
6233 QualType OrigTy = Param->getOriginalType();
6234
6235 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6236 if (!AT || AT->getSizeModifier() != ArrayType::Static)
6237 return;
6238
6239 if (ArgExpr->isNullPointerConstant(Context,
6240 Expr::NPC_NeverValueDependent)) {
6241 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6242 DiagnoseCalleeStaticArrayParam(*this, Param);
6243 return;
6244 }
6245
6246 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6247 if (!CAT)
6248 return;
6249
6250 const ConstantArrayType *ArgCAT =
6251 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6252 if (!ArgCAT)
6253 return;
6254
6255 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6256 ArgCAT->getElementType())) {
6257 if (ArgCAT->getSize().ult(CAT->getSize())) {
6258 Diag(CallLoc, diag::warn_static_array_too_small)
6259 << ArgExpr->getSourceRange()
6260 << (unsigned)ArgCAT->getSize().getZExtValue()
6261 << (unsigned)CAT->getSize().getZExtValue() << 0;
6262 DiagnoseCalleeStaticArrayParam(*this, Param);
6263 }
6264 return;
6265 }
6266
6267 Optional<CharUnits> ArgSize =
6268 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6269 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6270 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6271 Diag(CallLoc, diag::warn_static_array_too_small)
6272 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6273 << (unsigned)ParmSize->getQuantity() << 1;
6274 DiagnoseCalleeStaticArrayParam(*this, Param);
6275 }
6276}
6277
6278/// Given a function expression of unknown-any type, try to rebuild it
6279/// to have a function type.
6280static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6281
6282/// Is the given type a placeholder that we need to lower out
6283/// immediately during argument processing?
6284static bool isPlaceholderToRemoveAsArg(QualType type) {
6285 // Placeholders are never sugared.
6286 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6287 if (!placeholder) return false;
6288
6289 switch (placeholder->getKind()) {
6290 // Ignore all the non-placeholder types.
6291#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6292 case BuiltinType::Id:
6293#include "clang/Basic/OpenCLImageTypes.def"
6294#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6295 case BuiltinType::Id:
6296#include "clang/Basic/OpenCLExtensionTypes.def"
6297 // In practice we'll never use this, since all SVE types are sugared
6298 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6299#define SVE_TYPE(Name, Id, SingletonId) \
6300 case BuiltinType::Id:
6301#include "clang/Basic/AArch64SVEACLETypes.def"
6302#define PPC_VECTOR_TYPE(Name, Id, Size) \
6303 case BuiltinType::Id:
6304#include "clang/Basic/PPCTypes.def"
6305#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6306#include "clang/Basic/RISCVVTypes.def"
6307#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6308#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6309#include "clang/AST/BuiltinTypes.def"
6310 return false;
6311
6312 // We cannot lower out overload sets; they might validly be resolved
6313 // by the call machinery.
6314 case BuiltinType::Overload:
6315 return false;
6316
6317 // Unbridged casts in ARC can be handled in some call positions and
6318 // should be left in place.
6319 case BuiltinType::ARCUnbridgedCast:
6320 return false;
6321
6322 // Pseudo-objects should be converted as soon as possible.
6323 case BuiltinType::PseudoObject:
6324 return true;
6325
6326 // The debugger mode could theoretically but currently does not try
6327 // to resolve unknown-typed arguments based on known parameter types.
6328 case BuiltinType::UnknownAny:
6329 return true;
6330
6331 // These are always invalid as call arguments and should be reported.
6332 case BuiltinType::BoundMember:
6333 case BuiltinType::BuiltinFn:
6334 case BuiltinType::IncompleteMatrixIdx:
6335 case BuiltinType::OMPArraySection:
6336 case BuiltinType::OMPArrayShaping:
6337 case BuiltinType::OMPIterator:
6338 return true;
6339
6340 }
6341 llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "clang/lib/Sema/SemaExpr.cpp"
, 6341)
;
6342}
6343
6344/// Check an argument list for placeholders that we won't try to
6345/// handle later.
6346static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6347 // Apply this processing to all the arguments at once instead of
6348 // dying at the first failure.
6349 bool hasInvalid = false;
6350 for (size_t i = 0, e = args.size(); i != e; i++) {
6351 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6352 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6353 if (result.isInvalid()) hasInvalid = true;
6354 else args[i] = result.get();
6355 }
6356 }
6357 return hasInvalid;
6358}
6359
6360/// If a builtin function has a pointer argument with no explicit address
6361/// space, then it should be able to accept a pointer to any address
6362/// space as input. In order to do this, we need to replace the
6363/// standard builtin declaration with one that uses the same address space
6364/// as the call.
6365///
6366/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6367/// it does not contain any pointer arguments without
6368/// an address space qualifer. Otherwise the rewritten
6369/// FunctionDecl is returned.
6370/// TODO: Handle pointer return types.
6371static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6372 FunctionDecl *FDecl,
6373 MultiExprArg ArgExprs) {
6374
6375 QualType DeclType = FDecl->getType();
6376 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6377
6378 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6379 ArgExprs.size() < FT->getNumParams())
6380 return nullptr;
6381
6382 bool NeedsNewDecl = false;
6383 unsigned i = 0;
6384 SmallVector<QualType, 8> OverloadParams;
6385
6386 for (QualType ParamType : FT->param_types()) {
6387
6388 // Convert array arguments to pointer to simplify type lookup.
6389 ExprResult ArgRes =
6390 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6391 if (ArgRes.isInvalid())
6392 return nullptr;
6393 Expr *Arg = ArgRes.get();
6394 QualType ArgType = Arg->getType();
6395 if (!ParamType->isPointerType() ||
6396 ParamType.hasAddressSpace() ||
6397 !ArgType->isPointerType() ||
6398 !ArgType->getPointeeType().hasAddressSpace()) {
6399 OverloadParams.push_back(ParamType);
6400 continue;
6401 }
6402
6403 QualType PointeeType = ParamType->getPointeeType();
6404 if (PointeeType.hasAddressSpace())
6405 continue;
6406
6407 NeedsNewDecl = true;
6408 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6409
6410 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6411 OverloadParams.push_back(Context.getPointerType(PointeeType));
6412 }
6413
6414 if (!NeedsNewDecl)
6415 return nullptr;
6416
6417 FunctionProtoType::ExtProtoInfo EPI;
6418 EPI.Variadic = FT->isVariadic();
6419 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6420 OverloadParams, EPI);
6421 DeclContext *Parent = FDecl->getParent();
6422 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6423 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6424 FDecl->getIdentifier(), OverloadTy,
6425 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6426 false,
6427 /*hasPrototype=*/true);
6428 SmallVector<ParmVarDecl*, 16> Params;
6429 FT = cast<FunctionProtoType>(OverloadTy);
6430 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6431 QualType ParamType = FT->getParamType(i);
6432 ParmVarDecl *Parm =
6433 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6434 SourceLocation(), nullptr, ParamType,
6435 /*TInfo=*/nullptr, SC_None, nullptr);
6436 Parm->setScopeInfo(0, i);
6437 Params.push_back(Parm);
6438 }
6439 OverloadDecl->setParams(Params);
6440 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6441 return OverloadDecl;
6442}
6443
6444static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6445 FunctionDecl *Callee,
6446 MultiExprArg ArgExprs) {
6447 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6448 // similar attributes) really don't like it when functions are called with an
6449 // invalid number of args.
6450 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6451 /*PartialOverloading=*/false) &&
6452 !Callee->isVariadic())
6453 return;
6454 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6455 return;
6456
6457 if (const EnableIfAttr *Attr =
6458 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6459 S.Diag(Fn->getBeginLoc(),
6460 isa<CXXMethodDecl>(Callee)
6461 ? diag::err_ovl_no_viable_member_function_in_call
6462 : diag::err_ovl_no_viable_function_in_call)
6463 << Callee << Callee->getSourceRange();
6464 S.Diag(Callee->getLocation(),
6465 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6466 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6467 return;
6468 }
6469}
6470
6471static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6472 const UnresolvedMemberExpr *const UME, Sema &S) {
6473
6474 const auto GetFunctionLevelDCIfCXXClass =
6475 [](Sema &S) -> const CXXRecordDecl * {
6476 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6477 if (!DC || !DC->getParent())
6478 return nullptr;
6479
6480 // If the call to some member function was made from within a member
6481 // function body 'M' return return 'M's parent.
6482 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6483 return MD->getParent()->getCanonicalDecl();
6484 // else the call was made from within a default member initializer of a
6485 // class, so return the class.
6486 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6487 return RD->getCanonicalDecl();
6488 return nullptr;
6489 };
6490 // If our DeclContext is neither a member function nor a class (in the
6491 // case of a lambda in a default member initializer), we can't have an
6492 // enclosing 'this'.
6493
6494 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6495 if (!CurParentClass)
6496 return false;
6497
6498 // The naming class for implicit member functions call is the class in which
6499 // name lookup starts.
6500 const CXXRecordDecl *const NamingClass =
6501 UME->getNamingClass()->getCanonicalDecl();
6502 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", 6502, __extension__ __PRETTY_FUNCTION__
))
;
6503
6504 // If the unresolved member functions were found in a 'naming class' that is
6505 // related (either the same or derived from) to the class that contains the
6506 // member function that itself contained the implicit member access.
6507
6508 return CurParentClass == NamingClass ||
6509 CurParentClass->isDerivedFrom(NamingClass);
6510}
6511
6512static void
6513tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6514 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6515
6516 if (!UME)
6517 return;
6518
6519 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6520 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6521 // already been captured, or if this is an implicit member function call (if
6522 // it isn't, an attempt to capture 'this' should already have been made).
6523 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6524 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6525 return;
6526
6527 // Check if the naming class in which the unresolved members were found is
6528 // related (same as or is a base of) to the enclosing class.
6529
6530 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6531 return;
6532
6533
6534 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6535 // If the enclosing function is not dependent, then this lambda is
6536 // capture ready, so if we can capture this, do so.
6537 if (!EnclosingFunctionCtx->isDependentContext()) {
6538 // If the current lambda and all enclosing lambdas can capture 'this' -
6539 // then go ahead and capture 'this' (since our unresolved overload set
6540 // contains at least one non-static member function).
6541 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6542 S.CheckCXXThisCapture(CallLoc);
6543 } else if (S.CurContext->isDependentContext()) {
6544 // ... since this is an implicit member reference, that might potentially
6545 // involve a 'this' capture, mark 'this' for potential capture in
6546 // enclosing lambdas.
6547 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6548 CurLSI->addPotentialThisCapture(CallLoc);
6549 }
6550}
6551
6552// Once a call is fully resolved, warn for unqualified calls to specific
6553// C++ standard functions, like move and forward.
6554static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6555 // We are only checking unary move and forward so exit early here.
6556 if (Call->getNumArgs() != 1)
6557 return;
6558
6559 Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6560 if (!E || isa<UnresolvedLookupExpr>(E))
6561 return;
6562 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6563 if (!DRE || !DRE->getLocation().isValid())
6564 return;
6565
6566 if (DRE->getQualifier())
6567 return;
6568
6569 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Call->getCalleeDecl());
6570 if (!D || !D->isInStdNamespace())
6571 return;
6572
6573 // Only warn for some functions deemed more frequent or problematic.
6574 static constexpr llvm::StringRef SpecialFunctions[] = {"move", "forward"};
6575 auto it = llvm::find(SpecialFunctions, D->getName());
6576 if (it == std::end(SpecialFunctions))
6577 return;
6578
6579 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6580 << D->getQualifiedNameAsString()
6581 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6582}
6583
6584ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6585 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6586 Expr *ExecConfig) {
6587 ExprResult Call =
6588 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6589 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6590 if (Call.isInvalid())
6591 return Call;
6592
6593 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6594 // language modes.
6595 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6596 if (ULE->hasExplicitTemplateArgs() &&
6597 ULE->decls_begin() == ULE->decls_end()) {
6598 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6599 ? diag::warn_cxx17_compat_adl_only_template_id
6600 : diag::ext_adl_only_template_id)
6601 << ULE->getName();
6602 }
6603 }
6604
6605 if (LangOpts.OpenMP)
6606 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6607 ExecConfig);
6608 if (LangOpts.CPlusPlus) {
6609 CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6610 if (CE)
6611 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6612 }
6613 return Call;
6614}
6615
6616/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6617/// This provides the location of the left/right parens and a list of comma
6618/// locations.
6619ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6620 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6621 Expr *ExecConfig, bool IsExecConfig,
6622 bool AllowRecovery) {
6623 // Since this might be a postfix expression, get rid of ParenListExprs.
6624 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6625 if (Result.isInvalid()) return ExprError();
6626 Fn = Result.get();
6627
6628 if (checkArgsForPlaceholders(*this, ArgExprs))
6629 return ExprError();
6630
6631 if (getLangOpts().CPlusPlus) {
6632 // If this is a pseudo-destructor expression, build the call immediately.
6633 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6634 if (!ArgExprs.empty()) {
6635 // Pseudo-destructor calls should not have any arguments.
6636 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6637 << FixItHint::CreateRemoval(
6638 SourceRange(ArgExprs.front()->getBeginLoc(),
6639 ArgExprs.back()->getEndLoc()));
6640 }
6641
6642 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6643 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6644 }
6645 if (Fn->getType() == Context.PseudoObjectTy) {
6646 ExprResult result = CheckPlaceholderExpr(Fn);
6647 if (result.isInvalid()) return ExprError();
6648 Fn = result.get();
6649 }
6650
6651 // Determine whether this is a dependent call inside a C++ template,
6652 // in which case we won't do any semantic analysis now.
6653 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6654 if (ExecConfig) {
6655 return CUDAKernelCallExpr::Create(Context, Fn,
6656 cast<CallExpr>(ExecConfig), ArgExprs,
6657 Context.DependentTy, VK_PRValue,
6658 RParenLoc, CurFPFeatureOverrides());
6659 } else {
6660
6661 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6662 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6663 Fn->getBeginLoc());
6664
6665 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6666 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6667 }
6668 }
6669
6670 // Determine whether this is a call to an object (C++ [over.call.object]).
6671 if (Fn->getType()->isRecordType())
6672 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6673 RParenLoc);
6674
6675 if (Fn->getType() == Context.UnknownAnyTy) {
6676 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6677 if (result.isInvalid()) return ExprError();
6678 Fn = result.get();
6679 }
6680
6681 if (Fn->getType() == Context.BoundMemberTy) {
6682 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6683 RParenLoc, ExecConfig, IsExecConfig,
6684 AllowRecovery);
6685 }
6686 }
6687
6688 // Check for overloaded calls. This can happen even in C due to extensions.
6689 if (Fn->getType() == Context.OverloadTy) {
6690 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6691
6692 // We aren't supposed to apply this logic if there's an '&' involved.
6693 if (!find.HasFormOfMemberPointer) {
6694 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6695 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6696 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6697 OverloadExpr *ovl = find.Expression;
6698 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6699 return BuildOverloadedCallExpr(
6700 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6701 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6702 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6703 RParenLoc, ExecConfig, IsExecConfig,
6704 AllowRecovery);
6705 }
6706 }
6707
6708 // If we're directly calling a function, get the appropriate declaration.
6709 if (Fn->getType() == Context.UnknownAnyTy) {
6710 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6711 if (result.isInvalid()) return ExprError();
6712 Fn = result.get();
6713 }
6714
6715 Expr *NakedFn = Fn->IgnoreParens();
6716
6717 bool CallingNDeclIndirectly = false;
6718 NamedDecl *NDecl = nullptr;
6719 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6720 if (UnOp->getOpcode() == UO_AddrOf) {
6721 CallingNDeclIndirectly = true;
6722 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6723 }
6724 }
6725
6726 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6727 NDecl = DRE->getDecl();
6728
6729 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6730 if (FDecl && FDecl->getBuiltinID()) {
6731 // Rewrite the function decl for this builtin by replacing parameters
6732 // with no explicit address space with the address space of the arguments
6733 // in ArgExprs.
6734 if ((FDecl =
6735 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6736 NDecl = FDecl;
6737 Fn = DeclRefExpr::Create(
6738 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6739 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6740 nullptr, DRE->isNonOdrUse());
6741 }
6742 }
6743 } else if (isa<MemberExpr>(NakedFn))
6744 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6745
6746 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6747 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6748 FD, /*Complain=*/true, Fn->getBeginLoc()))
6749 return ExprError();
6750
6751 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6752
6753 // If this expression is a call to a builtin function in HIP device
6754 // compilation, allow a pointer-type argument to default address space to be
6755 // passed as a pointer-type parameter to a non-default address space.
6756 // If Arg is declared in the default address space and Param is declared
6757 // in a non-default address space, perform an implicit address space cast to
6758 // the parameter type.
6759 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6760 FD->getBuiltinID()) {
6761 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6762 ParmVarDecl *Param = FD->getParamDecl(Idx);
6763 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6764 !ArgExprs[Idx]->getType()->isPointerType())
6765 continue;
6766
6767 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6768 auto ArgTy = ArgExprs[Idx]->getType();
6769 auto ArgPtTy = ArgTy->getPointeeType();
6770 auto ArgAS = ArgPtTy.getAddressSpace();
6771
6772 // Add address space cast if target address spaces are different
6773 bool NeedImplicitASC =
6774 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6775 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6776 // or from specific AS which has target AS matching that of Param.
6777 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6778 if (!NeedImplicitASC)
6779 continue;
6780
6781 // First, ensure that the Arg is an RValue.
6782 if (ArgExprs[Idx]->isGLValue()) {
6783 ArgExprs[Idx] = ImplicitCastExpr::Create(
6784 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6785 nullptr, VK_PRValue, FPOptionsOverride());
6786 }
6787
6788 // Construct a new arg type with address space of Param
6789 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6790 ArgPtQuals.setAddressSpace(ParamAS);
6791 auto NewArgPtTy =
6792 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6793 auto NewArgTy =
6794 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6795 ArgTy.getQualifiers());
6796
6797 // Finally perform an implicit address space cast
6798 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6799 CK_AddressSpaceConversion)
6800 .get();
6801 }
6802 }
6803 }
6804
6805 if (Context.isDependenceAllowed() &&
6806 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6807 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 6807, __extension__ __PRETTY_FUNCTION__))
;
6808 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", 6811, __extension__ __PRETTY_FUNCTION__
))
6809 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", 6811, __extension__ __PRETTY_FUNCTION__
))
6810 [](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", 6811, __extension__ __PRETTY_FUNCTION__
))
6811 "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", 6811, __extension__ __PRETTY_FUNCTION__
))
;
6812 QualType ReturnType =
6813 llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6814 ? cast<FunctionDecl>(NDecl)->getCallResultType()
6815 : Context.DependentTy;
6816 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6817 Expr::getValueKindForType(ReturnType), RParenLoc,
6818 CurFPFeatureOverrides());
6819 }
6820 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6821 ExecConfig, IsExecConfig);
6822}
6823
6824/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6825// with the specified CallArgs
6826Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6827 MultiExprArg CallArgs) {
6828 StringRef Name = Context.BuiltinInfo.getName(Id);
6829 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6830 Sema::LookupOrdinaryName);
6831 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6832
6833 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6834 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", 6834, __extension__ __PRETTY_FUNCTION__
))
;
6835
6836 ExprResult DeclRef =
6837 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6838 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", 6838, __extension__ __PRETTY_FUNCTION__
))
;
6839
6840 ExprResult Call =
6841 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6842
6843 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", 6843, __extension__ __PRETTY_FUNCTION__
))
;
6844 return Call.get();
6845}
6846
6847/// Parse a __builtin_astype expression.
6848///
6849/// __builtin_astype( value, dst type )
6850///
6851ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6852 SourceLocation BuiltinLoc,
6853 SourceLocation RParenLoc) {
6854 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6855 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6856}
6857
6858/// Create a new AsTypeExpr node (bitcast) from the arguments.
6859ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6860 SourceLocation BuiltinLoc,
6861 SourceLocation RParenLoc) {
6862 ExprValueKind VK = VK_PRValue;
6863 ExprObjectKind OK = OK_Ordinary;
6864 QualType SrcTy = E->getType();
6865 if (!SrcTy->isDependentType() &&
6866 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6867 return ExprError(
6868 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6869 << DestTy << SrcTy << E->getSourceRange());
6870 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6871}
6872
6873/// ActOnConvertVectorExpr - create a new convert-vector expression from the
6874/// provided arguments.
6875///
6876/// __builtin_convertvector( value, dst type )
6877///
6878ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6879 SourceLocation BuiltinLoc,
6880 SourceLocation RParenLoc) {
6881 TypeSourceInfo *TInfo;
6882 GetTypeFromParser(ParsedDestTy, &TInfo);
6883 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6884}
6885
6886/// BuildResolvedCallExpr - Build a call to a resolved expression,
6887/// i.e. an expression not of \p OverloadTy. The expression should
6888/// unary-convert to an expression of function-pointer or
6889/// block-pointer type.
6890///
6891/// \param NDecl the declaration being called, if available
6892ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6893 SourceLocation LParenLoc,
6894 ArrayRef<Expr *> Args,
6895 SourceLocation RParenLoc, Expr *Config,
6896 bool IsExecConfig, ADLCallKind UsesADL) {
6897 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6898 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6899
6900 // Functions with 'interrupt' attribute cannot be called directly.
6901 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6902 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6903 return ExprError();
6904 }
6905
6906 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6907 // so there's some risk when calling out to non-interrupt handler functions
6908 // that the callee might not preserve them. This is easy to diagnose here,
6909 // but can be very challenging to debug.
6910 // Likewise, X86 interrupt handlers may only call routines with attribute
6911 // no_caller_saved_registers since there is no efficient way to
6912 // save and restore the non-GPR state.
6913 if (auto *Caller = getCurFunctionDecl()) {
6914 if (Caller->hasAttr<ARMInterruptAttr>()) {
6915 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6916 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6917 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6918 if (FDecl)
6919 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6920 }
6921 }
6922 if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6923 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6924 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6925 if (FDecl)
6926 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6927 }
6928 }
6929
6930 // Promote the function operand.
6931 // We special-case function promotion here because we only allow promoting
6932 // builtin functions to function pointers in the callee of a call.
6933 ExprResult Result;
6934 QualType ResultTy;
6935 if (BuiltinID &&
6936 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6937 // Extract the return type from the (builtin) function pointer type.
6938 // FIXME Several builtins still have setType in
6939 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6940 // Builtins.def to ensure they are correct before removing setType calls.
6941 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6942 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6943 ResultTy = FDecl->getCallResultType();
6944 } else {
6945 Result = CallExprUnaryConversions(Fn);
6946 ResultTy = Context.BoolTy;
6947 }
6948 if (Result.isInvalid())
6949 return ExprError();
6950 Fn = Result.get();
6951
6952 // Check for a valid function type, but only if it is not a builtin which
6953 // requires custom type checking. These will be handled by
6954 // CheckBuiltinFunctionCall below just after creation of the call expression.
6955 const FunctionType *FuncT = nullptr;
6956 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6957 retry:
6958 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6959 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6960 // have type pointer to function".
6961 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6962 if (!FuncT)
6963 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6964 << Fn->getType() << Fn->getSourceRange());
6965 } else if (const BlockPointerType *BPT =
6966 Fn->getType()->getAs<BlockPointerType>()) {
6967 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6968 } else {
6969 // Handle calls to expressions of unknown-any type.
6970 if (Fn->getType() == Context.UnknownAnyTy) {
6971 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6972 if (rewrite.isInvalid())
6973 return ExprError();
6974 Fn = rewrite.get();
6975 goto retry;
6976 }
6977
6978 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6979 << Fn->getType() << Fn->getSourceRange());
6980 }
6981 }
6982
6983 // Get the number of parameters in the function prototype, if any.
6984 // We will allocate space for max(Args.size(), NumParams) arguments
6985 // in the call expression.
6986 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6987 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6988
6989 CallExpr *TheCall;
6990 if (Config) {
6991 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", 6992, __extension__ __PRETTY_FUNCTION__
))
6992 "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", 6992, __extension__ __PRETTY_FUNCTION__
))
;
6993 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6994 Args, ResultTy, VK_PRValue, RParenLoc,
6995 CurFPFeatureOverrides(), NumParams);
6996 } else {
6997 TheCall =
6998 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6999 CurFPFeatureOverrides(), NumParams, UsesADL);
7000 }
7001
7002 if (!Context.isDependenceAllowed()) {
7003 // Forget about the nulled arguments since typo correction
7004 // do not handle them well.
7005 TheCall->shrinkNumArgs(Args.size());
7006 // C cannot always handle TypoExpr nodes in builtin calls and direct
7007 // function calls as their argument checking don't necessarily handle
7008 // dependent types properly, so make sure any TypoExprs have been
7009 // dealt with.
7010 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7011 if (!Result.isUsable()) return ExprError();
7012 CallExpr *TheOldCall = TheCall;
7013 TheCall = dyn_cast<CallExpr>(Result.get());
7014 bool CorrectedTypos = TheCall != TheOldCall;
7015 if (!TheCall) return Result;
7016 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7017
7018 // A new call expression node was created if some typos were corrected.
7019 // However it may not have been constructed with enough storage. In this
7020 // case, rebuild the node with enough storage. The waste of space is
7021 // immaterial since this only happens when some typos were corrected.
7022 if (CorrectedTypos && Args.size() < NumParams) {
7023 if (Config)
7024 TheCall = CUDAKernelCallExpr::Create(
7025 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7026 RParenLoc, CurFPFeatureOverrides(), NumParams);
7027 else
7028 TheCall =
7029 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7030 CurFPFeatureOverrides(), NumParams, UsesADL);
7031 }
7032 // We can now handle the nulled arguments for the default arguments.
7033 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7034 }
7035
7036 // Bail out early if calling a builtin with custom type checking.
7037 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7038 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7039
7040 if (getLangOpts().CUDA) {
7041 if (Config) {
7042 // CUDA: Kernel calls must be to global functions
7043 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7044 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7045 << FDecl << Fn->getSourceRange());
7046
7047 // CUDA: Kernel function must have 'void' return type
7048 if (!FuncT->getReturnType()->isVoidType() &&
7049 !FuncT->getReturnType()->getAs<AutoType>() &&
7050 !FuncT->getReturnType()->isInstantiationDependentType())
7051 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7052 << Fn->getType() << Fn->getSourceRange());
7053 } else {
7054 // CUDA: Calls to global functions must be configured
7055 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7056 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7057 << FDecl << Fn->getSourceRange());
7058 }
7059 }
7060
7061 // Check for a valid return type
7062 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7063 FDecl))
7064 return ExprError();
7065
7066 // We know the result type of the call, set it.
7067 TheCall->setType(FuncT->getCallResultType(Context));
7068 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7069
7070 if (Proto) {
7071 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7072 IsExecConfig))
7073 return ExprError();
7074 } else {
7075 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", 7075, __extension__ __PRETTY_FUNCTION__
))
;
7076
7077 if (FDecl) {
7078 // Check if we have too few/too many template arguments, based
7079 // on our knowledge of the function definition.
7080 const FunctionDecl *Def = nullptr;
7081 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7082 Proto = Def->getType()->getAs<FunctionProtoType>();
7083 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7084 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7085 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7086 }
7087
7088 // If the function we're calling isn't a function prototype, but we have
7089 // a function prototype from a prior declaratiom, use that prototype.
7090 if (!FDecl->hasPrototype())
7091 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7092 }
7093
7094 // If we still haven't found a prototype to use but there are arguments to
7095 // the call, diagnose this as calling a function without a prototype.
7096 // However, if we found a function declaration, check to see if
7097 // -Wdeprecated-non-prototype was disabled where the function was declared.
7098 // If so, we will silence the diagnostic here on the assumption that this
7099 // interface is intentional and the user knows what they're doing. We will
7100 // also silence the diagnostic if there is a function declaration but it
7101 // was implicitly defined (the user already gets diagnostics about the
7102 // creation of the implicit function declaration, so the additional warning
7103 // is not helpful).
7104 if (!Proto && !Args.empty() &&
7105 (!FDecl || (!FDecl->isImplicit() &&
7106 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7107 FDecl->getLocation()))))
7108 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7109 << (FDecl != nullptr) << FDecl;
7110
7111 // Promote the arguments (C99 6.5.2.2p6).
7112 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7113 Expr *Arg = Args[i];
7114
7115 if (Proto && i < Proto->getNumParams()) {
7116 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7117 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7118 ExprResult ArgE =
7119 PerformCopyInitialization(Entity, SourceLocation(), Arg);
7120 if (ArgE.isInvalid())
7121 return true;
7122
7123 Arg = ArgE.getAs<Expr>();
7124
7125 } else {
7126 ExprResult ArgE = DefaultArgumentPromotion(Arg);
7127
7128 if (ArgE.isInvalid())
7129 return true;
7130
7131 Arg = ArgE.getAs<Expr>();
7132 }
7133
7134 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7135 diag::err_call_incomplete_argument, Arg))
7136 return ExprError();
7137
7138 TheCall->setArg(i, Arg);
7139 }
7140 TheCall->computeDependence();
7141 }
7142
7143 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7144 if (!Method->isStatic())
7145 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7146 << Fn->getSourceRange());
7147
7148 // Check for sentinels
7149 if (NDecl)
7150 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7151
7152 // Warn for unions passing across security boundary (CMSE).
7153 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7154 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7155 if (const auto *RT =
7156 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7157 if (RT->getDecl()->isOrContainsUnion())
7158 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7159 << 0 << i;
7160 }
7161 }
7162 }
7163
7164 // Do special checking on direct calls to functions.
7165 if (FDecl) {
7166 if (CheckFunctionCall(FDecl, TheCall, Proto))
7167 return ExprError();
7168
7169 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7170
7171 if (BuiltinID)
7172 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7173 } else if (NDecl) {
7174 if (CheckPointerCall(NDecl, TheCall, Proto))
7175 return ExprError();
7176 } else {
7177 if (CheckOtherCall(TheCall, Proto))
7178 return ExprError();
7179 }
7180
7181 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7182}
7183
7184ExprResult
7185Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7186 SourceLocation RParenLoc, Expr *InitExpr) {
7187 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", 7187, __extension__ __PRETTY_FUNCTION__
))
;
7188 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", 7188, __extension__ __PRETTY_FUNCTION__
))
;
7189
7190 TypeSourceInfo *TInfo;
7191 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7192 if (!TInfo)
7193 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7194
7195 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7196}
7197
7198ExprResult
7199Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7200 SourceLocation RParenLoc, Expr *LiteralExpr) {
7201 QualType literalType = TInfo->getType();
7202
7203 if (literalType->isArrayType()) {
7204 if (RequireCompleteSizedType(
7205 LParenLoc, Context.getBaseElementType(literalType),
7206 diag::err_array_incomplete_or_sizeless_type,
7207 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7208 return ExprError();
7209 if (literalType->isVariableArrayType()) {
7210 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7211 diag::err_variable_object_no_init)) {
7212 return ExprError();
7213 }
7214 }
7215 } else if (!literalType->isDependentType() &&
7216 RequireCompleteType(LParenLoc, literalType,
7217 diag::err_typecheck_decl_incomplete_type,
7218 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7219 return ExprError();
7220
7221 InitializedEntity Entity
7222 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7223 InitializationKind Kind
7224 = InitializationKind::CreateCStyleCast(LParenLoc,
7225 SourceRange(LParenLoc, RParenLoc),
7226 /*InitList=*/true);
7227 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7228 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7229 &literalType);
7230 if (Result.isInvalid())
7231 return ExprError();
7232 LiteralExpr = Result.get();
7233
7234 bool isFileScope = !CurContext->isFunctionOrMethod();
7235
7236 // In C, compound literals are l-values for some reason.
7237 // For GCC compatibility, in C++, file-scope array compound literals with
7238 // constant initializers are also l-values, and compound literals are
7239 // otherwise prvalues.
7240 //
7241 // (GCC also treats C++ list-initialized file-scope array prvalues with
7242 // constant initializers as l-values, but that's non-conforming, so we don't
7243 // follow it there.)
7244 //
7245 // FIXME: It would be better to handle the lvalue cases as materializing and
7246 // lifetime-extending a temporary object, but our materialized temporaries
7247 // representation only supports lifetime extension from a variable, not "out
7248 // of thin air".
7249 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7250 // is bound to the result of applying array-to-pointer decay to the compound
7251 // literal.
7252 // FIXME: GCC supports compound literals of reference type, which should
7253 // obviously have a value kind derived from the kind of reference involved.
7254 ExprValueKind VK =
7255 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7256 ? VK_PRValue
7257 : VK_LValue;
7258
7259 if (isFileScope)
7260 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7261 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7262 Expr *Init = ILE->getInit(i);
7263 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7264 }
7265
7266 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7267 VK, LiteralExpr, isFileScope);
7268 if (isFileScope) {
7269 if (!LiteralExpr->isTypeDependent() &&
7270 !LiteralExpr->isValueDependent() &&
7271 !literalType->isDependentType()) // C99 6.5.2.5p3
7272 if (CheckForConstantInitializer(LiteralExpr, literalType))
7273 return ExprError();
7274 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7275 literalType.getAddressSpace() != LangAS::Default) {
7276 // Embedded-C extensions to C99 6.5.2.5:
7277 // "If the compound literal occurs inside the body of a function, the
7278 // type name shall not be qualified by an address-space qualifier."
7279 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7280 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7281 return ExprError();
7282 }
7283
7284 if (!isFileScope && !getLangOpts().CPlusPlus) {
7285 // Compound literals that have automatic storage duration are destroyed at
7286 // the end of the scope in C; in C++, they're just temporaries.
7287
7288 // Emit diagnostics if it is or contains a C union type that is non-trivial
7289 // to destruct.
7290 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7291 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7292 NTCUC_CompoundLiteral, NTCUK_Destruct);
7293
7294 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7295 if (literalType.isDestructedType()) {
7296 Cleanup.setExprNeedsCleanups(true);
7297 ExprCleanupObjects.push_back(E);
7298 getCurFunction()->setHasBranchProtectedScope();
7299 }
7300 }
7301
7302 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7303 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7304 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7305 E->getInitializer()->getExprLoc());
7306
7307 return MaybeBindToTemporary(E);
7308}
7309
7310ExprResult
7311Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7312 SourceLocation RBraceLoc) {
7313 // Only produce each kind of designated initialization diagnostic once.
7314 SourceLocation FirstDesignator;
7315 bool DiagnosedArrayDesignator = false;
7316 bool DiagnosedNestedDesignator = false;
7317 bool DiagnosedMixedDesignator = false;
7318
7319 // Check that any designated initializers are syntactically valid in the
7320 // current language mode.
7321 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7322 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7323 if (FirstDesignator.isInvalid())
7324 FirstDesignator = DIE->getBeginLoc();
7325
7326 if (!getLangOpts().CPlusPlus)
7327 break;
7328
7329 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7330 DiagnosedNestedDesignator = true;
7331 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7332 << DIE->getDesignatorsSourceRange();
7333 }
7334
7335 for (auto &Desig : DIE->designators()) {
7336 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7337 DiagnosedArrayDesignator = true;
7338 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7339 << Desig.getSourceRange();
7340 }
7341 }
7342
7343 if (!DiagnosedMixedDesignator &&
7344 !isa<DesignatedInitExpr>(InitArgList[0])) {
7345 DiagnosedMixedDesignator = true;
7346 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7347 << DIE->getSourceRange();
7348 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7349 << InitArgList[0]->getSourceRange();
7350 }
7351 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7352 isa<DesignatedInitExpr>(InitArgList[0])) {
7353 DiagnosedMixedDesignator = true;
7354 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7355 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7356 << DIE->getSourceRange();
7357 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7358 << InitArgList[I]->getSourceRange();
7359 }
7360 }
7361
7362 if (FirstDesignator.isValid()) {
7363 // Only diagnose designated initiaization as a C++20 extension if we didn't
7364 // already diagnose use of (non-C++20) C99 designator syntax.
7365 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7366 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7367 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7368 ? diag::warn_cxx17_compat_designated_init
7369 : diag::ext_cxx_designated_init);
7370 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7371 Diag(FirstDesignator, diag::ext_designated_init);
7372 }
7373 }
7374
7375 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7376}
7377
7378ExprResult
7379Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7380 SourceLocation RBraceLoc) {
7381 // Semantic analysis for initializers is done by ActOnDeclarator() and
7382 // CheckInitializer() - it requires knowledge of the object being initialized.
7383
7384 // Immediately handle non-overload placeholders. Overloads can be
7385 // resolved contextually, but everything else here can't.
7386 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7387 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7388 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7389
7390 // Ignore failures; dropping the entire initializer list because
7391 // of one failure would be terrible for indexing/etc.
7392 if (result.isInvalid()) continue;
7393
7394 InitArgList[I] = result.get();
7395 }
7396 }
7397
7398 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7399 RBraceLoc);
7400 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7401 return E;
7402}
7403
7404/// Do an explicit extend of the given block pointer if we're in ARC.
7405void Sema::maybeExtendBlockObject(ExprResult &E) {
7406 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", 7406, __extension__ __PRETTY_FUNCTION__
))
;
7407 assert(E.get()->isPRValue())(static_cast <bool> (E.get()->isPRValue()) ? void (0
) : __assert_fail ("E.get()->isPRValue()", "clang/lib/Sema/SemaExpr.cpp"
, 7407, __extension__ __PRETTY_FUNCTION__))
;
7408
7409 // Only do this in an r-value context.
7410 if (!getLangOpts().ObjCAutoRefCount) return;
7411
7412 E = ImplicitCastExpr::Create(
7413 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7414 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7415 Cleanup.setExprNeedsCleanups(true);
7416}
7417
7418/// Prepare a conversion of the given expression to an ObjC object
7419/// pointer type.
7420CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7421 QualType type = E.get()->getType();
7422 if (type->isObjCObjectPointerType()) {
7423 return CK_BitCast;
7424 } else if (type->isBlockPointerType()) {
7425 maybeExtendBlockObject(E);
7426 return CK_BlockPointerToObjCPointerCast;
7427 } else {
7428 assert(type->isPointerType())(static_cast <bool> (type->isPointerType()) ? void (
0) : __assert_fail ("type->isPointerType()", "clang/lib/Sema/SemaExpr.cpp"
, 7428, __extension__ __PRETTY_FUNCTION__))
;
7429 return CK_CPointerToObjCPointerCast;
7430 }
7431}
7432
7433/// Prepares for a scalar cast, performing all the necessary stages
7434/// except the final cast and returning the kind required.
7435CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7436 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7437 // Also, callers should have filtered out the invalid cases with
7438 // pointers. Everything else should be possible.
7439
7440 QualType SrcTy = Src.get()->getType();
7441 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7442 return CK_NoOp;
7443
7444 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7445 case Type::STK_MemberPointer:
7446 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7446)
;
7447
7448 case Type::STK_CPointer:
7449 case Type::STK_BlockPointer:
7450 case Type::STK_ObjCObjectPointer:
7451 switch (DestTy->getScalarTypeKind()) {
7452 case Type::STK_CPointer: {
7453 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7454 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7455 if (SrcAS != DestAS)
7456 return CK_AddressSpaceConversion;
7457 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7458 return CK_NoOp;
7459 return CK_BitCast;
7460 }
7461 case Type::STK_BlockPointer:
7462 return (SrcKind == Type::STK_BlockPointer
7463 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7464 case Type::STK_ObjCObjectPointer:
7465 if (SrcKind == Type::STK_ObjCObjectPointer)
7466 return CK_BitCast;
7467 if (SrcKind == Type::STK_CPointer)
7468 return CK_CPointerToObjCPointerCast;
7469 maybeExtendBlockObject(Src);
7470 return CK_BlockPointerToObjCPointerCast;
7471 case Type::STK_Bool:
7472 return CK_PointerToBoolean;
7473 case Type::STK_Integral:
7474 return CK_PointerToIntegral;
7475 case Type::STK_Floating:
7476 case Type::STK_FloatingComplex:
7477 case Type::STK_IntegralComplex:
7478 case Type::STK_MemberPointer:
7479 case Type::STK_FixedPoint:
7480 llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer"
, "clang/lib/Sema/SemaExpr.cpp", 7480)
;
7481 }
7482 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7482)
;
7483
7484 case Type::STK_FixedPoint:
7485 switch (DestTy->getScalarTypeKind()) {
7486 case Type::STK_FixedPoint:
7487 return CK_FixedPointCast;
7488 case Type::STK_Bool:
7489 return CK_FixedPointToBoolean;
7490 case Type::STK_Integral:
7491 return CK_FixedPointToIntegral;
7492 case Type::STK_Floating:
7493 return CK_FixedPointToFloating;
7494 case Type::STK_IntegralComplex:
7495 case Type::STK_FloatingComplex:
7496 Diag(Src.get()->getExprLoc(),
7497 diag::err_unimplemented_conversion_with_fixed_point_type)
7498 << DestTy;
7499 return CK_IntegralCast;
7500 case Type::STK_CPointer:
7501 case Type::STK_ObjCObjectPointer:
7502 case Type::STK_BlockPointer:
7503 case Type::STK_MemberPointer:
7504 llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type"
, "clang/lib/Sema/SemaExpr.cpp", 7504)
;
7505 }
7506 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7506)
;
7507
7508 case Type::STK_Bool: // casting from bool is like casting from an integer
7509 case Type::STK_Integral:
7510 switch (DestTy->getScalarTypeKind()) {
7511 case Type::STK_CPointer:
7512 case Type::STK_ObjCObjectPointer:
7513 case Type::STK_BlockPointer:
7514 if (Src.get()->isNullPointerConstant(Context,
7515 Expr::NPC_ValueDependentIsNull))
7516 return CK_NullToPointer;
7517 return CK_IntegralToPointer;
7518 case Type::STK_Bool:
7519 return CK_IntegralToBoolean;
7520 case Type::STK_Integral:
7521 return CK_IntegralCast;
7522 case Type::STK_Floating:
7523 return CK_IntegralToFloating;
7524 case Type::STK_IntegralComplex:
7525 Src = ImpCastExprToType(Src.get(),
7526 DestTy->castAs<ComplexType>()->getElementType(),
7527 CK_IntegralCast);
7528 return CK_IntegralRealToComplex;
7529 case Type::STK_FloatingComplex:
7530 Src = ImpCastExprToType(Src.get(),
7531 DestTy->castAs<ComplexType>()->getElementType(),
7532 CK_IntegralToFloating);
7533 return CK_FloatingRealToComplex;
7534 case Type::STK_MemberPointer:
7535 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7535)
;
7536 case Type::STK_FixedPoint:
7537 return CK_IntegralToFixedPoint;
7538 }
7539 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7539)
;
7540
7541 case Type::STK_Floating:
7542 switch (DestTy->getScalarTypeKind()) {
7543 case Type::STK_Floating:
7544 return CK_FloatingCast;
7545 case Type::STK_Bool:
7546 return CK_FloatingToBoolean;
7547 case Type::STK_Integral:
7548 return CK_FloatingToIntegral;
7549 case Type::STK_FloatingComplex:
7550 Src = ImpCastExprToType(Src.get(),
7551 DestTy->castAs<ComplexType>()->getElementType(),
7552 CK_FloatingCast);
7553 return CK_FloatingRealToComplex;
7554 case Type::STK_IntegralComplex:
7555 Src = ImpCastExprToType(Src.get(),
7556 DestTy->castAs<ComplexType>()->getElementType(),
7557 CK_FloatingToIntegral);
7558 return CK_IntegralRealToComplex;
7559 case Type::STK_CPointer:
7560 case Type::STK_ObjCObjectPointer:
7561 case Type::STK_BlockPointer:
7562 llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7562)
;
7563 case Type::STK_MemberPointer:
7564 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7564)
;
7565 case Type::STK_FixedPoint:
7566 return CK_FloatingToFixedPoint;
7567 }
7568 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7568)
;
7569
7570 case Type::STK_FloatingComplex:
7571 switch (DestTy->getScalarTypeKind()) {
7572 case Type::STK_FloatingComplex:
7573 return CK_FloatingComplexCast;
7574 case Type::STK_IntegralComplex:
7575 return CK_FloatingComplexToIntegralComplex;
7576 case Type::STK_Floating: {
7577 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7578 if (Context.hasSameType(ET, DestTy))
7579 return CK_FloatingComplexToReal;
7580 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7581 return CK_FloatingCast;
7582 }
7583 case Type::STK_Bool:
7584 return CK_FloatingComplexToBoolean;
7585 case Type::STK_Integral:
7586 Src = ImpCastExprToType(Src.get(),
7587 SrcTy->castAs<ComplexType>()->getElementType(),
7588 CK_FloatingComplexToReal);
7589 return CK_FloatingToIntegral;
7590 case Type::STK_CPointer:
7591 case Type::STK_ObjCObjectPointer:
7592 case Type::STK_BlockPointer:
7593 llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7593)
;
7594 case Type::STK_MemberPointer:
7595 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7595)
;
7596 case Type::STK_FixedPoint:
7597 Diag(Src.get()->getExprLoc(),
7598 diag::err_unimplemented_conversion_with_fixed_point_type)
7599 << SrcTy;
7600 return CK_IntegralCast;
7601 }
7602 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7602)
;
7603
7604 case Type::STK_IntegralComplex:
7605 switch (DestTy->getScalarTypeKind()) {
7606 case Type::STK_FloatingComplex:
7607 return CK_IntegralComplexToFloatingComplex;
7608 case Type::STK_IntegralComplex:
7609 return CK_IntegralComplexCast;
7610 case Type::STK_Integral: {
7611 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7612 if (Context.hasSameType(ET, DestTy))
7613 return CK_IntegralComplexToReal;
7614 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7615 return CK_IntegralCast;
7616 }
7617 case Type::STK_Bool:
7618 return CK_IntegralComplexToBoolean;
7619 case Type::STK_Floating:
7620 Src = ImpCastExprToType(Src.get(),
7621 SrcTy->castAs<ComplexType>()->getElementType(),
7622 CK_IntegralComplexToReal);
7623 return CK_IntegralToFloating;
7624 case Type::STK_CPointer:
7625 case Type::STK_ObjCObjectPointer:
7626 case Type::STK_BlockPointer:
7627 llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7627)
;
7628 case Type::STK_MemberPointer:
7629 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7629)
;
7630 case Type::STK_FixedPoint:
7631 Diag(Src.get()->getExprLoc(),
7632 diag::err_unimplemented_conversion_with_fixed_point_type)
7633 << SrcTy;
7634 return CK_IntegralCast;
7635 }
7636 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7636)
;
7637 }
7638
7639 llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "clang/lib/Sema/SemaExpr.cpp"
, 7639)
;
7640}
7641
7642static bool breakDownVectorType(QualType type, uint64_t &len,
7643 QualType &eltType) {
7644 // Vectors are simple.
7645 if (const VectorType *vecType = type->getAs<VectorType>()) {
7646 len = vecType->getNumElements();
7647 eltType = vecType->getElementType();
7648 assert(eltType->isScalarType())(static_cast <bool> (eltType->isScalarType()) ? void
(0) : __assert_fail ("eltType->isScalarType()", "clang/lib/Sema/SemaExpr.cpp"
, 7648, __extension__ __PRETTY_FUNCTION__))
;
7649 return true;
7650 }
7651
7652 // We allow lax conversion to and from non-vector types, but only if
7653 // they're real types (i.e. non-complex, non-pointer scalar types).
7654 if (!type->isRealType()) return false;
7655
7656 len = 1;
7657 eltType = type;
7658 return true;
7659}
7660
7661/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7662/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7663/// allowed?
7664///
7665/// This will also return false if the two given types do not make sense from
7666/// the perspective of SVE bitcasts.
7667bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7668 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", 7668, __extension__ __PRETTY_FUNCTION__
))
;
7669
7670 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7671 if (!FirstType->isSizelessBuiltinType())
7672 return false;
7673
7674 const auto *VecTy = SecondType->getAs<VectorType>();
7675 return VecTy &&
7676 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7677 };
7678
7679 return ValidScalableConversion(srcTy, destTy) ||
7680 ValidScalableConversion(destTy, srcTy);
7681}
7682
7683/// Are the two types matrix types and do they have the same dimensions i.e.
7684/// do they have the same number of rows and the same number of columns?
7685bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7686 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7687 return false;
7688
7689 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7690 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7691
7692 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7693 matSrcType->getNumColumns() == matDestType->getNumColumns();
7694}
7695
7696bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7697 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", 7697, __extension__ __PRETTY_FUNCTION__
))
;
7698
7699 uint64_t SrcLen, DestLen;
7700 QualType SrcEltTy, DestEltTy;
7701 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7702 return false;
7703 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7704 return false;
7705
7706 // ASTContext::getTypeSize will return the size rounded up to a
7707 // power of 2, so instead of using that, we need to use the raw
7708 // element size multiplied by the element count.
7709 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7710 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7711
7712 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7713}
7714
7715/// Are the two types lax-compatible vector types? That is, given
7716/// that one of them is a vector, do they have equal storage sizes,
7717/// where the storage size is the number of elements times the element
7718/// size?
7719///
7720/// This will also return false if either of the types is neither a
7721/// vector nor a real type.
7722bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7723 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", 7723, __extension__ __PRETTY_FUNCTION__
))
;
7724
7725 // Disallow lax conversions between scalars and ExtVectors (these
7726 // conversions are allowed for other vector types because common headers
7727 // depend on them). Most scalar OP ExtVector cases are handled by the
7728 // splat path anyway, which does what we want (convert, not bitcast).
7729 // What this rules out for ExtVectors is crazy things like char4*float.
7730 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7731 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7732
7733 return areVectorTypesSameSize(srcTy, destTy);
7734}
7735
7736/// Is this a legal conversion between two types, one of which is
7737/// known to be a vector type?
7738bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7739 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", 7739, __extension__ __PRETTY_FUNCTION__
))
;
7740
7741 switch (Context.getLangOpts().getLaxVectorConversions()) {
7742 case LangOptions::LaxVectorConversionKind::None:
7743 return false;
7744
7745 case LangOptions::LaxVectorConversionKind::Integer:
7746 if (!srcTy->isIntegralOrEnumerationType()) {
7747 auto *Vec = srcTy->getAs<VectorType>();
7748 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7749 return false;
7750 }
7751 if (!destTy->isIntegralOrEnumerationType()) {
7752 auto *Vec = destTy->getAs<VectorType>();
7753 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7754 return false;
7755 }
7756 // OK, integer (vector) -> integer (vector) bitcast.
7757 break;
7758
7759 case LangOptions::LaxVectorConversionKind::All:
7760 break;
7761 }
7762
7763 return areLaxCompatibleVectorTypes(srcTy, destTy);
7764}
7765
7766bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7767 CastKind &Kind) {
7768 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7769 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7770 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7771 << DestTy << SrcTy << R;
7772 }
7773 } else if (SrcTy->isMatrixType()) {
7774 return Diag(R.getBegin(),
7775 diag::err_invalid_conversion_between_matrix_and_type)
7776 << SrcTy << DestTy << R;
7777 } else if (DestTy->isMatrixType()) {
7778 return Diag(R.getBegin(),
7779 diag::err_invalid_conversion_between_matrix_and_type)
7780 << DestTy << SrcTy << R;
7781 }
7782
7783 Kind = CK_MatrixCast;
7784 return false;
7785}
7786
7787bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7788 CastKind &Kind) {
7789 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", 7789, __extension__ __PRETTY_FUNCTION__
))
;
7790
7791 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7792 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7793 return Diag(R.getBegin(),
7794 Ty->isVectorType() ?
7795 diag::err_invalid_conversion_between_vectors :
7796 diag::err_invalid_conversion_between_vector_and_integer)
7797 << VectorTy << Ty << R;
7798 } else
7799 return Diag(R.getBegin(),
7800 diag::err_invalid_conversion_between_vector_and_scalar)
7801 << VectorTy << Ty << R;
7802
7803 Kind = CK_BitCast;
7804 return false;
7805}
7806
7807ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7808 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7809
7810 if (DestElemTy == SplattedExpr->getType())
7811 return SplattedExpr;
7812
7813 assert(DestElemTy->isFloatingType() ||(static_cast <bool> (DestElemTy->isFloatingType() ||
DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "clang/lib/Sema/SemaExpr.cpp", 7814, __extension__ __PRETTY_FUNCTION__
))
7814 DestElemTy->isIntegralOrEnumerationType())(static_cast <bool> (DestElemTy->isFloatingType() ||
DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "clang/lib/Sema/SemaExpr.cpp", 7814, __extension__ __PRETTY_FUNCTION__
))
;
7815
7816 CastKind CK;
7817 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7818 // OpenCL requires that we convert `true` boolean expressions to -1, but
7819 // only when splatting vectors.
7820 if (DestElemTy->isFloatingType()) {
7821 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7822 // in two steps: boolean to signed integral, then to floating.
7823 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7824 CK_BooleanToSignedIntegral);
7825 SplattedExpr = CastExprRes.get();
7826 CK = CK_IntegralToFloating;
7827 } else {
7828 CK = CK_BooleanToSignedIntegral;
7829 }
7830 } else {
7831 ExprResult CastExprRes = SplattedExpr;
7832 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7833 if (CastExprRes.isInvalid())
7834 return ExprError();
7835 SplattedExpr = CastExprRes.get();
7836 }
7837 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7838}
7839
7840ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7841 Expr *CastExpr, CastKind &Kind) {
7842 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", 7842, __extension__ __PRETTY_FUNCTION__
))
;
7843
7844 QualType SrcTy = CastExpr->getType();
7845
7846 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7847 // an ExtVectorType.
7848 // In OpenCL, casts between vectors of different types are not allowed.
7849 // (See OpenCL 6.2).
7850 if (SrcTy->isVectorType()) {
7851 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7852 (getLangOpts().OpenCL &&
7853 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7854 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7855 << DestTy << SrcTy << R;
7856 return ExprError();
7857 }
7858 Kind = CK_BitCast;
7859 return CastExpr;
7860 }
7861
7862 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7863 // conversion will take place first from scalar to elt type, and then
7864 // splat from elt type to vector.
7865 if (SrcTy->isPointerType())
7866 return Diag(R.getBegin(),
7867 diag::err_invalid_conversion_between_vector_and_scalar)
7868 << DestTy << SrcTy << R;
7869
7870 Kind = CK_VectorSplat;
7871 return prepareVectorSplat(DestTy, CastExpr);
7872}
7873
7874ExprResult
7875Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7876 Declarator &D, ParsedType &Ty,
7877 SourceLocation RParenLoc, Expr *CastExpr) {
7878 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", 7879, __extension__ __PRETTY_FUNCTION__
))
7879 "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", 7879, __extension__ __PRETTY_FUNCTION__
))
;
7880
7881 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7882 if (D.isInvalidType())
7883 return ExprError();
7884
7885 if (getLangOpts().CPlusPlus) {
7886 // Check that there are no default arguments (C++ only).
7887 CheckExtraCXXDefaultArguments(D);
7888 } else {
7889 // Make sure any TypoExprs have been dealt with.
7890 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7891 if (!Res.isUsable())
7892 return ExprError();
7893 CastExpr = Res.get();
7894 }
7895
7896 checkUnusedDeclAttributes(D);
7897
7898 QualType castType = castTInfo->getType();
7899 Ty = CreateParsedType(castType, castTInfo);
7900
7901 bool isVectorLiteral = false;
7902
7903 // Check for an altivec or OpenCL literal,
7904 // i.e. all the elements are integer constants.
7905 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7906 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7907 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7908 && castType->isVectorType() && (PE || PLE)) {
7909 if (PLE && PLE->getNumExprs() == 0) {
7910 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7911 return ExprError();
7912 }
7913 if (PE || PLE->getNumExprs() == 1) {
7914 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7915 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7916 isVectorLiteral = true;
7917 }
7918 else
7919 isVectorLiteral = true;
7920 }
7921
7922 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7923 // then handle it as such.
7924 if (isVectorLiteral)
7925 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7926
7927 // If the Expr being casted is a ParenListExpr, handle it specially.
7928 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7929 // sequence of BinOp comma operators.
7930 if (isa<ParenListExpr>(CastExpr)) {
7931 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7932 if (Result.isInvalid()) return ExprError();
7933 CastExpr = Result.get();
7934 }
7935
7936 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7937 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7938
7939 CheckTollFreeBridgeCast(castType, CastExpr);
7940
7941 CheckObjCBridgeRelatedCast(castType, CastExpr);
7942
7943 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7944
7945 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7946}
7947
7948ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7949 SourceLocation RParenLoc, Expr *E,
7950 TypeSourceInfo *TInfo) {
7951 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", 7952, __extension__ __PRETTY_FUNCTION__
))
7952 "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", 7952, __extension__ __PRETTY_FUNCTION__
))
;
7953
7954 Expr **exprs;
7955 unsigned numExprs;
7956 Expr *subExpr;
7957 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7958 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7959 LiteralLParenLoc = PE->getLParenLoc();
7960 LiteralRParenLoc = PE->getRParenLoc();
7961 exprs = PE->getExprs();
7962 numExprs = PE->getNumExprs();
7963 } else { // isa<ParenExpr> by assertion at function entrance
7964 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7965 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7966 subExpr = cast<ParenExpr>(E)->getSubExpr();
7967 exprs = &subExpr;
7968 numExprs = 1;
7969 }
7970
7971 QualType Ty = TInfo->getType();
7972 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", 7972, __extension__ __PRETTY_FUNCTION__
))
;
7973
7974 SmallVector<Expr *, 8> initExprs;
7975 const VectorType *VTy = Ty->castAs<VectorType>();
7976 unsigned numElems = VTy->getNumElements();
7977
7978 // '(...)' form of vector initialization in AltiVec: the number of
7979 // initializers must be one or must match the size of the vector.
7980 // If a single value is specified in the initializer then it will be
7981 // replicated to all the components of the vector
7982 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
7983 VTy->getElementType()))
7984 return ExprError();
7985 if (ShouldSplatAltivecScalarInCast(VTy)) {
7986 // The number of initializers must be one or must match the size of the
7987 // vector. If a single value is specified in the initializer then it will
7988 // be replicated to all the components of the vector
7989 if (numExprs == 1) {
7990 QualType ElemTy = VTy->getElementType();
7991 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7992 if (Literal.isInvalid())
7993 return ExprError();
7994 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7995 PrepareScalarCast(Literal, ElemTy));
7996 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7997 }
7998 else if (numExprs < numElems) {
7999 Diag(E->getExprLoc(),
8000 diag::err_incorrect_number_of_vector_initializers);
8001 return ExprError();
8002 }
8003 else
8004 initExprs.append(exprs, exprs + numExprs);
8005 }
8006 else {
8007 // For OpenCL, when the number of initializers is a single value,
8008 // it will be replicated to all components of the vector.
8009 if (getLangOpts().OpenCL &&
8010 VTy->getVectorKind() == VectorType::GenericVector &&
8011 numExprs == 1) {
8012 QualType ElemTy = VTy->getElementType();
8013 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8014 if (Literal.isInvalid())
8015 return ExprError();
8016 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8017 PrepareScalarCast(Literal, ElemTy));
8018 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8019 }
8020
8021 initExprs.append(exprs, exprs + numExprs);
8022 }
8023 // FIXME: This means that pretty-printing the final AST will produce curly
8024 // braces instead of the original commas.
8025 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8026 initExprs, LiteralRParenLoc);
8027 initE->setType(Ty);
8028 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8029}
8030
8031/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8032/// the ParenListExpr into a sequence of comma binary operators.
8033ExprResult
8034Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8035 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8036 if (!E)
8037 return OrigExpr;
8038
8039 ExprResult Result(E->getExpr(0));
8040
8041 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8042 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8043 E->getExpr(i));
8044
8045 if (Result.isInvalid()) return ExprError();
8046
8047 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8048}
8049
8050ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8051 SourceLocation R,
8052 MultiExprArg Val) {
8053 return ParenListExpr::Create(Context, L, Val, R);
8054}
8055
8056/// Emit a specialized diagnostic when one expression is a null pointer
8057/// constant and the other is not a pointer. Returns true if a diagnostic is
8058/// emitted.
8059bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8060 SourceLocation QuestionLoc) {
8061 Expr *NullExpr = LHSExpr;
8062 Expr *NonPointerExpr = RHSExpr;
8063 Expr::NullPointerConstantKind NullKind =
8064 NullExpr->isNullPointerConstant(Context,
8065 Expr::NPC_ValueDependentIsNotNull);
8066
8067 if (NullKind == Expr::NPCK_NotNull) {
8068 NullExpr = RHSExpr;
8069 NonPointerExpr = LHSExpr;
8070 NullKind =
8071 NullExpr->isNullPointerConstant(Context,
8072 Expr::NPC_ValueDependentIsNotNull);
8073 }
8074
8075 if (NullKind == Expr::NPCK_NotNull)
8076 return false;
8077
8078 if (NullKind == Expr::NPCK_ZeroExpression)
8079 return false;
8080
8081 if (NullKind == Expr::NPCK_ZeroLiteral) {
8082 // In this case, check to make sure that we got here from a "NULL"
8083 // string in the source code.
8084 NullExpr = NullExpr->IgnoreParenImpCasts();
8085 SourceLocation loc = NullExpr->getExprLoc();
8086 if (!findMacroSpelling(loc, "NULL"))
8087 return false;
8088 }
8089
8090 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8091 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8092 << NonPointerExpr->getType() << DiagType
8093 << NonPointerExpr->getSourceRange();
8094 return true;
8095}
8096
8097/// Return false if the condition expression is valid, true otherwise.
8098static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8099 QualType CondTy = Cond->getType();
8100
8101 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8102 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8103 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8104 << CondTy << Cond->getSourceRange();
8105 return true;
8106 }
8107
8108 // C99 6.5.15p2
8109 if (CondTy->isScalarType()) return false;
8110
8111 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8112 << CondTy << Cond->getSourceRange();
8113 return true;
8114}
8115
8116/// Handle when one or both operands are void type.
8117static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
8118 ExprResult &RHS) {
8119 Expr *LHSExpr = LHS.get();
8120 Expr *RHSExpr = RHS.get();
8121
8122 if (!LHSExpr->getType()->isVoidType())
8123 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8124 << RHSExpr->getSourceRange();
8125 if (!RHSExpr->getType()->isVoidType())
8126 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8127 << LHSExpr->getSourceRange();
8128 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
8129 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
8130 return S.Context.VoidTy;
8131}
8132
8133/// Return false if the NullExpr can be promoted to PointerTy,
8134/// true otherwise.
8135static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8136 QualType PointerTy) {
8137 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8138 !NullExpr.get()->isNullPointerConstant(S.Context,
8139 Expr::NPC_ValueDependentIsNull))
8140 return true;
8141
8142 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8143 return false;
8144}
8145
8146/// Checks compatibility between two pointers and return the resulting
8147/// type.
8148static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8149 ExprResult &RHS,
8150 SourceLocation Loc) {
8151 QualType LHSTy = LHS.get()->getType();
8152 QualType RHSTy = RHS.get()->getType();
8153
8154 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8155 // Two identical pointers types are always compatible.
8156 return LHSTy;
8157 }
8158
8159 QualType lhptee, rhptee;
8160
8161 // Get the pointee types.
8162 bool IsBlockPointer = false;
8163 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8164 lhptee = LHSBTy->getPointeeType();
8165 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8166 IsBlockPointer = true;
8167 } else {
8168 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8169 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8170 }
8171
8172 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8173 // differently qualified versions of compatible types, the result type is
8174 // a pointer to an appropriately qualified version of the composite
8175 // type.
8176
8177 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8178 // clause doesn't make sense for our extensions. E.g. address space 2 should
8179 // be incompatible with address space 3: they may live on different devices or
8180 // anything.
8181 Qualifiers lhQual = lhptee.getQualifiers();
8182 Qualifiers rhQual = rhptee.getQualifiers();
8183
8184 LangAS ResultAddrSpace = LangAS::Default;
8185 LangAS LAddrSpace = lhQual.getAddressSpace();
8186 LangAS RAddrSpace = rhQual.getAddressSpace();
8187
8188 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8189 // spaces is disallowed.
8190 if (lhQual.isAddressSpaceSupersetOf(rhQual))
8191 ResultAddrSpace = LAddrSpace;
8192 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8193 ResultAddrSpace = RAddrSpace;
8194 else {
8195 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8196 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8197 << RHS.get()->getSourceRange();
8198 return QualType();
8199 }
8200
8201 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8202 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8203 lhQual.removeCVRQualifiers();
8204 rhQual.removeCVRQualifiers();
8205
8206 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8207 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8208 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8209 // qual types are compatible iff
8210 // * corresponded types are compatible
8211 // * CVR qualifiers are equal
8212 // * address spaces are equal
8213 // Thus for conditional operator we merge CVR and address space unqualified
8214 // pointees and if there is a composite type we return a pointer to it with
8215 // merged qualifiers.
8216 LHSCastKind =
8217 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8218 RHSCastKind =
8219 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8220 lhQual.removeAddressSpace();
8221 rhQual.removeAddressSpace();
8222
8223 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8224 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8225
8226 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
8227
8228 if (CompositeTy.isNull()) {
8229 // In this situation, we assume void* type. No especially good
8230 // reason, but this is what gcc does, and we do have to pick
8231 // to get a consistent AST.
8232 QualType incompatTy;
8233 incompatTy = S.Context.getPointerType(
8234 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8235 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8236 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8237
8238 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8239 // for casts between types with incompatible address space qualifiers.
8240 // For the following code the compiler produces casts between global and
8241 // local address spaces of the corresponded innermost pointees:
8242 // local int *global *a;
8243 // global int *global *b;
8244 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8245 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8246 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8247 << RHS.get()->getSourceRange();
8248
8249 return incompatTy;
8250 }
8251
8252 // The pointer types are compatible.
8253 // In case of OpenCL ResultTy should have the address space qualifier
8254 // which is a superset of address spaces of both the 2nd and the 3rd
8255 // operands of the conditional operator.
8256 QualType ResultTy = [&, ResultAddrSpace]() {
8257 if (S.getLangOpts().OpenCL) {
8258 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8259 CompositeQuals.setAddressSpace(ResultAddrSpace);
8260 return S.Context
8261 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8262 .withCVRQualifiers(MergedCVRQual);
8263 }
8264 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8265 }();
8266 if (IsBlockPointer)
8267 ResultTy = S.Context.getBlockPointerType(ResultTy);
8268 else
8269 ResultTy = S.Context.getPointerType(ResultTy);
8270
8271 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8272 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8273 return ResultTy;
8274}
8275
8276/// Return the resulting type when the operands are both block pointers.
8277static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8278 ExprResult &LHS,
8279 ExprResult &RHS,
8280 SourceLocation Loc) {
8281 QualType LHSTy = LHS.get()->getType();
8282 QualType RHSTy = RHS.get()->getType();
8283
8284 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8285 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8286 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8287 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8288 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8289 return destType;
8290 }
8291 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8292 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8293 << RHS.get()->getSourceRange();
8294 return QualType();
8295 }
8296
8297 // We have 2 block pointer types.
8298 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8299}
8300
8301/// Return the resulting type when the operands are both pointers.
8302static QualType
8303checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8304 ExprResult &RHS,
8305 SourceLocation Loc) {
8306 // get the pointer types
8307 QualType LHSTy = LHS.get()->getType();
8308 QualType RHSTy = RHS.get()->getType();
8309
8310 // get the "pointed to" types
8311 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8312 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8313
8314 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8315 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8316 // Figure out necessary qualifiers (C99 6.5.15p6)
8317 QualType destPointee
8318 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8319 QualType destType = S.Context.getPointerType(destPointee);
8320 // Add qualifiers if necessary.
8321 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8322 // Promote to void*.
8323 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8324 return destType;
8325 }
8326 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8327 QualType destPointee
8328 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8329 QualType destType = S.Context.getPointerType(destPointee);
8330 // Add qualifiers if necessary.
8331 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8332 // Promote to void*.
8333 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8334 return destType;
8335 }
8336
8337 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8338}
8339
8340/// Return false if the first expression is not an integer and the second
8341/// expression is not a pointer, true otherwise.
8342static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8343 Expr* PointerExpr, SourceLocation Loc,
8344 bool IsIntFirstExpr) {
8345 if (!PointerExpr->getType()->isPointerType() ||
8346 !Int.get()->getType()->isIntegerType())
8347 return false;
8348
8349 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8350 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8351
8352 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8353 << Expr1->getType() << Expr2->getType()
8354 << Expr1->getSourceRange() << Expr2->getSourceRange();
8355 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8356 CK_IntegralToPointer);
8357 return true;
8358}
8359
8360/// Simple conversion between integer and floating point types.
8361///
8362/// Used when handling the OpenCL conditional operator where the
8363/// condition is a vector while the other operands are scalar.
8364///
8365/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8366/// types are either integer or floating type. Between the two
8367/// operands, the type with the higher rank is defined as the "result
8368/// type". The other operand needs to be promoted to the same type. No
8369/// other type promotion is allowed. We cannot use
8370/// UsualArithmeticConversions() for this purpose, since it always
8371/// promotes promotable types.
8372static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8373 ExprResult &RHS,
8374 SourceLocation QuestionLoc) {
8375 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8376 if (LHS.isInvalid())
8377 return QualType();
8378 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8379 if (RHS.isInvalid())
8380 return QualType();
8381
8382 // For conversion purposes, we ignore any qualifiers.
8383 // For example, "const float" and "float" are equivalent.
8384 QualType LHSType =
8385 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8386 QualType RHSType =
8387 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8388
8389 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8390 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8391 << LHSType << LHS.get()->getSourceRange();
8392 return QualType();
8393 }
8394
8395 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8396 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8397 << RHSType << RHS.get()->getSourceRange();
8398 return QualType();
8399 }
8400
8401 // If both types are identical, no conversion is needed.
8402 if (LHSType == RHSType)
8403 return LHSType;
8404
8405 // Now handle "real" floating types (i.e. float, double, long double).
8406 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8407 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8408 /*IsCompAssign = */ false);
8409
8410 // Finally, we have two differing integer types.
8411 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8412 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8413}
8414
8415/// Convert scalar operands to a vector that matches the
8416/// condition in length.
8417///
8418/// Used when handling the OpenCL conditional operator where the
8419/// condition is a vector while the other operands are scalar.
8420///
8421/// We first compute the "result type" for the scalar operands
8422/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8423/// into a vector of that type where the length matches the condition
8424/// vector type. s6.11.6 requires that the element types of the result
8425/// and the condition must have the same number of bits.
8426static QualType
8427OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8428 QualType CondTy, SourceLocation QuestionLoc) {
8429 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8430 if (ResTy.isNull()) return QualType();
8431
8432 const VectorType *CV = CondTy->getAs<VectorType>();
8433 assert(CV)(static_cast <bool> (CV) ? void (0) : __assert_fail ("CV"
, "clang/lib/Sema/SemaExpr.cpp", 8433, __extension__ __PRETTY_FUNCTION__
))
;
8434
8435 // Determine the vector result type
8436 unsigned NumElements = CV->getNumElements();
8437 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8438
8439 // Ensure that all types have the same number of bits
8440 if (S.Context.getTypeSize(CV->getElementType())
8441 != S.Context.getTypeSize(ResTy)) {
8442 // Since VectorTy is created internally, it does not pretty print
8443 // with an OpenCL name. Instead, we just print a description.
8444 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8445 SmallString<64> Str;
8446 llvm::raw_svector_ostream OS(Str);
8447 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8448 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8449 << CondTy << OS.str();
8450 return QualType();
8451 }
8452
8453 // Convert operands to the vector result type
8454 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8455 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8456
8457 return VectorTy;
8458}
8459
8460/// Return false if this is a valid OpenCL condition vector
8461static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8462 SourceLocation QuestionLoc) {
8463 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8464 // integral type.
8465 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8466 assert(CondTy)(static_cast <bool> (CondTy) ? void (0) : __assert_fail
("CondTy", "clang/lib/Sema/SemaExpr.cpp", 8466, __extension__
__PRETTY_FUNCTION__))
;
8467 QualType EleTy = CondTy->getElementType();
8468 if (EleTy->isIntegerType()) return false;
8469
8470 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8471 << Cond->getType() << Cond->getSourceRange();
8472 return true;
8473}
8474
8475/// Return false if the vector condition type and the vector
8476/// result type are compatible.
8477///
8478/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8479/// number of elements, and their element types have the same number
8480/// of bits.
8481static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8482 SourceLocation QuestionLoc) {
8483 const VectorType *CV = CondTy->getAs<VectorType>();
8484 const VectorType *RV = VecResTy->getAs<VectorType>();
8485 assert(CV && RV)(static_cast <bool> (CV && RV) ? void (0) : __assert_fail
("CV && RV", "clang/lib/Sema/SemaExpr.cpp", 8485, __extension__
__PRETTY_FUNCTION__))
;
8486
8487 if (CV->getNumElements() != RV->getNumElements()) {
8488 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8489 << CondTy << VecResTy;
8490 return true;
8491 }
8492
8493 QualType CVE = CV->getElementType();
8494 QualType RVE = RV->getElementType();
8495
8496 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8497 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8498 << CondTy << VecResTy;
8499 return true;
8500 }
8501
8502 return false;
8503}
8504
8505/// Return the resulting type for the conditional operator in
8506/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8507/// s6.3.i) when the condition is a vector type.
8508static QualType
8509OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8510 ExprResult &LHS, ExprResult &RHS,
8511 SourceLocation QuestionLoc) {
8512 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8513 if (Cond.isInvalid())
8514 return QualType();
8515 QualType CondTy = Cond.get()->getType();
8516
8517 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8518 return QualType();
8519
8520 // If either operand is a vector then find the vector type of the
8521 // result as specified in OpenCL v1.1 s6.3.i.
8522 if (LHS.get()->getType()->isVectorType() ||
8523 RHS.get()->getType()->isVectorType()) {
8524 bool IsBoolVecLang =
8525 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8526 QualType VecResTy =
8527 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8528 /*isCompAssign*/ false,
8529 /*AllowBothBool*/ true,
8530 /*AllowBoolConversions*/ false,
8531 /*AllowBooleanOperation*/ IsBoolVecLang,
8532 /*ReportInvalid*/ true);
8533 if (VecResTy.isNull())
8534 return QualType();
8535 // The result type must match the condition type as specified in
8536 // OpenCL v1.1 s6.11.6.
8537 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8538 return QualType();
8539 return VecResTy;
8540 }
8541
8542 // Both operands are scalar.
8543 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8544}
8545
8546/// Return true if the Expr is block type
8547static bool checkBlockType(Sema &S, const Expr *E) {
8548 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8549 QualType Ty = CE->getCallee()->getType();
8550 if (Ty->isBlockPointerType()) {
8551 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8552 return true;
8553 }
8554 }
8555 return false;
8556}
8557
8558/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8559/// In that case, LHS = cond.
8560/// C99 6.5.15
8561QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8562 ExprResult &RHS, ExprValueKind &VK,
8563 ExprObjectKind &OK,
8564 SourceLocation QuestionLoc) {
8565
8566 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8567 if (!LHSResult.isUsable()) return QualType();
8568 LHS = LHSResult;
8569
8570 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8571 if (!RHSResult.isUsable()) return QualType();
8572 RHS = RHSResult;
8573
8574 // C++ is sufficiently different to merit its own checker.
8575 if (getLangOpts().CPlusPlus)
8576 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8577
8578 VK = VK_PRValue;
8579 OK = OK_Ordinary;
8580
8581 if (Context.isDependenceAllowed() &&
8582 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8583 RHS.get()->isTypeDependent())) {
8584 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 8584, __extension__ __PRETTY_FUNCTION__))
;
8585 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", 8587, __extension__ __PRETTY_FUNCTION__
))
8586 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", 8587, __extension__ __PRETTY_FUNCTION__
))
8587 "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", 8587, __extension__ __PRETTY_FUNCTION__
))
;
8588 return Context.DependentTy;
8589 }
8590
8591 // The OpenCL operator with a vector condition is sufficiently
8592 // different to merit its own checker.
8593 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8594 Cond.get()->getType()->isExtVectorType())
8595 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8596
8597 // First, check the condition.
8598 Cond = UsualUnaryConversions(Cond.get());
8599 if (Cond.isInvalid())
8600 return QualType();
8601 if (checkCondition(*this, Cond.get(), QuestionLoc))
8602 return QualType();
8603
8604 // Now check the two expressions.
8605 if (LHS.get()->getType()->isVectorType() ||
8606 RHS.get()->getType()->isVectorType())
8607 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8608 /*AllowBothBool*/ true,
8609 /*AllowBoolConversions*/ false,
8610 /*AllowBooleanOperation*/ false,
8611 /*ReportInvalid*/ true);
8612
8613 QualType ResTy =
8614 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8615 if (LHS.isInvalid() || RHS.isInvalid())
8616 return QualType();
8617
8618 QualType LHSTy = LHS.get()->getType();
8619 QualType RHSTy = RHS.get()->getType();
8620
8621 // Diagnose attempts to convert between __ibm128, __float128 and long double
8622 // where such conversions currently can't be handled.
8623 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8624 Diag(QuestionLoc,
8625 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8626 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8627 return QualType();
8628 }
8629
8630 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8631 // selection operator (?:).
8632 if (getLangOpts().OpenCL &&
8633 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8634 return QualType();
8635 }
8636
8637 // If both operands have arithmetic type, do the usual arithmetic conversions
8638 // to find a common type: C99 6.5.15p3,5.
8639 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8640 // Disallow invalid arithmetic conversions, such as those between bit-
8641 // precise integers types of different sizes, or between a bit-precise
8642 // integer and another type.
8643 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8644 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8645 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8646 << RHS.get()->getSourceRange();
8647 return QualType();
8648 }
8649
8650 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8651 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8652
8653 return ResTy;
8654 }
8655
8656 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8657 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8658 return LHSTy;
8659 }
8660
8661 // If both operands are the same structure or union type, the result is that
8662 // type.
8663 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8664 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8665 if (LHSRT->getDecl() == RHSRT->getDecl())
8666 // "If both the operands have structure or union type, the result has
8667 // that type." This implies that CV qualifiers are dropped.
8668 return LHSTy.getUnqualifiedType();
8669 // FIXME: Type of conditional expression must be complete in C mode.
8670 }
8671
8672 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8673 // The following || allows only one side to be void (a GCC-ism).
8674 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8675 return checkConditionalVoidType(*this, LHS, RHS);
8676 }
8677
8678 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8679 // the type of the other operand."
8680 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8681 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8682
8683 // All objective-c pointer type analysis is done here.
8684 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8685 QuestionLoc);
8686 if (LHS.isInvalid() || RHS.isInvalid())
8687 return QualType();
8688 if (!compositeType.isNull())
8689 return compositeType;
8690
8691
8692 // Handle block pointer types.
8693 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8694 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8695 QuestionLoc);
8696
8697 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8698 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8699 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8700 QuestionLoc);
8701
8702 // GCC compatibility: soften pointer/integer mismatch. Note that
8703 // null pointers have been filtered out by this point.
8704 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8705 /*IsIntFirstExpr=*/true))
8706 return RHSTy;
8707 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8708 /*IsIntFirstExpr=*/false))
8709 return LHSTy;
8710
8711 // Allow ?: operations in which both operands have the same
8712 // built-in sizeless type.
8713 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8714 return LHSTy;
8715
8716 // Emit a better diagnostic if one of the expressions is a null pointer
8717 // constant and the other is not a pointer type. In this case, the user most
8718 // likely forgot to take the address of the other expression.
8719 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8720 return QualType();
8721
8722 // Otherwise, the operands are not compatible.
8723 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8724 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8725 << RHS.get()->getSourceRange();
8726 return QualType();
8727}
8728
8729/// FindCompositeObjCPointerType - Helper method to find composite type of
8730/// two objective-c pointer types of the two input expressions.
8731QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8732 SourceLocation QuestionLoc) {
8733 QualType LHSTy = LHS.get()->getType();
8734 QualType RHSTy = RHS.get()->getType();
8735
8736 // Handle things like Class and struct objc_class*. Here we case the result
8737 // to the pseudo-builtin, because that will be implicitly cast back to the
8738 // redefinition type if an attempt is made to access its fields.
8739 if (LHSTy->isObjCClassType() &&
8740 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8741 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8742 return LHSTy;
8743 }
8744 if (RHSTy->isObjCClassType() &&
8745 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8746 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8747 return RHSTy;
8748 }
8749 // And the same for struct objc_object* / id
8750 if (LHSTy->isObjCIdType() &&
8751 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8752 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8753 return LHSTy;
8754 }
8755 if (RHSTy->isObjCIdType() &&
8756 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8757 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8758 return RHSTy;
8759 }
8760 // And the same for struct objc_selector* / SEL
8761 if (Context.isObjCSelType(LHSTy) &&
8762 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8763 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8764 return LHSTy;
8765 }
8766 if (Context.isObjCSelType(RHSTy) &&
8767 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8768 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8769 return RHSTy;
8770 }
8771 // Check constraints for Objective-C object pointers types.
8772 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8773
8774 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8775 // Two identical object pointer types are always compatible.
8776 return LHSTy;
8777 }
8778 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8779 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8780 QualType compositeType = LHSTy;
8781
8782 // If both operands are interfaces and either operand can be
8783 // assigned to the other, use that type as the composite
8784 // type. This allows
8785 // xxx ? (A*) a : (B*) b
8786 // where B is a subclass of A.
8787 //
8788 // Additionally, as for assignment, if either type is 'id'
8789 // allow silent coercion. Finally, if the types are
8790 // incompatible then make sure to use 'id' as the composite
8791 // type so the result is acceptable for sending messages to.
8792
8793 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8794 // It could return the composite type.
8795 if (!(compositeType =
8796 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8797 // Nothing more to do.
8798 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8799 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8800 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8801 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8802 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8803 RHSOPT->isObjCQualifiedIdType()) &&
8804 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8805 true)) {
8806 // Need to handle "id<xx>" explicitly.
8807 // GCC allows qualified id and any Objective-C type to devolve to
8808 // id. Currently localizing to here until clear this should be
8809 // part of ObjCQualifiedIdTypesAreCompatible.
8810 compositeType = Context.getObjCIdType();
8811 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8812 compositeType = Context.getObjCIdType();
8813 } else {
8814 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8815 << LHSTy << RHSTy
8816 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8817 QualType incompatTy = Context.getObjCIdType();
8818 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8819 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8820 return incompatTy;
8821 }
8822 // The object pointer types are compatible.
8823 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8824 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8825 return compositeType;
8826 }
8827 // Check Objective-C object pointer types and 'void *'
8828 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8829 if (getLangOpts().ObjCAutoRefCount) {
8830 // ARC forbids the implicit conversion of object pointers to 'void *',
8831 // so these types are not compatible.
8832 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8833 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8834 LHS = RHS = true;
8835 return QualType();
8836 }
8837 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8838 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8839 QualType destPointee
8840 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8841 QualType destType = Context.getPointerType(destPointee);
8842 // Add qualifiers if necessary.
8843 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8844 // Promote to void*.
8845 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8846 return destType;
8847 }
8848 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8849 if (getLangOpts().ObjCAutoRefCount) {
8850 // ARC forbids the implicit conversion of object pointers to 'void *',
8851 // so these types are not compatible.
8852 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8853 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8854 LHS = RHS = true;
8855 return QualType();
8856 }
8857 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8858 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8859 QualType destPointee
8860 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8861 QualType destType = Context.getPointerType(destPointee);
8862 // Add qualifiers if necessary.
8863 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8864 // Promote to void*.
8865 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8866 return destType;
8867 }
8868 return QualType();
8869}
8870
8871/// SuggestParentheses - Emit a note with a fixit hint that wraps
8872/// ParenRange in parentheses.
8873static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8874 const PartialDiagnostic &Note,
8875 SourceRange ParenRange) {
8876 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8877 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8878 EndLoc.isValid()) {
8879 Self.Diag(Loc, Note)
8880 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8881 << FixItHint::CreateInsertion(EndLoc, ")");
8882 } else {
8883 // We can't display the parentheses, so just show the bare note.
8884 Self.Diag(Loc, Note) << ParenRange;
8885 }
8886}
8887
8888static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8889 return BinaryOperator::isAdditiveOp(Opc) ||
8890 BinaryOperator::isMultiplicativeOp(Opc) ||
8891 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8892 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8893 // not any of the logical operators. Bitwise-xor is commonly used as a
8894 // logical-xor because there is no logical-xor operator. The logical
8895 // operators, including uses of xor, have a high false positive rate for
8896 // precedence warnings.
8897}
8898
8899/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8900/// expression, either using a built-in or overloaded operator,
8901/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8902/// expression.
8903static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8904 Expr **RHSExprs) {
8905 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8906 E = E->IgnoreImpCasts();
8907 E = E->IgnoreConversionOperatorSingleStep();
8908 E = E->IgnoreImpCasts();
8909 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8910 E = MTE->getSubExpr();
8911 E = E->IgnoreImpCasts();
8912 }
8913
8914 // Built-in binary operator.
8915 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8916 if (IsArithmeticOp(OP->getOpcode())) {
8917 *Opcode = OP->getOpcode();
8918 *RHSExprs = OP->getRHS();
8919 return true;
8920 }
8921 }
8922
8923 // Overloaded operator.
8924 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8925 if (Call->getNumArgs() != 2)
8926 return false;
8927
8928 // Make sure this is really a binary operator that is safe to pass into
8929 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8930 OverloadedOperatorKind OO = Call->getOperator();
8931 if (OO < OO_Plus || OO > OO_Arrow ||
8932 OO == OO_PlusPlus || OO == OO_MinusMinus)
8933 return false;
8934
8935 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8936 if (IsArithmeticOp(OpKind)) {
8937 *Opcode = OpKind;
8938 *RHSExprs = Call->getArg(1);
8939 return true;
8940 }
8941 }
8942
8943 return false;
8944}
8945
8946/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8947/// or is a logical expression such as (x==y) which has int type, but is
8948/// commonly interpreted as boolean.
8949static bool ExprLooksBoolean(Expr *E) {
8950 E = E->IgnoreParenImpCasts();
8951
8952 if (E->getType()->isBooleanType())
8953 return true;
8954 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8955 return OP->isComparisonOp() || OP->isLogicalOp();
8956 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8957 return OP->getOpcode() == UO_LNot;
8958 if (E->getType()->isPointerType())
8959 return true;
8960 // FIXME: What about overloaded operator calls returning "unspecified boolean
8961 // type"s (commonly pointer-to-members)?
8962
8963 return false;
8964}
8965
8966/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8967/// and binary operator are mixed in a way that suggests the programmer assumed
8968/// the conditional operator has higher precedence, for example:
8969/// "int x = a + someBinaryCondition ? 1 : 2".
8970static void DiagnoseConditionalPrecedence(Sema &Self,
8971 SourceLocation OpLoc,
8972 Expr *Condition,
8973 Expr *LHSExpr,
8974 Expr *RHSExpr) {
8975 BinaryOperatorKind CondOpcode;
8976 Expr *CondRHS;
8977
8978 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8979 return;
8980 if (!ExprLooksBoolean(CondRHS))
8981 return;
8982
8983 // The condition is an arithmetic binary expression, with a right-
8984 // hand side that looks boolean, so warn.
8985
8986 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8987 ? diag::warn_precedence_bitwise_conditional
8988 : diag::warn_precedence_conditional;
8989
8990 Self.Diag(OpLoc, DiagID)
8991 << Condition->getSourceRange()
8992 << BinaryOperator::getOpcodeStr(CondOpcode);
8993
8994 SuggestParentheses(
8995 Self, OpLoc,
8996 Self.PDiag(diag::note_precedence_silence)
8997 << BinaryOperator::getOpcodeStr(CondOpcode),
8998 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8999
9000 SuggestParentheses(Self, OpLoc,
9001 Self.PDiag(diag::note_precedence_conditional_first),
9002 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9003}
9004
9005/// Compute the nullability of a conditional expression.
9006static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9007 QualType LHSTy, QualType RHSTy,
9008 ASTContext &Ctx) {
9009 if (!ResTy->isAnyPointerType())
9010 return ResTy;
9011
9012 auto GetNullability = [&Ctx](QualType Ty) {
9013 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
9014 if (Kind) {
9015 // For our purposes, treat _Nullable_result as _Nullable.
9016 if (*Kind == NullabilityKind::NullableResult)
9017 return NullabilityKind::Nullable;
9018 return *Kind;
9019 }
9020 return NullabilityKind::Unspecified;
9021 };
9022
9023 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9024 NullabilityKind MergedKind;
9025
9026 // Compute nullability of a binary conditional expression.
9027 if (IsBin) {
9028 if (LHSKind == NullabilityKind::NonNull)
9029 MergedKind = NullabilityKind::NonNull;
9030 else
9031 MergedKind = RHSKind;
9032 // Compute nullability of a normal conditional expression.
9033 } else {
9034 if (LHSKind == NullabilityKind::Nullable ||
9035 RHSKind == NullabilityKind::Nullable)
9036 MergedKind = NullabilityKind::Nullable;
9037 else if (LHSKind == NullabilityKind::NonNull)
9038 MergedKind = RHSKind;
9039 else if (RHSKind == NullabilityKind::NonNull)
9040 MergedKind = LHSKind;
9041 else
9042 MergedKind = NullabilityKind::Unspecified;
9043 }
9044
9045 // Return if ResTy already has the correct nullability.
9046 if (GetNullability(ResTy) == MergedKind)
9047 return ResTy;
9048
9049 // Strip all nullability from ResTy.
9050 while (ResTy->getNullability(Ctx))
9051 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9052
9053 // Create a new AttributedType with the new nullability kind.
9054 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9055 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9056}
9057
9058/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9059/// in the case of a the GNU conditional expr extension.
9060ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9061 SourceLocation ColonLoc,
9062 Expr *CondExpr, Expr *LHSExpr,
9063 Expr *RHSExpr) {
9064 if (!Context.isDependenceAllowed()) {
9065 // C cannot handle TypoExpr nodes in the condition because it
9066 // doesn't handle dependent types properly, so make sure any TypoExprs have
9067 // been dealt with before checking the operands.
9068 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9069 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9070 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9071
9072 if (!CondResult.isUsable())
9073 return ExprError();
9074
9075 if (LHSExpr) {
9076 if (!LHSResult.isUsable())
9077 return ExprError();
9078 }
9079
9080 if (!RHSResult.isUsable())
9081 return ExprError();
9082
9083 CondExpr = CondResult.get();
9084 LHSExpr = LHSResult.get();
9085 RHSExpr = RHSResult.get();
9086 }
9087
9088 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9089 // was the condition.
9090 OpaqueValueExpr *opaqueValue = nullptr;
9091 Expr *commonExpr = nullptr;
9092 if (!LHSExpr) {
9093 commonExpr = CondExpr;
9094 // Lower out placeholder types first. This is important so that we don't
9095 // try to capture a placeholder. This happens in few cases in C++; such
9096 // as Objective-C++'s dictionary subscripting syntax.
9097 if (commonExpr->hasPlaceholderType()) {
9098 ExprResult result = CheckPlaceholderExpr(commonExpr);
9099 if (!result.isUsable()) return ExprError();
9100 commonExpr = result.get();
9101 }
9102 // We usually want to apply unary conversions *before* saving, except
9103 // in the special case of a C++ l-value conditional.
9104 if (!(getLangOpts().CPlusPlus
9105 && !commonExpr->isTypeDependent()
9106 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9107 && commonExpr->isGLValue()
9108 && commonExpr->isOrdinaryOrBitFieldObject()
9109 && RHSExpr->isOrdinaryOrBitFieldObject()
9110 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9111 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9112 if (commonRes.isInvalid())
9113 return ExprError();
9114 commonExpr = commonRes.get();
9115 }
9116
9117 // If the common expression is a class or array prvalue, materialize it
9118 // so that we can safely refer to it multiple times.
9119 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9120 commonExpr->getType()->isArrayType())) {
9121 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9122 if (MatExpr.isInvalid())
9123 return ExprError();
9124 commonExpr = MatExpr.get();
9125 }
9126
9127 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9128 commonExpr->getType(),
9129 commonExpr->getValueKind(),
9130 commonExpr->getObjectKind(),
9131 commonExpr);
9132 LHSExpr = CondExpr = opaqueValue;
9133 }
9134
9135 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9136 ExprValueKind VK = VK_PRValue;
9137 ExprObjectKind OK = OK_Ordinary;
9138 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9139 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9140 VK, OK, QuestionLoc);
9141 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9142 RHS.isInvalid())
9143 return ExprError();
9144
9145 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9146 RHS.get());
9147
9148 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9149
9150 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9151 Context);
9152
9153 if (!commonExpr)
9154 return new (Context)
9155 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9156 RHS.get(), result, VK, OK);
9157
9158 return new (Context) BinaryConditionalOperator(
9159 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9160 ColonLoc, result, VK, OK);
9161}
9162
9163// Check if we have a conversion between incompatible cmse function pointer
9164// types, that is, a conversion between a function pointer with the
9165// cmse_nonsecure_call attribute and one without.
9166static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9167 QualType ToType) {
9168 if (const auto *ToFn =
9169 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9170 if (const auto *FromFn =
9171 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9172 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9173 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9174
9175 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9176 }
9177 }
9178 return false;
9179}
9180
9181// checkPointerTypesForAssignment - This is a very tricky routine (despite
9182// being closely modeled after the C99 spec:-). The odd characteristic of this
9183// routine is it effectively iqnores the qualifiers on the top level pointee.
9184// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9185// FIXME: add a couple examples in this comment.
9186static Sema::AssignConvertType
9187checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
9188 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", 9188, __extension__ __PRETTY_FUNCTION__
))
;
9189 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", 9189, __extension__ __PRETTY_FUNCTION__
))
;
9190
9191 // get the "pointed to" type (ignoring qualifiers at the top level)
9192 const Type *lhptee, *rhptee;
9193 Qualifiers lhq, rhq;
9194 std::tie(lhptee, lhq) =
9195 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9196 std::tie(rhptee, rhq) =
9197 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9198
9199 Sema::AssignConvertType ConvTy = Sema::Compatible;
9200
9201 // C99 6.5.16.1p1: This following citation is common to constraints
9202 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9203 // qualifiers of the type *pointed to* by the right;
9204
9205 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9206 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9207 lhq.compatiblyIncludesObjCLifetime(rhq)) {
9208 // Ignore lifetime for further calculation.
9209 lhq.removeObjCLifetime();
9210 rhq.removeObjCLifetime();
9211 }
9212
9213 if (!lhq.compatiblyIncludes(rhq)) {
9214 // Treat address-space mismatches as fatal.
9215 if (!lhq.isAddressSpaceSupersetOf(rhq))
9216 return Sema::IncompatiblePointerDiscardsQualifiers;
9217
9218 // It's okay to add or remove GC or lifetime qualifiers when converting to
9219 // and from void*.
9220 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9221 .compatiblyIncludes(
9222 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9223 && (lhptee->isVoidType() || rhptee->isVoidType()))
9224 ; // keep old
9225
9226 // Treat lifetime mismatches as fatal.
9227 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9228 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9229
9230 // For GCC/MS compatibility, other qualifier mismatches are treated
9231 // as still compatible in C.
9232 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9233 }
9234
9235 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9236 // incomplete type and the other is a pointer to a qualified or unqualified
9237 // version of void...
9238 if (lhptee->isVoidType()) {
9239 if (rhptee->isIncompleteOrObjectType())
9240 return ConvTy;
9241
9242 // As an extension, we allow cast to/from void* to function pointer.
9243 assert(rhptee->isFunctionType())(static_cast <bool> (rhptee->isFunctionType()) ? void
(0) : __assert_fail ("rhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp"
, 9243, __extension__ __PRETTY_FUNCTION__))
;
9244 return Sema::FunctionVoidPointer;
9245 }
9246
9247 if (rhptee->isVoidType()) {
9248 if (lhptee->isIncompleteOrObjectType())
9249 return ConvTy;
9250
9251 // As an extension, we allow cast to/from void* to function pointer.
9252 assert(lhptee->isFunctionType())(static_cast <bool> (lhptee->isFunctionType()) ? void
(0) : __assert_fail ("lhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp"
, 9252, __extension__ __PRETTY_FUNCTION__))
;
9253 return Sema::FunctionVoidPointer;
9254 }
9255
9256 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9257 // unqualified versions of compatible types, ...
9258 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9259 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9260 // Check if the pointee types are compatible ignoring the sign.
9261 // We explicitly check for char so that we catch "char" vs
9262 // "unsigned char" on systems where "char" is unsigned.
9263 if (lhptee->isCharType())
9264 ltrans = S.Context.UnsignedCharTy;
9265 else if (lhptee->hasSignedIntegerRepresentation())
9266 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9267
9268 if (rhptee->isCharType())
9269 rtrans = S.Context.UnsignedCharTy;
9270 else if (rhptee->hasSignedIntegerRepresentation())
9271 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9272
9273 if (ltrans == rtrans) {
9274 // Types are compatible ignoring the sign. Qualifier incompatibility
9275 // takes priority over sign incompatibility because the sign
9276 // warning can be disabled.
9277 if (ConvTy != Sema::Compatible)
9278 return ConvTy;
9279
9280 return Sema::IncompatiblePointerSign;
9281 }
9282
9283 // If we are a multi-level pointer, it's possible that our issue is simply
9284 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9285 // the eventual target type is the same and the pointers have the same
9286 // level of indirection, this must be the issue.
9287 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9288 do {
9289 std::tie(lhptee, lhq) =
9290 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9291 std::tie(rhptee, rhq) =
9292 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9293
9294 // Inconsistent address spaces at this point is invalid, even if the
9295 // address spaces would be compatible.
9296 // FIXME: This doesn't catch address space mismatches for pointers of
9297 // different nesting levels, like:
9298 // __local int *** a;
9299 // int ** b = a;
9300 // It's not clear how to actually determine when such pointers are
9301 // invalidly incompatible.
9302 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9303 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9304
9305 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9306
9307 if (lhptee == rhptee)
9308 return Sema::IncompatibleNestedPointerQualifiers;
9309 }
9310
9311 // General pointer incompatibility takes priority over qualifiers.
9312 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9313 return Sema::IncompatibleFunctionPointer;
9314 return Sema::IncompatiblePointer;
9315 }
9316 if (!S.getLangOpts().CPlusPlus &&
9317 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9318 return Sema::IncompatibleFunctionPointer;
9319 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9320 return Sema::IncompatibleFunctionPointer;
9321 return ConvTy;
9322}
9323
9324/// checkBlockPointerTypesForAssignment - This routine determines whether two
9325/// block pointer types are compatible or whether a block and normal pointer
9326/// are compatible. It is more restrict than comparing two function pointer
9327// types.
9328static Sema::AssignConvertType
9329checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9330 QualType RHSType) {
9331 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", 9331, __extension__ __PRETTY_FUNCTION__
))
;
9332 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", 9332, __extension__ __PRETTY_FUNCTION__
))
;
9333
9334 QualType lhptee, rhptee;
9335
9336 // get the "pointed to" type (ignoring qualifiers at the top level)
9337 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9338 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9339
9340 // In C++, the types have to match exactly.
9341 if (S.getLangOpts().CPlusPlus)
9342 return Sema::IncompatibleBlockPointer;
9343
9344 Sema::AssignConvertType ConvTy = Sema::Compatible;
9345
9346 // For blocks we enforce that qualifiers are identical.
9347 Qualifiers LQuals = lhptee.getLocalQualifiers();
9348 Qualifiers RQuals = rhptee.getLocalQualifiers();
9349 if (S.getLangOpts().OpenCL) {
9350 LQuals.removeAddressSpace();
9351 RQuals.removeAddressSpace();
9352 }
9353 if (LQuals != RQuals)
9354 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9355
9356 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9357 // assignment.
9358 // The current behavior is similar to C++ lambdas. A block might be
9359 // assigned to a variable iff its return type and parameters are compatible
9360 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9361 // an assignment. Presumably it should behave in way that a function pointer
9362 // assignment does in C, so for each parameter and return type:
9363 // * CVR and address space of LHS should be a superset of CVR and address
9364 // space of RHS.
9365 // * unqualified types should be compatible.
9366 if (S.getLangOpts().OpenCL) {
9367 if (!S.Context.typesAreBlockPointerCompatible(
9368 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9369 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9370 return Sema::IncompatibleBlockPointer;
9371 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9372 return Sema::IncompatibleBlockPointer;
9373
9374 return ConvTy;
9375}
9376
9377/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9378/// for assignment compatibility.
9379static Sema::AssignConvertType
9380checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9381 QualType RHSType) {
9382 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", 9382, __extension__ __PRETTY_FUNCTION__
))
;
9383 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", 9383, __extension__ __PRETTY_FUNCTION__
))
;
9384
9385 if (LHSType->isObjCBuiltinType()) {
9386 // Class is not compatible with ObjC object pointers.
9387 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9388 !RHSType->isObjCQualifiedClassType())
9389 return Sema::IncompatiblePointer;
9390 return Sema::Compatible;
9391 }
9392 if (RHSType->isObjCBuiltinType()) {
9393 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9394 !LHSType->isObjCQualifiedClassType())
9395 return Sema::IncompatiblePointer;
9396 return Sema::Compatible;
9397 }
9398 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9399 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9400
9401 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9402 // make an exception for id<P>
9403 !LHSType->isObjCQualifiedIdType())
9404 return Sema::CompatiblePointerDiscardsQualifiers;
9405
9406 if (S.Context.typesAreCompatible(LHSType, RHSType))
9407 return Sema::Compatible;
9408 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9409 return Sema::IncompatibleObjCQualifiedId;
9410 return Sema::IncompatiblePointer;
9411}
9412
9413Sema::AssignConvertType
9414Sema::CheckAssignmentConstraints(SourceLocation Loc,
9415 QualType LHSType, QualType RHSType) {
9416 // Fake up an opaque expression. We don't actually care about what
9417 // cast operations are required, so if CheckAssignmentConstraints
9418 // adds casts to this they'll be wasted, but fortunately that doesn't
9419 // usually happen on valid code.
9420 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9421 ExprResult RHSPtr = &RHSExpr;
9422 CastKind K;
9423
9424 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9425}
9426
9427/// This helper function returns true if QT is a vector type that has element
9428/// type ElementType.
9429static bool isVector(QualType QT, QualType ElementType) {
9430 if (const VectorType *VT = QT->getAs<VectorType>())
9431 return VT->getElementType().getCanonicalType() == ElementType;
9432 return false;
9433}
9434
9435/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9436/// has code to accommodate several GCC extensions when type checking
9437/// pointers. Here are some objectionable examples that GCC considers warnings:
9438///
9439/// int a, *pint;
9440/// short *pshort;
9441/// struct foo *pfoo;
9442///
9443/// pint = pshort; // warning: assignment from incompatible pointer type
9444/// a = pint; // warning: assignment makes integer from pointer without a cast
9445/// pint = a; // warning: assignment makes pointer from integer without a cast
9446/// pint = pfoo; // warning: assignment from incompatible pointer type
9447///
9448/// As a result, the code for dealing with pointers is more complex than the
9449/// C99 spec dictates.
9450///
9451/// Sets 'Kind' for any result kind except Incompatible.
9452Sema::AssignConvertType
9453Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9454 CastKind &Kind, bool ConvertRHS) {
9455 QualType RHSType = RHS.get()->getType();
9456 QualType OrigLHSType = LHSType;
9457
9458 // Get canonical types. We're not formatting these types, just comparing
9459 // them.
9460 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9461 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9462
9463 // Common case: no conversion required.
9464 if (LHSType == RHSType) {
9465 Kind = CK_NoOp;
9466 return Compatible;
9467 }
9468
9469 // If the LHS has an __auto_type, there are no additional type constraints
9470 // to be worried about.
9471 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9472 if (AT->isGNUAutoType()) {
9473 Kind = CK_NoOp;
9474 return Compatible;
9475 }
9476 }
9477
9478 // If we have an atomic type, try a non-atomic assignment, then just add an
9479 // atomic qualification step.
9480 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9481 Sema::AssignConvertType result =
9482 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9483 if (result != Compatible)
9484 return result;
9485 if (Kind != CK_NoOp && ConvertRHS)
9486 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9487 Kind = CK_NonAtomicToAtomic;
9488 return Compatible;
9489 }
9490
9491 // If the left-hand side is a reference type, then we are in a
9492 // (rare!) case where we've allowed the use of references in C,
9493 // e.g., as a parameter type in a built-in function. In this case,
9494 // just make sure that the type referenced is compatible with the
9495 // right-hand side type. The caller is responsible for adjusting
9496 // LHSType so that the resulting expression does not have reference
9497 // type.
9498 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9499 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9500 Kind = CK_LValueBitCast;
9501 return Compatible;
9502 }
9503 return Incompatible;
9504 }
9505
9506 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9507 // to the same ExtVector type.
9508 if (LHSType->isExtVectorType()) {
9509 if (RHSType->isExtVectorType())
9510 return Incompatible;
9511 if (RHSType->isArithmeticType()) {
9512 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9513 if (ConvertRHS)
9514 RHS = prepareVectorSplat(LHSType, RHS.get());
9515 Kind = CK_VectorSplat;
9516 return Compatible;
9517 }
9518 }
9519
9520 // Conversions to or from vector type.
9521 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9522 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9523 // Allow assignments of an AltiVec vector type to an equivalent GCC
9524 // vector type and vice versa
9525 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9526 Kind = CK_BitCast;
9527 return Compatible;
9528 }
9529
9530 // If we are allowing lax vector conversions, and LHS and RHS are both
9531 // vectors, the total size only needs to be the same. This is a bitcast;
9532 // no bits are changed but the result type is different.
9533 if (isLaxVectorConversion(RHSType, LHSType)) {
9534 Kind = CK_BitCast;
9535 return IncompatibleVectors;
9536 }
9537 }
9538
9539 // When the RHS comes from another lax conversion (e.g. binops between
9540 // scalars and vectors) the result is canonicalized as a vector. When the
9541 // LHS is also a vector, the lax is allowed by the condition above. Handle
9542 // the case where LHS is a scalar.
9543 if (LHSType->isScalarType()) {
9544 const VectorType *VecType = RHSType->getAs<VectorType>();
9545 if (VecType && VecType->getNumElements() == 1 &&
9546 isLaxVectorConversion(RHSType, LHSType)) {
9547 ExprResult *VecExpr = &RHS;
9548 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9549 Kind = CK_BitCast;
9550 return Compatible;
9551 }
9552 }
9553
9554 // Allow assignments between fixed-length and sizeless SVE vectors.
9555 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9556 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9557 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9558 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9559 Kind = CK_BitCast;
9560 return Compatible;
9561 }
9562
9563 return Incompatible;
9564 }
9565
9566 // Diagnose attempts to convert between __ibm128, __float128 and long double
9567 // where such conversions currently can't be handled.
9568 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9569 return Incompatible;
9570
9571 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9572 // discards the imaginary part.
9573 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9574 !LHSType->getAs<ComplexType>())
9575 return Incompatible;
9576
9577 // Arithmetic conversions.
9578 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9579 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9580 if (ConvertRHS)
9581 Kind = PrepareScalarCast(RHS, LHSType);
9582 return Compatible;
9583 }
9584
9585 // Conversions to normal pointers.
9586 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9587 // U* -> T*
9588 if (isa<PointerType>(RHSType)) {
9589 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9590 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9591 if (AddrSpaceL != AddrSpaceR)
9592 Kind = CK_AddressSpaceConversion;
9593 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9594 Kind = CK_NoOp;
9595 else
9596 Kind = CK_BitCast;
9597 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9598 }
9599
9600 // int -> T*
9601 if (RHSType->isIntegerType()) {
9602 Kind = CK_IntegralToPointer; // FIXME: null?
9603 return IntToPointer;
9604 }
9605
9606 // C pointers are not compatible with ObjC object pointers,
9607 // with two exceptions:
9608 if (isa<ObjCObjectPointerType>(RHSType)) {
9609 // - conversions to void*
9610 if (LHSPointer->getPointeeType()->isVoidType()) {
9611 Kind = CK_BitCast;
9612 return Compatible;
9613 }
9614
9615 // - conversions from 'Class' to the redefinition type
9616 if (RHSType->isObjCClassType() &&
9617 Context.hasSameType(LHSType,
9618 Context.getObjCClassRedefinitionType())) {
9619 Kind = CK_BitCast;
9620 return Compatible;
9621 }
9622
9623 Kind = CK_BitCast;
9624 return IncompatiblePointer;
9625 }
9626
9627 // U^ -> void*
9628 if (RHSType->getAs<BlockPointerType>()) {
9629 if (LHSPointer->getPointeeType()->isVoidType()) {
9630 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9631 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9632 ->getPointeeType()
9633 .getAddressSpace();
9634 Kind =
9635 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9636 return Compatible;
9637 }
9638 }
9639
9640 return Incompatible;
9641 }
9642
9643 // Conversions to block pointers.
9644 if (isa<BlockPointerType>(LHSType)) {
9645 // U^ -> T^
9646 if (RHSType->isBlockPointerType()) {
9647 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9648 ->getPointeeType()
9649 .getAddressSpace();
9650 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9651 ->getPointeeType()
9652 .getAddressSpace();
9653 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9654 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9655 }
9656
9657 // int or null -> T^
9658 if (RHSType->isIntegerType()) {
9659 Kind = CK_IntegralToPointer; // FIXME: null
9660 return IntToBlockPointer;
9661 }
9662
9663 // id -> T^
9664 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9665 Kind = CK_AnyPointerToBlockPointerCast;
9666 return Compatible;
9667 }
9668
9669 // void* -> T^
9670 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9671 if (RHSPT->getPointeeType()->isVoidType()) {
9672 Kind = CK_AnyPointerToBlockPointerCast;
9673 return Compatible;
9674 }
9675
9676 return Incompatible;
9677 }
9678
9679 // Conversions to Objective-C pointers.
9680 if (isa<ObjCObjectPointerType>(LHSType)) {
9681 // A* -> B*
9682 if (RHSType->isObjCObjectPointerType()) {
9683 Kind = CK_BitCast;
9684 Sema::AssignConvertType result =
9685 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9686 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9687 result == Compatible &&
9688 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9689 result = IncompatibleObjCWeakRef;
9690 return result;
9691 }
9692
9693 // int or null -> A*
9694 if (RHSType->isIntegerType()) {
9695 Kind = CK_IntegralToPointer; // FIXME: null
9696 return IntToPointer;
9697 }
9698
9699 // In general, C pointers are not compatible with ObjC object pointers,
9700 // with two exceptions:
9701 if (isa<PointerType>(RHSType)) {
9702 Kind = CK_CPointerToObjCPointerCast;
9703
9704 // - conversions from 'void*'
9705 if (RHSType->isVoidPointerType()) {
9706 return Compatible;
9707 }
9708
9709 // - conversions to 'Class' from its redefinition type
9710 if (LHSType->isObjCClassType() &&
9711 Context.hasSameType(RHSType,
9712 Context.getObjCClassRedefinitionType())) {
9713 return Compatible;
9714 }
9715
9716 return IncompatiblePointer;
9717 }
9718
9719 // Only under strict condition T^ is compatible with an Objective-C pointer.
9720 if (RHSType->isBlockPointerType() &&
9721 LHSType->isBlockCompatibleObjCPointerType(Context)) {
9722 if (ConvertRHS)
9723 maybeExtendBlockObject(RHS);
9724 Kind = CK_BlockPointerToObjCPointerCast;
9725 return Compatible;
9726 }
9727
9728 return Incompatible;
9729 }
9730
9731 // Conversions from pointers that are not covered by the above.
9732 if (isa<PointerType>(RHSType)) {
9733 // T* -> _Bool
9734 if (LHSType == Context.BoolTy) {
9735 Kind = CK_PointerToBoolean;
9736 return Compatible;
9737 }
9738
9739 // T* -> int
9740 if (LHSType->isIntegerType()) {
9741 Kind = CK_PointerToIntegral;
9742 return PointerToInt;
9743 }
9744
9745 return Incompatible;
9746 }
9747
9748 // Conversions from Objective-C pointers that are not covered by the above.
9749 if (isa<ObjCObjectPointerType>(RHSType)) {
9750 // T* -> _Bool
9751 if (LHSType == Context.BoolTy) {
9752 Kind = CK_PointerToBoolean;
9753 return Compatible;
9754 }
9755
9756 // T* -> int
9757 if (LHSType->isIntegerType()) {
9758 Kind = CK_PointerToIntegral;
9759 return PointerToInt;
9760 }
9761
9762 return Incompatible;
9763 }
9764
9765 // struct A -> struct B
9766 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9767 if (Context.typesAreCompatible(LHSType, RHSType)) {
9768 Kind = CK_NoOp;
9769 return Compatible;
9770 }
9771 }
9772
9773 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9774 Kind = CK_IntToOCLSampler;
9775 return Compatible;
9776 }
9777
9778 return Incompatible;
9779}
9780
9781/// Constructs a transparent union from an expression that is
9782/// used to initialize the transparent union.
9783static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9784 ExprResult &EResult, QualType UnionType,
9785 FieldDecl *Field) {
9786 // Build an initializer list that designates the appropriate member
9787 // of the transparent union.
9788 Expr *E = EResult.get();
9789 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9790 E, SourceLocation());
9791 Initializer->setType(UnionType);
9792 Initializer->setInitializedFieldInUnion(Field);
9793
9794 // Build a compound literal constructing a value of the transparent
9795 // union type from this initializer list.
9796 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9797 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9798 VK_PRValue, Initializer, false);
9799}
9800
9801Sema::AssignConvertType
9802Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9803 ExprResult &RHS) {
9804 QualType RHSType = RHS.get()->getType();
9805
9806 // If the ArgType is a Union type, we want to handle a potential
9807 // transparent_union GCC extension.
9808 const RecordType *UT = ArgType->getAsUnionType();
9809 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9810 return Incompatible;
9811
9812 // The field to initialize within the transparent union.
9813 RecordDecl *UD = UT->getDecl();
9814 FieldDecl *InitField = nullptr;
9815 // It's compatible if the expression matches any of the fields.
9816 for (auto *it : UD->fields()) {
9817 if (it->getType()->isPointerType()) {
9818 // If the transparent union contains a pointer type, we allow:
9819 // 1) void pointer
9820 // 2) null pointer constant
9821 if (RHSType->isPointerType())
9822 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9823 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9824 InitField = it;
9825 break;
9826 }
9827
9828 if (RHS.get()->isNullPointerConstant(Context,
9829 Expr::NPC_ValueDependentIsNull)) {
9830 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9831 CK_NullToPointer);
9832 InitField = it;
9833 break;
9834 }
9835 }
9836
9837 CastKind Kind;
9838 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9839 == Compatible) {
9840 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9841 InitField = it;
9842 break;
9843 }
9844 }
9845
9846 if (!InitField)
9847 return Incompatible;
9848
9849 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9850 return Compatible;
9851}
9852
9853Sema::AssignConvertType
9854Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9855 bool Diagnose,
9856 bool DiagnoseCFAudited,
9857 bool ConvertRHS) {
9858 // We need to be able to tell the caller whether we diagnosed a problem, if
9859 // they ask us to issue diagnostics.
9860 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", 9860, __extension__ __PRETTY_FUNCTION__
))
;
9861
9862 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9863 // we can't avoid *all* modifications at the moment, so we need some somewhere
9864 // to put the updated value.
9865 ExprResult LocalRHS = CallerRHS;
9866 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9867
9868 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9869 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9870 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9871 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9872 Diag(RHS.get()->getExprLoc(),
9873 diag::warn_noderef_to_dereferenceable_pointer)
9874 << RHS.get()->getSourceRange();
9875 }
9876 }
9877 }
9878
9879 if (getLangOpts().CPlusPlus) {
9880 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9881 // C++ 5.17p3: If the left operand is not of class type, the
9882 // expression is implicitly converted (C++ 4) to the
9883 // cv-unqualified type of the left operand.
9884 QualType RHSType = RHS.get()->getType();
9885 if (Diagnose) {
9886 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9887 AA_Assigning);
9888 } else {
9889 ImplicitConversionSequence ICS =
9890 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9891 /*SuppressUserConversions=*/false,
9892 AllowedExplicit::None,
9893 /*InOverloadResolution=*/false,
9894 /*CStyle=*/false,
9895 /*AllowObjCWritebackConversion=*/false);
9896 if (ICS.isFailure())
9897 return Incompatible;
9898 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9899 ICS, AA_Assigning);
9900 }
9901 if (RHS.isInvalid())
9902 return Incompatible;
9903 Sema::AssignConvertType result = Compatible;
9904 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9905 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9906 result = IncompatibleObjCWeakRef;
9907 return result;
9908 }
9909
9910 // FIXME: Currently, we fall through and treat C++ classes like C
9911 // structures.
9912 // FIXME: We also fall through for atomics; not sure what should
9913 // happen there, though.
9914 } else if (RHS.get()->getType() == Context.OverloadTy) {
9915 // As a set of extensions to C, we support overloading on functions. These
9916 // functions need to be resolved here.
9917 DeclAccessPair DAP;
9918 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9919 RHS.get(), LHSType, /*Complain=*/false, DAP))
9920 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9921 else
9922 return Incompatible;
9923 }
9924
9925 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9926 // a null pointer constant.
9927 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9928 LHSType->isBlockPointerType()) &&
9929 RHS.get()->isNullPointerConstant(Context,
9930 Expr::NPC_ValueDependentIsNull)) {
9931 if (Diagnose || ConvertRHS) {
9932 CastKind Kind;
9933 CXXCastPath Path;
9934 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9935 /*IgnoreBaseAccess=*/false, Diagnose);
9936 if (ConvertRHS)
9937 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9938 }
9939 return Compatible;
9940 }
9941
9942 // OpenCL queue_t type assignment.
9943 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9944 Context, Expr::NPC_ValueDependentIsNull)) {
9945 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9946 return Compatible;
9947 }
9948
9949 // This check seems unnatural, however it is necessary to ensure the proper
9950 // conversion of functions/arrays. If the conversion were done for all
9951 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9952 // expressions that suppress this implicit conversion (&, sizeof).
9953 //
9954 // Suppress this for references: C++ 8.5.3p5.
9955 if (!LHSType->isReferenceType()) {
9956 // FIXME: We potentially allocate here even if ConvertRHS is false.
9957 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9958 if (RHS.isInvalid())
9959 return Incompatible;
9960 }
9961 CastKind Kind;
9962 Sema::AssignConvertType result =
9963 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9964
9965 // C99 6.5.16.1p2: The value of the right operand is converted to the
9966 // type of the assignment expression.
9967 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9968 // so that we can use references in built-in functions even in C.
9969 // The getNonReferenceType() call makes sure that the resulting expression
9970 // does not have reference type.
9971 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9972 QualType Ty = LHSType.getNonLValueExprType(Context);
9973 Expr *E = RHS.get();
9974
9975 // Check for various Objective-C errors. If we are not reporting
9976 // diagnostics and just checking for errors, e.g., during overload
9977 // resolution, return Incompatible to indicate the failure.
9978 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9979 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9980 Diagnose, DiagnoseCFAudited) != ACR_okay) {
9981 if (!Diagnose)
9982 return Incompatible;
9983 }
9984 if (getLangOpts().ObjC &&
9985 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9986 E->getType(), E, Diagnose) ||
9987 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9988 if (!Diagnose)
9989 return Incompatible;
9990 // Replace the expression with a corrected version and continue so we
9991 // can find further errors.
9992 RHS = E;
9993 return Compatible;
9994 }
9995
9996 if (ConvertRHS)
9997 RHS = ImpCastExprToType(E, Ty, Kind);
9998 }
9999
10000 return result;
10001}
10002
10003namespace {
10004/// The original operand to an operator, prior to the application of the usual
10005/// arithmetic conversions and converting the arguments of a builtin operator
10006/// candidate.
10007struct OriginalOperand {
10008 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10009 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10010 Op = MTE->getSubExpr();
10011 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10012 Op = BTE->getSubExpr();
10013 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10014 Orig = ICE->getSubExprAsWritten();
10015 Conversion = ICE->getConversionFunction();
10016 }
10017 }
10018
10019 QualType getType() const { return Orig->getType(); }
10020
10021 Expr *Orig;
10022 NamedDecl *Conversion;
10023};
10024}
10025
10026QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10027 ExprResult &RHS) {
10028 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10029
10030 Diag(Loc, diag::err_typecheck_invalid_operands)
10031 << OrigLHS.getType() << OrigRHS.getType()
10032 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10033
10034 // If a user-defined conversion was applied to either of the operands prior
10035 // to applying the built-in operator rules, tell the user about it.
10036 if (OrigLHS.Conversion) {
10037 Diag(OrigLHS.Conversion->getLocation(),
10038 diag::note_typecheck_invalid_operands_converted)
10039 << 0 << LHS.get()->getType();
10040 }
10041 if (OrigRHS.Conversion) {
10042 Diag(OrigRHS.Conversion->getLocation(),
10043 diag::note_typecheck_invalid_operands_converted)
10044 << 1 << RHS.get()->getType();
10045 }
10046
10047 return QualType();
10048}
10049
10050// Diagnose cases where a scalar was implicitly converted to a vector and
10051// diagnose the underlying types. Otherwise, diagnose the error
10052// as invalid vector logical operands for non-C++ cases.
10053QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10054 ExprResult &RHS) {
10055 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10056 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10057
10058 bool LHSNatVec = LHSType->isVectorType();
10059 bool RHSNatVec = RHSType->isVectorType();
10060
10061 if (!(LHSNatVec && RHSNatVec)) {
10062 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10063 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10064 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10065 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10066 << Vector->getSourceRange();
10067 return QualType();
10068 }
10069
10070 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10071 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10072 << RHS.get()->getSourceRange();
10073
10074 return QualType();
10075}
10076
10077/// Try to convert a value of non-vector type to a vector type by converting
10078/// the type to the element type of the vector and then performing a splat.
10079/// If the language is OpenCL, we only use conversions that promote scalar
10080/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10081/// for float->int.
10082///
10083/// OpenCL V2.0 6.2.6.p2:
10084/// An error shall occur if any scalar operand type has greater rank
10085/// than the type of the vector element.
10086///
10087/// \param scalar - if non-null, actually perform the conversions
10088/// \return true if the operation fails (but without diagnosing the failure)
10089static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10090 QualType scalarTy,
10091 QualType vectorEltTy,
10092 QualType vectorTy,
10093 unsigned &DiagID) {
10094 // The conversion to apply to the scalar before splatting it,
10095 // if necessary.
10096 CastKind scalarCast = CK_NoOp;
10097
10098 if (vectorEltTy->isIntegralType(S.Context)) {
10099 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10100 (scalarTy->isIntegerType() &&
10101 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10102 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10103 return true;
10104 }
10105 if (!scalarTy->isIntegralType(S.Context))
10106 return true;
10107 scalarCast = CK_IntegralCast;
10108 } else if (vectorEltTy->isRealFloatingType()) {
10109 if (scalarTy->isRealFloatingType()) {
10110 if (S.getLangOpts().OpenCL &&
10111 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10112 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10113 return true;
10114 }
10115 scalarCast = CK_FloatingCast;
10116 }
10117 else if (scalarTy->isIntegralType(S.Context))
10118 scalarCast = CK_IntegralToFloating;
10119 else
10120 return true;
10121 } else {
10122 return true;
10123 }
10124
10125 // Adjust scalar if desired.
10126 if (scalar) {
10127 if (scalarCast != CK_NoOp)
10128 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10129 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10130 }
10131 return false;
10132}
10133
10134/// Convert vector E to a vector with the same number of elements but different
10135/// element type.
10136static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10137 const auto *VecTy = E->getType()->getAs<VectorType>();
10138 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", 10138, __extension__ __PRETTY_FUNCTION__
))
;
10139 QualType NewVecTy =
10140 VecTy->isExtVectorType()
10141 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10142 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10143 VecTy->getVectorKind());
10144
10145 // Look through the implicit cast. Return the subexpression if its type is
10146 // NewVecTy.
10147 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10148 if (ICE->getSubExpr()->getType() == NewVecTy)
10149 return ICE->getSubExpr();
10150
10151 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10152 return S.ImpCastExprToType(E, NewVecTy, Cast);
10153}
10154
10155/// Test if a (constant) integer Int can be casted to another integer type
10156/// IntTy without losing precision.
10157static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10158 QualType OtherIntTy) {
10159 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10160
10161 // Reject cases where the value of the Int is unknown as that would
10162 // possibly cause truncation, but accept cases where the scalar can be
10163 // demoted without loss of precision.
10164 Expr::EvalResult EVResult;
10165 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10166 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10167 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10168 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10169
10170 if (CstInt) {
10171 // If the scalar is constant and is of a higher order and has more active
10172 // bits that the vector element type, reject it.
10173 llvm::APSInt Result = EVResult.Val.getInt();
10174 unsigned NumBits = IntSigned
10175 ? (Result.isNegative() ? Result.getMinSignedBits()
10176 : Result.getActiveBits())
10177 : Result.getActiveBits();
10178 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10179 return true;
10180
10181 // If the signedness of the scalar type and the vector element type
10182 // differs and the number of bits is greater than that of the vector
10183 // element reject it.
10184 return (IntSigned != OtherIntSigned &&
10185 NumBits > S.Context.getIntWidth(OtherIntTy));
10186 }
10187
10188 // Reject cases where the value of the scalar is not constant and it's
10189 // order is greater than that of the vector element type.
10190 return (Order < 0);
10191}
10192
10193/// Test if a (constant) integer Int can be casted to floating point type
10194/// FloatTy without losing precision.
10195static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10196 QualType FloatTy) {
10197 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10198
10199 // Determine if the integer constant can be expressed as a floating point
10200 // number of the appropriate type.
10201 Expr::EvalResult EVResult;
10202 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10203
10204 uint64_t Bits = 0;
10205 if (CstInt) {
10206 // Reject constants that would be truncated if they were converted to
10207 // the floating point type. Test by simple to/from conversion.
10208 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10209 // could be avoided if there was a convertFromAPInt method
10210 // which could signal back if implicit truncation occurred.
10211 llvm::APSInt Result = EVResult.Val.getInt();
10212 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10213 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10214 llvm::APFloat::rmTowardZero);
10215 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10216 !IntTy->hasSignedIntegerRepresentation());
10217 bool Ignored = false;
10218 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10219 &Ignored);
10220 if (Result != ConvertBack)
10221 return true;
10222 } else {
10223 // Reject types that cannot be fully encoded into the mantissa of
10224 // the float.
10225 Bits = S.Context.getTypeSize(IntTy);
10226 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10227 S.Context.getFloatTypeSemantics(FloatTy));
10228 if (Bits > FloatPrec)
10229 return true;
10230 }
10231
10232 return false;
10233}
10234
10235/// Attempt to convert and splat Scalar into a vector whose types matches
10236/// Vector following GCC conversion rules. The rule is that implicit
10237/// conversion can occur when Scalar can be casted to match Vector's element
10238/// type without causing truncation of Scalar.
10239static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10240 ExprResult *Vector) {
10241 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10242 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10243 const auto *VT = VectorTy->castAs<VectorType>();
10244
10245 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", 10246, __extension__ __PRETTY_FUNCTION__
))
10246 "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", 10246, __extension__ __PRETTY_FUNCTION__
))
;
10247
10248 QualType VectorEltTy = VT->getElementType();
10249
10250 // Reject cases where the vector element type or the scalar element type are
10251 // not integral or floating point types.
10252 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10253 return true;
10254
10255 // The conversion to apply to the scalar before splatting it,
10256 // if necessary.
10257 CastKind ScalarCast = CK_NoOp;
10258
10259 // Accept cases where the vector elements are integers and the scalar is
10260 // an integer.
10261 // FIXME: Notionally if the scalar was a floating point value with a precise
10262 // integral representation, we could cast it to an appropriate integer
10263 // type and then perform the rest of the checks here. GCC will perform
10264 // this conversion in some cases as determined by the input language.
10265 // We should accept it on a language independent basis.
10266 if (VectorEltTy->isIntegralType(S.Context) &&
10267 ScalarTy->isIntegralType(S.Context) &&
10268 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10269
10270 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10271 return true;
10272
10273 ScalarCast = CK_IntegralCast;
10274 } else if (VectorEltTy->isIntegralType(S.Context) &&
10275 ScalarTy->isRealFloatingType()) {
10276 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10277 ScalarCast = CK_FloatingToIntegral;
10278 else
10279 return true;
10280 } else if (VectorEltTy->isRealFloatingType()) {
10281 if (ScalarTy->isRealFloatingType()) {
10282
10283 // Reject cases where the scalar type is not a constant and has a higher
10284 // Order than the vector element type.
10285 llvm::APFloat Result(0.0);
10286
10287 // Determine whether this is a constant scalar. In the event that the
10288 // value is dependent (and thus cannot be evaluated by the constant
10289 // evaluator), skip the evaluation. This will then diagnose once the
10290 // expression is instantiated.
10291 bool CstScalar = Scalar->get()->isValueDependent() ||
10292 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10293 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10294 if (!CstScalar && Order < 0)
10295 return true;
10296
10297 // If the scalar cannot be safely casted to the vector element type,
10298 // reject it.
10299 if (CstScalar) {
10300 bool Truncated = false;
10301 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10302 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10303 if (Truncated)
10304 return true;
10305 }
10306
10307 ScalarCast = CK_FloatingCast;
10308 } else if (ScalarTy->isIntegralType(S.Context)) {
10309 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10310 return true;
10311
10312 ScalarCast = CK_IntegralToFloating;
10313 } else
10314 return true;
10315 } else if (ScalarTy->isEnumeralType())
10316 return true;
10317
10318 // Adjust scalar if desired.
10319 if (Scalar) {
10320 if (ScalarCast != CK_NoOp)
10321 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10322 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10323 }
10324 return false;
10325}
10326
10327QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10328 SourceLocation Loc, bool IsCompAssign,
10329 bool AllowBothBool,
10330 bool AllowBoolConversions,
10331 bool AllowBoolOperation,
10332 bool ReportInvalid) {
10333 if (!IsCompAssign) {
10334 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10335 if (LHS.isInvalid())
10336 return QualType();
10337 }
10338 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10339 if (RHS.isInvalid())
10340 return QualType();
10341
10342 // For conversion purposes, we ignore any qualifiers.
10343 // For example, "const float" and "float" are equivalent.
10344 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10345 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10346
10347 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10348 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10349 assert(LHSVecType || RHSVecType)(static_cast <bool> (LHSVecType || RHSVecType) ? void (
0) : __assert_fail ("LHSVecType || RHSVecType", "clang/lib/Sema/SemaExpr.cpp"
, 10349, __extension__ __PRETTY_FUNCTION__))
;
10350
10351 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10352 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10353 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10354
10355 // AltiVec-style "vector bool op vector bool" combinations are allowed
10356 // for some operators but not others.
10357 if (!AllowBothBool &&
10358 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10359 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10360 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10361
10362 // This operation may not be performed on boolean vectors.
10363 if (!AllowBoolOperation &&
10364 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10365 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10366
10367 // If the vector types are identical, return.
10368 if (Context.hasSameType(LHSType, RHSType))
10369 return LHSType;
10370
10371 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10372 if (LHSVecType && RHSVecType &&
10373 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10374 if (isa<ExtVectorType>(LHSVecType)) {
10375 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10376 return LHSType;
10377 }
10378
10379 if (!IsCompAssign)
10380 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10381 return RHSType;
10382 }
10383
10384 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10385 // can be mixed, with the result being the non-bool type. The non-bool
10386 // operand must have integer element type.
10387 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10388 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10389 (Context.getTypeSize(LHSVecType->getElementType()) ==
10390 Context.getTypeSize(RHSVecType->getElementType()))) {
10391 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10392 LHSVecType->getElementType()->isIntegerType() &&
10393 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10394 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10395 return LHSType;
10396 }
10397 if (!IsCompAssign &&
10398 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10399 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10400 RHSVecType->getElementType()->isIntegerType()) {
10401 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10402 return RHSType;
10403 }
10404 }
10405
10406 // Expressions containing fixed-length and sizeless SVE vectors are invalid
10407 // since the ambiguity can affect the ABI.
10408 auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10409 const VectorType *VecType = SecondType->getAs<VectorType>();
10410 return FirstType->isSizelessBuiltinType() && VecType &&
10411 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10412 VecType->getVectorKind() ==
10413 VectorType::SveFixedLengthPredicateVector);
10414 };
10415
10416 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10417 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10418 return QualType();
10419 }
10420
10421 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10422 // since the ambiguity can affect the ABI.
10423 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10424 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10425 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10426
10427 if (FirstVecType && SecondVecType)
10428 return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10429 (SecondVecType->getVectorKind() ==
10430 VectorType::SveFixedLengthDataVector ||
10431 SecondVecType->getVectorKind() ==
10432 VectorType::SveFixedLengthPredicateVector);
10433
10434 return FirstType->isSizelessBuiltinType() && SecondVecType &&
10435 SecondVecType->getVectorKind() == VectorType::GenericVector;
10436 };
10437
10438 if (IsSveGnuConversion(LHSType, RHSType) ||
10439 IsSveGnuConversion(RHSType, LHSType)) {
10440 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10441 return QualType();
10442 }
10443
10444 // If there's a vector type and a scalar, try to convert the scalar to
10445 // the vector element type and splat.
10446 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10447 if (!RHSVecType) {
10448 if (isa<ExtVectorType>(LHSVecType)) {
10449 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10450 LHSVecType->getElementType(), LHSType,
10451 DiagID))
10452 return LHSType;
10453 } else {
10454 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10455 return LHSType;
10456 }
10457 }
10458 if (!LHSVecType) {
10459 if (isa<ExtVectorType>(RHSVecType)) {
10460 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10461 LHSType, RHSVecType->getElementType(),
10462 RHSType, DiagID))
10463 return RHSType;
10464 } else {
10465 if (LHS.get()->isLValue() ||
10466 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10467 return RHSType;
10468 }
10469 }
10470
10471 // FIXME: The code below also handles conversion between vectors and
10472 // non-scalars, we should break this down into fine grained specific checks
10473 // and emit proper diagnostics.
10474 QualType VecType = LHSVecType ? LHSType : RHSType;
10475 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10476 QualType OtherType = LHSVecType ? RHSType : LHSType;
10477 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10478 if (isLaxVectorConversion(OtherType, VecType)) {
10479 // If we're allowing lax vector conversions, only the total (data) size
10480 // needs to be the same. For non compound assignment, if one of the types is
10481 // scalar, the result is always the vector type.
10482 if (!IsCompAssign) {
10483 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10484 return VecType;
10485 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10486 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10487 // type. Note that this is already done by non-compound assignments in
10488 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10489 // <1 x T> -> T. The result is also a vector type.
10490 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10491 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10492 ExprResult *RHSExpr = &RHS;
10493 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10494 return VecType;
10495 }
10496 }
10497
10498 // Okay, the expression is invalid.
10499
10500 // If there's a non-vector, non-real operand, diagnose that.
10501 if ((!RHSVecType && !RHSType->isRealType()) ||
10502 (!LHSVecType && !LHSType->isRealType())) {
10503 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10504 << LHSType << RHSType
10505 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10506 return QualType();
10507 }
10508
10509 // OpenCL V1.1 6.2.6.p1:
10510 // If the operands are of more than one vector type, then an error shall
10511 // occur. Implicit conversions between vector types are not permitted, per
10512 // section 6.2.1.
10513 if (getLangOpts().OpenCL &&
10514 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10515 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10516 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10517 << RHSType;
10518 return QualType();
10519 }
10520
10521
10522 // If there is a vector type that is not a ExtVector and a scalar, we reach
10523 // this point if scalar could not be converted to the vector's element type
10524 // without truncation.
10525 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10526 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10527 QualType Scalar = LHSVecType ? RHSType : LHSType;
10528 QualType Vector = LHSVecType ? LHSType : RHSType;
10529 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10530 Diag(Loc,
10531 diag::err_typecheck_vector_not_convertable_implict_truncation)
10532 << ScalarOrVector << Scalar << Vector;
10533
10534 return QualType();
10535 }
10536
10537 // Otherwise, use the generic diagnostic.
10538 Diag(Loc, DiagID)
10539 << LHSType << RHSType
10540 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10541 return QualType();
10542}
10543
10544QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10545 SourceLocation Loc,
10546 bool IsCompAssign,
10547 ArithConvKind OperationKind) {
10548 if (!IsCompAssign) {
10549 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10550 if (LHS.isInvalid())
10551 return QualType();
10552 }
10553 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10554 if (RHS.isInvalid())
10555 return QualType();
10556
10557 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10558 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10559
10560 unsigned DiagID = diag::err_typecheck_invalid_operands;
10561 if ((OperationKind == ACK_Arithmetic) &&
10562 (LHSType->castAs<BuiltinType>()->isSVEBool() ||
10563 RHSType->castAs<BuiltinType>()->isSVEBool())) {
10564 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10565 << RHS.get()->getSourceRange();
10566 return QualType();
10567 }
10568
10569 if (Context.hasSameType(LHSType, RHSType))
10570 return LHSType;
10571
10572 auto tryScalableVectorConvert = [this](ExprResult *Src, QualType SrcType,
10573 QualType DestType) {
10574 const QualType DestBaseType = DestType->getSveEltType(Context);
10575 if (DestBaseType->getUnqualifiedDesugaredType() ==
10576 SrcType->getUnqualifiedDesugaredType()) {
10577 unsigned DiagID = diag::err_typecheck_invalid_operands;
10578 if (!tryVectorConvertAndSplat(*this, Src, SrcType, DestBaseType, DestType,
10579 DiagID))
10580 return DestType;
10581 }
10582 return QualType();
10583 };
10584
10585 if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
10586 auto DestType = tryScalableVectorConvert(&RHS, RHSType, LHSType);
10587 if (DestType == QualType())
10588 return InvalidOperands(Loc, LHS, RHS);
10589 return DestType;
10590 }
10591
10592 if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
10593 auto DestType = tryScalableVectorConvert((IsCompAssign ? nullptr : &LHS),
10594 LHSType, RHSType);
10595 if (DestType == QualType())
10596 return InvalidOperands(Loc, LHS, RHS);
10597 return DestType;
10598 }
10599
10600 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10601 << RHS.get()->getSourceRange();
10602 return QualType();
10603}
10604
10605// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10606// expression. These are mainly cases where the null pointer is used as an
10607// integer instead of a pointer.
10608static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10609 SourceLocation Loc, bool IsCompare) {
10610 // The canonical way to check for a GNU null is with isNullPointerConstant,
10611 // but we use a bit of a hack here for speed; this is a relatively
10612 // hot path, and isNullPointerConstant is slow.
10613 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10614 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10615
10616 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10617
10618 // Avoid analyzing cases where the result will either be invalid (and
10619 // diagnosed as such) or entirely valid and not something to warn about.
10620 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10621 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10622 return;
10623
10624 // Comparison operations would not make sense with a null pointer no matter
10625 // what the other expression is.
10626 if (!IsCompare) {
10627 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10628 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10629 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10630 return;
10631 }
10632
10633 // The rest of the operations only make sense with a null pointer
10634 // if the other expression is a pointer.
10635 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10636 NonNullType->canDecayToPointerType())
10637 return;
10638
10639 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10640 << LHSNull /* LHS is NULL */ << NonNullType
10641 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10642}
10643
10644static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10645 SourceLocation Loc) {
10646 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10647 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10648 if (!LUE || !RUE)
10649 return;
10650 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10651 RUE->getKind() != UETT_SizeOf)
10652 return;
10653
10654 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10655 QualType LHSTy = LHSArg->getType();
10656 QualType RHSTy;
10657
10658 if (RUE->isArgumentType())
10659 RHSTy = RUE->getArgumentType().getNonReferenceType();
10660 else
10661 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10662
10663 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10664 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10665 return;
10666
10667 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10668 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10669 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10670 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10671 << LHSArgDecl;
10672 }
10673 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10674 QualType ArrayElemTy = ArrayTy->getElementType();
10675 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10676 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10677 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10678 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10679 return;
10680 S.Diag(Loc, diag::warn_division_sizeof_array)
10681 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10682 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10683 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10684 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10685 << LHSArgDecl;
10686 }
10687
10688 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10689 }
10690}
10691
10692static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10693 ExprResult &RHS,
10694 SourceLocation Loc, bool IsDiv) {
10695 // Check for division/remainder by zero.
10696 Expr::EvalResult RHSValue;
10697 if (!RHS.get()->isValueDependent() &&
10698 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10699 RHSValue.Val.getInt() == 0)
10700 S.DiagRuntimeBehavior(Loc, RHS.get(),
10701 S.PDiag(diag::warn_remainder_division_by_zero)
10702 << IsDiv << RHS.get()->getSourceRange());
10703}
10704
10705QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10706 SourceLocation Loc,
10707 bool IsCompAssign, bool IsDiv) {
10708 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10709
10710 QualType LHSTy = LHS.get()->getType();
10711 QualType RHSTy = RHS.get()->getType();
10712 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10713 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10714 /*AllowBothBool*/ getLangOpts().AltiVec,
10715 /*AllowBoolConversions*/ false,
10716 /*AllowBooleanOperation*/ false,
10717 /*ReportInvalid*/ true);
10718 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
10719 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10720 ACK_Arithmetic);
10721 if (!IsDiv &&
10722 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10723 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10724 // For division, only matrix-by-scalar is supported. Other combinations with
10725 // matrix types are invalid.
10726 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10727 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10728
10729 QualType compType = UsualArithmeticConversions(
10730 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10731 if (LHS.isInvalid() || RHS.isInvalid())
10732 return QualType();
10733
10734
10735 if (compType.isNull() || !compType->isArithmeticType())
10736 return InvalidOperands(Loc, LHS, RHS);
10737 if (IsDiv) {
10738 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10739 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10740 }
10741 return compType;
10742}
10743
10744QualType Sema::CheckRemainderOperands(
10745 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10746 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10747
10748 if (LHS.get()->getType()->isVectorType() ||
10749 RHS.get()->getType()->isVectorType()) {
10750 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10751 RHS.get()->getType()->hasIntegerRepresentation())
10752 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10753 /*AllowBothBool*/ getLangOpts().AltiVec,
10754 /*AllowBoolConversions*/ false,
10755 /*AllowBooleanOperation*/ false,
10756 /*ReportInvalid*/ true);
10757 return InvalidOperands(Loc, LHS, RHS);
10758 }
10759
10760 if (LHS.get()->getType()->isVLSTBuiltinType() ||
10761 RHS.get()->getType()->isVLSTBuiltinType()) {
10762 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10763 RHS.get()->getType()->hasIntegerRepresentation())
10764 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10765 ACK_Arithmetic);
10766
10767 return InvalidOperands(Loc, LHS, RHS);
10768 }
10769
10770 QualType compType = UsualArithmeticConversions(
10771 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10772 if (LHS.isInvalid() || RHS.isInvalid())
10773 return QualType();
10774
10775 if (compType.isNull() || !compType->isIntegerType())
10776 return InvalidOperands(Loc, LHS, RHS);
10777 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10778 return compType;
10779}
10780
10781/// Diagnose invalid arithmetic on two void pointers.
10782static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10783 Expr *LHSExpr, Expr *RHSExpr) {
10784 S.Diag(Loc, S.getLangOpts().CPlusPlus
10785 ? diag::err_typecheck_pointer_arith_void_type
10786 : diag::ext_gnu_void_ptr)
10787 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10788 << RHSExpr->getSourceRange();
10789}
10790
10791/// Diagnose invalid arithmetic on a void pointer.
10792static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10793 Expr *Pointer) {
10794 S.Diag(Loc, S.getLangOpts().CPlusPlus
10795 ? diag::err_typecheck_pointer_arith_void_type
10796 : diag::ext_gnu_void_ptr)
10797 << 0 /* one pointer */ << Pointer->getSourceRange();
10798}
10799
10800/// Diagnose invalid arithmetic on a null pointer.
10801///
10802/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10803/// idiom, which we recognize as a GNU extension.
10804///
10805static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10806 Expr *Pointer, bool IsGNUIdiom) {
10807 if (IsGNUIdiom)
10808 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10809 << Pointer->getSourceRange();
10810 else
10811 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10812 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10813}
10814
10815/// Diagnose invalid subraction on a null pointer.
10816///
10817static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10818 Expr *Pointer, bool BothNull) {
10819 // Null - null is valid in C++ [expr.add]p7
10820 if (BothNull && S.getLangOpts().CPlusPlus)
10821 return;
10822
10823 // Is this s a macro from a system header?
10824 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10825 return;
10826
10827 S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10828 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10829}
10830
10831/// Diagnose invalid arithmetic on two function pointers.
10832static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10833 Expr *LHS, Expr *RHS) {
10834 assert(LHS->getType()->isAnyPointerType())(static_cast <bool> (LHS->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("LHS->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 10834, __extension__ __PRETTY_FUNCTION__
))
;
10835 assert(RHS->getType()->isAnyPointerType())(static_cast <bool> (RHS->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("RHS->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 10835, __extension__ __PRETTY_FUNCTION__
))
;
10836 S.Diag(Loc, S.getLangOpts().CPlusPlus
10837 ? diag::err_typecheck_pointer_arith_function_type
10838 : diag::ext_gnu_ptr_func_arith)
10839 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10840 // We only show the second type if it differs from the first.
10841 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10842 RHS->getType())
10843 << RHS->getType()->getPointeeType()
10844 << LHS->getSourceRange() << RHS->getSourceRange();
10845}
10846
10847/// Diagnose invalid arithmetic on a function pointer.
10848static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10849 Expr *Pointer) {
10850 assert(Pointer->getType()->isAnyPointerType())(static_cast <bool> (Pointer->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 10850, __extension__ __PRETTY_FUNCTION__
))
;
10851 S.Diag(Loc, S.getLangOpts().CPlusPlus
10852 ? diag::err_typecheck_pointer_arith_function_type
10853 : diag::ext_gnu_ptr_func_arith)
10854 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10855 << 0 /* one pointer, so only one type */
10856 << Pointer->getSourceRange();
10857}
10858
10859/// Emit error if Operand is incomplete pointer type
10860///
10861/// \returns True if pointer has incomplete type
10862static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10863 Expr *Operand) {
10864 QualType ResType = Operand->getType();
10865 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10866 ResType = ResAtomicType->getValueType();
10867
10868 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", 10868, __extension__ __PRETTY_FUNCTION__
))
;
10869 QualType PointeeTy = ResType->getPointeeType();
10870 return S.RequireCompleteSizedType(
10871 Loc, PointeeTy,
10872 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10873 Operand->getSourceRange());
10874}
10875
10876/// Check the validity of an arithmetic pointer operand.
10877///
10878/// If the operand has pointer type, this code will check for pointer types
10879/// which are invalid in arithmetic operations. These will be diagnosed
10880/// appropriately, including whether or not the use is supported as an
10881/// extension.
10882///
10883/// \returns True when the operand is valid to use (even if as an extension).
10884static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10885 Expr *Operand) {
10886 QualType ResType = Operand->getType();
10887 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10888 ResType = ResAtomicType->getValueType();
10889
10890 if (!ResType->isAnyPointerType()) return true;
10891
10892 QualType PointeeTy = ResType->getPointeeType();
10893 if (PointeeTy->isVoidType()) {
10894 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10895 return !S.getLangOpts().CPlusPlus;
10896 }
10897 if (PointeeTy->isFunctionType()) {
10898 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10899 return !S.getLangOpts().CPlusPlus;
10900 }
10901
10902 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10903
10904 return true;
10905}
10906
10907/// Check the validity of a binary arithmetic operation w.r.t. pointer
10908/// operands.
10909///
10910/// This routine will diagnose any invalid arithmetic on pointer operands much
10911/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10912/// for emitting a single diagnostic even for operations where both LHS and RHS
10913/// are (potentially problematic) pointers.
10914///
10915/// \returns True when the operand is valid to use (even if as an extension).
10916static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10917 Expr *LHSExpr, Expr *RHSExpr) {
10918 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10919 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10920 if (!isLHSPointer && !isRHSPointer) return true;
10921
10922 QualType LHSPointeeTy, RHSPointeeTy;
10923 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10924 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10925
10926 // if both are pointers check if operation is valid wrt address spaces
10927 if (isLHSPointer && isRHSPointer) {
10928 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10929 S.Diag(Loc,
10930 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10931 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10932 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10933 return false;
10934 }
10935 }
10936
10937 // Check for arithmetic on pointers to incomplete types.
10938 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10939 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10940 if (isLHSVoidPtr || isRHSVoidPtr) {
10941 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10942 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10943 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10944
10945 return !S.getLangOpts().CPlusPlus;
10946 }
10947
10948 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10949 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10950 if (isLHSFuncPtr || isRHSFuncPtr) {
10951 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10952 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10953 RHSExpr);
10954 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10955
10956 return !S.getLangOpts().CPlusPlus;
10957 }
10958
10959 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10960 return false;
10961 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10962 return false;
10963
10964 return true;
10965}
10966
10967/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10968/// literal.
10969static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10970 Expr *LHSExpr, Expr *RHSExpr) {
10971 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10972 Expr* IndexExpr = RHSExpr;
10973 if (!StrExpr) {
10974 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10975 IndexExpr = LHSExpr;
10976 }
10977
10978 bool IsStringPlusInt = StrExpr &&
10979 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10980 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10981 return;
10982
10983 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10984 Self.Diag(OpLoc, diag::warn_string_plus_int)
10985 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10986
10987 // Only print a fixit for "str" + int, not for int + "str".
10988 if (IndexExpr == RHSExpr) {
10989 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10990 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10991 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10992 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10993 << FixItHint::CreateInsertion(EndLoc, "]");
10994 } else
10995 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10996}
10997
10998/// Emit a warning when adding a char literal to a string.
10999static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11000 Expr *LHSExpr, Expr *RHSExpr) {
11001 const Expr *StringRefExpr = LHSExpr;
11002 const CharacterLiteral *CharExpr =
11003 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11004
11005 if (!CharExpr) {
11006 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11007 StringRefExpr = RHSExpr;
11008 }
11009
11010 if (!CharExpr || !StringRefExpr)
11011 return;
11012
11013 const QualType StringType = StringRefExpr->getType();
11014
11015 // Return if not a PointerType.
11016 if (!StringType->isAnyPointerType())
11017 return;
11018
11019 // Return if not a CharacterType.
11020 if (!StringType->getPointeeType()->isAnyCharacterType())
11021 return;
11022
11023 ASTContext &Ctx = Self.getASTContext();
11024 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11025
11026 const QualType CharType = CharExpr->getType();
11027 if (!CharType->isAnyCharacterType() &&
11028 CharType->isIntegerType() &&
11029 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11030 Self.Diag(OpLoc, diag::warn_string_plus_char)
11031 << DiagRange << Ctx.CharTy;
11032 } else {
11033 Self.Diag(OpLoc, diag::warn_string_plus_char)
11034 << DiagRange << CharExpr->getType();
11035 }
11036
11037 // Only print a fixit for str + char, not for char + str.
11038 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11039 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11040 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11041 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11042 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11043 << FixItHint::CreateInsertion(EndLoc, "]");
11044 } else {
11045 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11046 }
11047}
11048
11049/// Emit error when two pointers are incompatible.
11050static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11051 Expr *LHSExpr, Expr *RHSExpr) {
11052 assert(LHSExpr->getType()->isAnyPointerType())(static_cast <bool> (LHSExpr->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11052, __extension__ __PRETTY_FUNCTION__
))
;
11053 assert(RHSExpr->getType()->isAnyPointerType())(static_cast <bool> (RHSExpr->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11053, __extension__ __PRETTY_FUNCTION__
))
;
11054 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11055 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11056 << RHSExpr->getSourceRange();
11057}
11058
11059// C99 6.5.6
11060QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11061 SourceLocation Loc, BinaryOperatorKind Opc,
11062 QualType* CompLHSTy) {
11063 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11064
11065 if (LHS.get()->getType()->isVectorType() ||
11066 RHS.get()->getType()->isVectorType()) {
11067 QualType compType =
11068 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11069 /*AllowBothBool*/ getLangOpts().AltiVec,
11070 /*AllowBoolConversions*/ getLangOpts().ZVector,
11071 /*AllowBooleanOperation*/ false,
11072 /*ReportInvalid*/ true);
11073 if (CompLHSTy) *CompLHSTy = compType;
11074 return compType;
11075 }
11076
11077 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11078 RHS.get()->getType()->isVLSTBuiltinType()) {
11079 QualType compType =
11080 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11081 if (CompLHSTy)
11082 *CompLHSTy = compType;
11083 return compType;
11084 }
11085
11086 if (LHS.get()->getType()->isConstantMatrixType() ||
11087 RHS.get()->getType()->isConstantMatrixType()) {
11088 QualType compType =
11089 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11090 if (CompLHSTy)
11091 *CompLHSTy = compType;
11092 return compType;
11093 }
11094
11095 QualType compType = UsualArithmeticConversions(
11096 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11097 if (LHS.isInvalid() || RHS.isInvalid())
11098 return QualType();
11099
11100 // Diagnose "string literal" '+' int and string '+' "char literal".
11101 if (Opc == BO_Add) {
11102 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11103 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11104 }
11105
11106 // handle the common case first (both operands are arithmetic).
11107 if (!compType.isNull() && compType->isArithmeticType()) {
11108 if (CompLHSTy) *CompLHSTy = compType;
11109 return compType;
11110 }
11111
11112 // Type-checking. Ultimately the pointer's going to be in PExp;
11113 // note that we bias towards the LHS being the pointer.
11114 Expr *PExp = LHS.get(), *IExp = RHS.get();
11115
11116 bool isObjCPointer;
11117 if (PExp->getType()->isPointerType()) {
11118 isObjCPointer = false;
11119 } else if (PExp->getType()->isObjCObjectPointerType()) {
11120 isObjCPointer = true;
11121 } else {
11122 std::swap(PExp, IExp);
11123 if (PExp->getType()->isPointerType()) {
11124 isObjCPointer = false;
11125 } else if (PExp->getType()->isObjCObjectPointerType()) {
11126 isObjCPointer = true;
11127 } else {
11128 return InvalidOperands(Loc, LHS, RHS);
11129 }
11130 }
11131 assert(PExp->getType()->isAnyPointerType())(static_cast <bool> (PExp->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("PExp->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11131, __extension__ __PRETTY_FUNCTION__
))
;
11132
11133 if (!IExp->getType()->isIntegerType())
11134 return InvalidOperands(Loc, LHS, RHS);
11135
11136 // Adding to a null pointer results in undefined behavior.
11137 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11138 Context, Expr::NPC_ValueDependentIsNotNull)) {
11139 // In C++ adding zero to a null pointer is defined.
11140 Expr::EvalResult KnownVal;
11141 if (!getLangOpts().CPlusPlus ||
11142 (!IExp->isValueDependent() &&
11143 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11144 KnownVal.Val.getInt() != 0))) {
11145 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11146 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11147 Context, BO_Add, PExp, IExp);
11148 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11149 }
11150 }
11151
11152 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11153 return QualType();
11154
11155 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11156 return QualType();
11157
11158 // Check array bounds for pointer arithemtic
11159 CheckArrayAccess(PExp, IExp);
11160
11161 if (CompLHSTy) {
11162 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11163 if (LHSTy.isNull()) {
11164 LHSTy = LHS.get()->getType();
11165 if (LHSTy->isPromotableIntegerType())
11166 LHSTy = Context.getPromotedIntegerType(LHSTy);
11167 }
11168 *CompLHSTy = LHSTy;
11169 }
11170
11171 return PExp->getType();
11172}
11173
11174// C99 6.5.6
11175QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11176 SourceLocation Loc,
11177 QualType* CompLHSTy) {
11178 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11179
11180 if (LHS.get()->getType()->isVectorType() ||
11181 RHS.get()->getType()->isVectorType()) {
11182 QualType compType =
11183 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11184 /*AllowBothBool*/ getLangOpts().AltiVec,
11185 /*AllowBoolConversions*/ getLangOpts().ZVector,
11186 /*AllowBooleanOperation*/ false,
11187 /*ReportInvalid*/ true);
11188 if (CompLHSTy) *CompLHSTy = compType;
11189 return compType;
11190 }
11191
11192 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11193 RHS.get()->getType()->isVLSTBuiltinType()) {
11194 QualType compType =
11195 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11196 if (CompLHSTy)
11197 *CompLHSTy = compType;
11198 return compType;
11199 }
11200
11201 if (LHS.get()->getType()->isConstantMatrixType() ||
11202 RHS.get()->getType()->isConstantMatrixType()) {
11203 QualType compType =
11204 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11205 if (CompLHSTy)
11206 *CompLHSTy = compType;
11207 return compType;
11208 }
11209
11210 QualType compType = UsualArithmeticConversions(
11211 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11212 if (LHS.isInvalid() || RHS.isInvalid())
11213 return QualType();
11214
11215 // Enforce type constraints: C99 6.5.6p3.
11216
11217 // Handle the common case first (both operands are arithmetic).
11218 if (!compType.isNull() && compType->isArithmeticType()) {
11219 if (CompLHSTy) *CompLHSTy = compType;
11220 return compType;
11221 }
11222
11223 // Either ptr - int or ptr - ptr.
11224 if (LHS.get()->getType()->isAnyPointerType()) {
11225 QualType lpointee = LHS.get()->getType()->getPointeeType();
11226
11227 // Diagnose bad cases where we step over interface counts.
11228 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11229 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11230 return QualType();
11231
11232 // The result type of a pointer-int computation is the pointer type.
11233 if (RHS.get()->getType()->isIntegerType()) {
11234 // Subtracting from a null pointer should produce a warning.
11235 // The last argument to the diagnose call says this doesn't match the
11236 // GNU int-to-pointer idiom.
11237 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11238 Expr::NPC_ValueDependentIsNotNull)) {
11239 // In C++ adding zero to a null pointer is defined.
11240 Expr::EvalResult KnownVal;
11241 if (!getLangOpts().CPlusPlus ||
11242 (!RHS.get()->isValueDependent() &&
11243 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11244 KnownVal.Val.getInt() != 0))) {
11245 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11246 }
11247 }
11248
11249 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11250 return QualType();
11251
11252 // Check array bounds for pointer arithemtic
11253 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11254 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11255
11256 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11257 return LHS.get()->getType();
11258 }
11259
11260 // Handle pointer-pointer subtractions.
11261 if (const PointerType *RHSPTy
11262 = RHS.get()->getType()->getAs<PointerType>()) {
11263 QualType rpointee = RHSPTy->getPointeeType();
11264
11265 if (getLangOpts().CPlusPlus) {
11266 // Pointee types must be the same: C++ [expr.add]
11267 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11268 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11269 }
11270 } else {
11271 // Pointee types must be compatible C99 6.5.6p3
11272 if (!Context.typesAreCompatible(
11273 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11274 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11275 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11276 return QualType();
11277 }
11278 }
11279
11280 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11281 LHS.get(), RHS.get()))
11282 return QualType();
11283
11284 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11285 Context, Expr::NPC_ValueDependentIsNotNull);
11286 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11287 Context, Expr::NPC_ValueDependentIsNotNull);
11288
11289 // Subtracting nullptr or from nullptr is suspect
11290 if (LHSIsNullPtr)
11291 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11292 if (RHSIsNullPtr)
11293 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11294
11295 // The pointee type may have zero size. As an extension, a structure or
11296 // union may have zero size or an array may have zero length. In this
11297 // case subtraction does not make sense.
11298 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11299 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11300 if (ElementSize.isZero()) {
11301 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11302 << rpointee.getUnqualifiedType()
11303 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11304 }
11305 }
11306
11307 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11308 return Context.getPointerDiffType();
11309 }
11310 }
11311
11312 return InvalidOperands(Loc, LHS, RHS);
11313}
11314
11315static bool isScopedEnumerationType(QualType T) {
11316 if (const EnumType *ET = T->getAs<EnumType>())
11317 return ET->getDecl()->isScoped();
11318 return false;
11319}
11320
11321static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11322 SourceLocation Loc, BinaryOperatorKind Opc,
11323 QualType LHSType) {
11324 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11325 // so skip remaining warnings as we don't want to modify values within Sema.
11326 if (S.getLangOpts().OpenCL)
11327 return;
11328
11329 // Check right/shifter operand
11330 Expr::EvalResult RHSResult;
11331 if (RHS.get()->isValueDependent() ||
11332 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11333 return;
11334 llvm::APSInt Right = RHSResult.Val.getInt();
11335
11336 if (Right.isNegative()) {
11337 S.DiagRuntimeBehavior(Loc, RHS.get(),
11338 S.PDiag(diag::warn_shift_negative)
11339 << RHS.get()->getSourceRange());
11340 return;
11341 }
11342
11343 QualType LHSExprType = LHS.get()->getType();
11344 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11345 if (LHSExprType->isBitIntType())
11346 LeftSize = S.Context.getIntWidth(LHSExprType);
11347 else if (LHSExprType->isFixedPointType()) {
11348 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11349 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11350 }
11351 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11352 if (Right.uge(LeftBits)) {
11353 S.DiagRuntimeBehavior(Loc, RHS.get(),
11354 S.PDiag(diag::warn_shift_gt_typewidth)
11355 << RHS.get()->getSourceRange());
11356 return;
11357 }
11358
11359 // FIXME: We probably need to handle fixed point types specially here.
11360 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11361 return;
11362
11363 // When left shifting an ICE which is signed, we can check for overflow which
11364 // according to C++ standards prior to C++2a has undefined behavior
11365 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11366 // more than the maximum value representable in the result type, so never
11367 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11368 // expression is still probably a bug.)
11369 Expr::EvalResult LHSResult;
11370 if (LHS.get()->isValueDependent() ||
11371 LHSType->hasUnsignedIntegerRepresentation() ||
11372 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11373 return;
11374 llvm::APSInt Left = LHSResult.Val.getInt();
11375
11376 // If LHS does not have a signed type and non-negative value
11377 // then, the behavior is undefined before C++2a. Warn about it.
11378 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
11379 !S.getLangOpts().CPlusPlus20) {
11380 S.DiagRuntimeBehavior(Loc, LHS.get(),
11381 S.PDiag(diag::warn_shift_lhs_negative)
11382 << LHS.get()->getSourceRange());
11383 return;
11384 }
11385
11386 llvm::APInt ResultBits =
11387 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11388 if (LeftBits.uge(ResultBits))
11389 return;
11390 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11391 Result = Result.shl(Right);
11392
11393 // Print the bit representation of the signed integer as an unsigned
11394 // hexadecimal number.
11395 SmallString<40> HexResult;
11396 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11397
11398 // If we are only missing a sign bit, this is less likely to result in actual
11399 // bugs -- if the result is cast back to an unsigned type, it will have the
11400 // expected value. Thus we place this behind a different warning that can be
11401 // turned off separately if needed.
11402 if (LeftBits == ResultBits - 1) {
11403 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11404 << HexResult << LHSType
11405 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11406 return;
11407 }
11408
11409 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11410 << HexResult.str() << Result.getMinSignedBits() << LHSType
11411 << Left.getBitWidth() << LHS.get()->getSourceRange()
11412 << RHS.get()->getSourceRange();
11413}
11414
11415/// Return the resulting type when a vector is shifted
11416/// by a scalar or vector shift amount.
11417static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11418 SourceLocation Loc, bool IsCompAssign) {
11419 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11420 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11421 !LHS.get()->getType()->isVectorType()) {
11422 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11423 << RHS.get()->getType() << LHS.get()->getType()
11424 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11425 return QualType();
11426 }
11427
11428 if (!IsCompAssign) {
11429 LHS = S.UsualUnaryConversions(LHS.get());
11430 if (LHS.isInvalid()) return QualType();
11431 }
11432
11433 RHS = S.UsualUnaryConversions(RHS.get());
11434 if (RHS.isInvalid()) return QualType();
11435
11436 QualType LHSType = LHS.get()->getType();
11437 // Note that LHS might be a scalar because the routine calls not only in
11438 // OpenCL case.
11439 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11440 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11441
11442 // Note that RHS might not be a vector.
11443 QualType RHSType = RHS.get()->getType();
11444 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11445 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11446
11447 // Do not allow shifts for boolean vectors.
11448 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11449 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11450 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11451 << LHS.get()->getType() << RHS.get()->getType()
11452 << LHS.get()->getSourceRange();
11453 return QualType();
11454 }
11455
11456 // The operands need to be integers.
11457 if (!LHSEleType->isIntegerType()) {
11458 S.Diag(Loc, diag::err_typecheck_expect_int)
11459 << LHS.get()->getType() << LHS.get()->getSourceRange();
11460 return QualType();
11461 }
11462
11463 if (!RHSEleType->isIntegerType()) {
11464 S.Diag(Loc, diag::err_typecheck_expect_int)
11465 << RHS.get()->getType() << RHS.get()->getSourceRange();
11466 return QualType();
11467 }
11468
11469 if (!LHSVecTy) {
11470 assert(RHSVecTy)(static_cast <bool> (RHSVecTy) ? void (0) : __assert_fail
("RHSVecTy", "clang/lib/Sema/SemaExpr.cpp", 11470, __extension__
__PRETTY_FUNCTION__))
;
11471 if (IsCompAssign)
11472 return RHSType;
11473 if (LHSEleType != RHSEleType) {
11474 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11475 LHSEleType = RHSEleType;
11476 }
11477 QualType VecTy =
11478 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11479 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11480 LHSType = VecTy;
11481 } else if (RHSVecTy) {
11482 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11483 // are applied component-wise. So if RHS is a vector, then ensure
11484 // that the number of elements is the same as LHS...
11485 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11486 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11487 << LHS.get()->getType() << RHS.get()->getType()
11488 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11489 return QualType();
11490 }
11491 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11492 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11493 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11494 if (LHSBT != RHSBT &&
11495 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11496 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11497 << LHS.get()->getType() << RHS.get()->getType()
11498 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11499 }
11500 }
11501 } else {
11502 // ...else expand RHS to match the number of elements in LHS.
11503 QualType VecTy =
11504 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11505 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11506 }
11507
11508 return LHSType;
11509}
11510
11511static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
11512 ExprResult &RHS, SourceLocation Loc,
11513 bool IsCompAssign) {
11514 if (!IsCompAssign) {
11515 LHS = S.UsualUnaryConversions(LHS.get());
11516 if (LHS.isInvalid())
11517 return QualType();
11518 }
11519
11520 RHS = S.UsualUnaryConversions(RHS.get());
11521 if (RHS.isInvalid())
11522 return QualType();
11523
11524 QualType LHSType = LHS.get()->getType();
11525 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11526 QualType LHSEleType = LHSType->isVLSTBuiltinType()
11527 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11528 : LHSType;
11529
11530 // Note that RHS might not be a vector
11531 QualType RHSType = RHS.get()->getType();
11532 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11533 QualType RHSEleType = RHSType->isVLSTBuiltinType()
11534 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11535 : RHSType;
11536
11537 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11538 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11539 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11540 << LHSType << RHSType << LHS.get()->getSourceRange();
11541 return QualType();
11542 }
11543
11544 if (!LHSEleType->isIntegerType()) {
11545 S.Diag(Loc, diag::err_typecheck_expect_int)
11546 << LHS.get()->getType() << LHS.get()->getSourceRange();
11547 return QualType();
11548 }
11549
11550 if (!RHSEleType->isIntegerType()) {
11551 S.Diag(Loc, diag::err_typecheck_expect_int)
11552 << RHS.get()->getType() << RHS.get()->getSourceRange();
11553 return QualType();
11554 }
11555
11556 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
11557 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11558 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11559 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11560 << LHSType << RHSType << LHS.get()->getSourceRange()
11561 << RHS.get()->getSourceRange();
11562 return QualType();
11563 }
11564
11565 if (!LHSType->isVLSTBuiltinType()) {
11566 assert(RHSType->isVLSTBuiltinType())(static_cast <bool> (RHSType->isVLSTBuiltinType()) ?
void (0) : __assert_fail ("RHSType->isVLSTBuiltinType()",
"clang/lib/Sema/SemaExpr.cpp", 11566, __extension__ __PRETTY_FUNCTION__
))
;
11567 if (IsCompAssign)
11568 return RHSType;
11569 if (LHSEleType != RHSEleType) {
11570 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11571 LHSEleType = RHSEleType;
11572 }
11573 const llvm::ElementCount VecSize =
11574 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11575 QualType VecTy =
11576 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11577 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11578 LHSType = VecTy;
11579 } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) {
11580 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11581 S.Context.getTypeSize(LHSBuiltinTy)) {
11582 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11583 << LHSType << RHSType << LHS.get()->getSourceRange()
11584 << RHS.get()->getSourceRange();
11585 return QualType();
11586 }
11587 } else {
11588 const llvm::ElementCount VecSize =
11589 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11590 if (LHSEleType != RHSEleType) {
11591 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11592 RHSEleType = LHSEleType;
11593 }
11594 QualType VecTy =
11595 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11596 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11597 }
11598
11599 return LHSType;
11600}
11601
11602// C99 6.5.7
11603QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11604 SourceLocation Loc, BinaryOperatorKind Opc,
11605 bool IsCompAssign) {
11606 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11607
11608 // Vector shifts promote their scalar inputs to vector type.
11609 if (LHS.get()->getType()->isVectorType() ||
11610 RHS.get()->getType()->isVectorType()) {
11611 if (LangOpts.ZVector) {
11612 // The shift operators for the z vector extensions work basically
11613 // like general shifts, except that neither the LHS nor the RHS is
11614 // allowed to be a "vector bool".
11615 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11616 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11617 return InvalidOperands(Loc, LHS, RHS);
11618 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11619 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11620 return InvalidOperands(Loc, LHS, RHS);
11621 }
11622 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11623 }
11624
11625 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11626 RHS.get()->getType()->isVLSTBuiltinType())
11627 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11628
11629 // Shifts don't perform usual arithmetic conversions, they just do integer
11630 // promotions on each operand. C99 6.5.7p3
11631
11632 // For the LHS, do usual unary conversions, but then reset them away
11633 // if this is a compound assignment.
11634 ExprResult OldLHS = LHS;
11635 LHS = UsualUnaryConversions(LHS.get());
11636 if (LHS.isInvalid())
11637 return QualType();
11638 QualType LHSType = LHS.get()->getType();
11639 if (IsCompAssign) LHS = OldLHS;
11640
11641 // The RHS is simpler.
11642 RHS = UsualUnaryConversions(RHS.get());
11643 if (RHS.isInvalid())
11644 return QualType();
11645 QualType RHSType = RHS.get()->getType();
11646
11647 // C99 6.5.7p2: Each of the operands shall have integer type.
11648 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11649 if ((!LHSType->isFixedPointOrIntegerType() &&
11650 !LHSType->hasIntegerRepresentation()) ||
11651 !RHSType->hasIntegerRepresentation())
11652 return InvalidOperands(Loc, LHS, RHS);
11653
11654 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11655 // hasIntegerRepresentation() above instead of this.
11656 if (isScopedEnumerationType(LHSType) ||
11657 isScopedEnumerationType(RHSType)) {
11658 return InvalidOperands(Loc, LHS, RHS);
11659 }
11660 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11661
11662 // "The type of the result is that of the promoted left operand."
11663 return LHSType;
11664}
11665
11666/// Diagnose bad pointer comparisons.
11667static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11668 ExprResult &LHS, ExprResult &RHS,
11669 bool IsError) {
11670 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11671 : diag::ext_typecheck_comparison_of_distinct_pointers)
11672 << LHS.get()->getType() << RHS.get()->getType()
11673 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11674}
11675
11676/// Returns false if the pointers are converted to a composite type,
11677/// true otherwise.
11678static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11679 ExprResult &LHS, ExprResult &RHS) {
11680 // C++ [expr.rel]p2:
11681 // [...] Pointer conversions (4.10) and qualification
11682 // conversions (4.4) are performed on pointer operands (or on
11683 // a pointer operand and a null pointer constant) to bring
11684 // them to their composite pointer type. [...]
11685 //
11686 // C++ [expr.eq]p1 uses the same notion for (in)equality
11687 // comparisons of pointers.
11688
11689 QualType LHSType = LHS.get()->getType();
11690 QualType RHSType = RHS.get()->getType();
11691 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", 11692, __extension__ __PRETTY_FUNCTION__
))
11692 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", 11692, __extension__ __PRETTY_FUNCTION__
))
;
11693
11694 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11695 if (T.isNull()) {
11696 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11697 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11698 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11699 else
11700 S.InvalidOperands(Loc, LHS, RHS);
11701 return true;
11702 }
11703
11704 return false;
11705}
11706
11707static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11708 ExprResult &LHS,
11709 ExprResult &RHS,
11710 bool IsError) {
11711 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11712 : diag::ext_typecheck_comparison_of_fptr_to_void)
11713 << LHS.get()->getType() << RHS.get()->getType()
11714 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11715}
11716
11717static bool isObjCObjectLiteral(ExprResult &E) {
11718 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11719 case Stmt::ObjCArrayLiteralClass:
11720 case Stmt::ObjCDictionaryLiteralClass:
11721 case Stmt::ObjCStringLiteralClass:
11722 case Stmt::ObjCBoxedExprClass:
11723 return true;
11724 default:
11725 // Note that ObjCBoolLiteral is NOT an object literal!
11726 return false;
11727 }
11728}
11729
11730static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11731 const ObjCObjectPointerType *Type =
11732 LHS->getType()->getAs<ObjCObjectPointerType>();
11733
11734 // If this is not actually an Objective-C object, bail out.
11735 if (!Type)
11736 return false;
11737
11738 // Get the LHS object's interface type.
11739 QualType InterfaceType = Type->getPointeeType();
11740
11741 // If the RHS isn't an Objective-C object, bail out.
11742 if (!RHS->getType()->isObjCObjectPointerType())
11743 return false;
11744
11745 // Try to find the -isEqual: method.
11746 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11747 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11748 InterfaceType,
11749 /*IsInstance=*/true);
11750 if (!Method) {
11751 if (Type->isObjCIdType()) {
11752 // For 'id', just check the global pool.
11753 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11754 /*receiverId=*/true);
11755 } else {
11756 // Check protocols.
11757 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11758 /*IsInstance=*/true);
11759 }
11760 }
11761
11762 if (!Method)
11763 return false;
11764
11765 QualType T = Method->parameters()[0]->getType();
11766 if (!T->isObjCObjectPointerType())
11767 return false;
11768
11769 QualType R = Method->getReturnType();
11770 if (!R->isScalarType())
11771 return false;
11772
11773 return true;
11774}
11775
11776Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11777 FromE = FromE->IgnoreParenImpCasts();
11778 switch (FromE->getStmtClass()) {
11779 default:
11780 break;
11781 case Stmt::ObjCStringLiteralClass:
11782 // "string literal"
11783 return LK_String;
11784 case Stmt::ObjCArrayLiteralClass:
11785 // "array literal"
11786 return LK_Array;
11787 case Stmt::ObjCDictionaryLiteralClass:
11788 // "dictionary literal"
11789 return LK_Dictionary;
11790 case Stmt::BlockExprClass:
11791 return LK_Block;
11792 case Stmt::ObjCBoxedExprClass: {
11793 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11794 switch (Inner->getStmtClass()) {
11795 case Stmt::IntegerLiteralClass:
11796 case Stmt::FloatingLiteralClass:
11797 case Stmt::CharacterLiteralClass:
11798 case Stmt::ObjCBoolLiteralExprClass:
11799 case Stmt::CXXBoolLiteralExprClass:
11800 // "numeric literal"
11801 return LK_Numeric;
11802 case Stmt::ImplicitCastExprClass: {
11803 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11804 // Boolean literals can be represented by implicit casts.
11805 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11806 return LK_Numeric;
11807 break;
11808 }
11809 default:
11810 break;
11811 }
11812 return LK_Boxed;
11813 }
11814 }
11815 return LK_None;
11816}
11817
11818static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11819 ExprResult &LHS, ExprResult &RHS,
11820 BinaryOperator::Opcode Opc){
11821 Expr *Literal;
11822 Expr *Other;
11823 if (isObjCObjectLiteral(LHS)) {
11824 Literal = LHS.get();
11825 Other = RHS.get();
11826 } else {
11827 Literal = RHS.get();
11828 Other = LHS.get();
11829 }
11830
11831 // Don't warn on comparisons against nil.
11832 Other = Other->IgnoreParenCasts();
11833 if (Other->isNullPointerConstant(S.getASTContext(),
11834 Expr::NPC_ValueDependentIsNotNull))
11835 return;
11836
11837 // This should be kept in sync with warn_objc_literal_comparison.
11838 // LK_String should always be after the other literals, since it has its own
11839 // warning flag.
11840 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11841 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"
, 11841, __extension__ __PRETTY_FUNCTION__))
;
11842 if (LiteralKind == Sema::LK_None) {
11843 llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind"
, "clang/lib/Sema/SemaExpr.cpp", 11843)
;
11844 }
11845
11846 if (LiteralKind == Sema::LK_String)
11847 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11848 << Literal->getSourceRange();
11849 else
11850 S.Diag(Loc, diag::warn_objc_literal_comparison)
11851 << LiteralKind << Literal->getSourceRange();
11852
11853 if (BinaryOperator::isEqualityOp(Opc) &&
11854 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11855 SourceLocation Start = LHS.get()->getBeginLoc();
11856 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11857 CharSourceRange OpRange =
11858 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11859
11860 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11861 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11862 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11863 << FixItHint::CreateInsertion(End, "]");
11864 }
11865}
11866
11867/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11868static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11869 ExprResult &RHS, SourceLocation Loc,
11870 BinaryOperatorKind Opc) {
11871 // Check that left hand side is !something.
11872 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11873 if (!UO || UO->getOpcode() != UO_LNot) return;
11874
11875 // Only check if the right hand side is non-bool arithmetic type.
11876 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11877
11878 // Make sure that the something in !something is not bool.
11879 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11880 if (SubExpr->isKnownToHaveBooleanValue()) return;
11881
11882 // Emit warning.
11883 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11884 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11885 << Loc << IsBitwiseOp;
11886
11887 // First note suggest !(x < y)
11888 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11889 SourceLocation FirstClose = RHS.get()->getEndLoc();
11890 FirstClose = S.getLocForEndOfToken(FirstClose);
11891 if (FirstClose.isInvalid())
11892 FirstOpen = SourceLocation();
11893 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11894 << IsBitwiseOp
11895 << FixItHint::CreateInsertion(FirstOpen, "(")
11896 << FixItHint::CreateInsertion(FirstClose, ")");
11897
11898 // Second note suggests (!x) < y
11899 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11900 SourceLocation SecondClose = LHS.get()->getEndLoc();
11901 SecondClose = S.getLocForEndOfToken(SecondClose);
11902 if (SecondClose.isInvalid())
11903 SecondOpen = SourceLocation();
11904 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11905 << FixItHint::CreateInsertion(SecondOpen, "(")
11906 << FixItHint::CreateInsertion(SecondClose, ")");
11907}
11908
11909// Returns true if E refers to a non-weak array.
11910static bool checkForArray(const Expr *E) {
11911 const ValueDecl *D = nullptr;
11912 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11913 D = DR->getDecl();
11914 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11915 if (Mem->isImplicitAccess())
11916 D = Mem->getMemberDecl();
11917 }
11918 if (!D)
11919 return false;
11920 return D->getType()->isArrayType() && !D->isWeak();
11921}
11922
11923/// Diagnose some forms of syntactically-obvious tautological comparison.
11924static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11925 Expr *LHS, Expr *RHS,
11926 BinaryOperatorKind Opc) {
11927 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11928 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11929
11930 QualType LHSType = LHS->getType();
11931 QualType RHSType = RHS->getType();
11932 if (LHSType->hasFloatingRepresentation() ||
11933 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11934 S.inTemplateInstantiation())
11935 return;
11936
11937 // Comparisons between two array types are ill-formed for operator<=>, so
11938 // we shouldn't emit any additional warnings about it.
11939 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11940 return;
11941
11942 // For non-floating point types, check for self-comparisons of the form
11943 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11944 // often indicate logic errors in the program.
11945 //
11946 // NOTE: Don't warn about comparison expressions resulting from macro
11947 // expansion. Also don't warn about comparisons which are only self
11948 // comparisons within a template instantiation. The warnings should catch
11949 // obvious cases in the definition of the template anyways. The idea is to
11950 // warn when the typed comparison operator will always evaluate to the same
11951 // result.
11952
11953 // Used for indexing into %select in warn_comparison_always
11954 enum {
11955 AlwaysConstant,
11956 AlwaysTrue,
11957 AlwaysFalse,
11958 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11959 };
11960
11961 // C++2a [depr.array.comp]:
11962 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11963 // operands of array type are deprecated.
11964 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11965 RHSStripped->getType()->isArrayType()) {
11966 S.Diag(Loc, diag::warn_depr_array_comparison)
11967 << LHS->getSourceRange() << RHS->getSourceRange()
11968 << LHSStripped->getType() << RHSStripped->getType();
11969 // Carry on to produce the tautological comparison warning, if this
11970 // expression is potentially-evaluated, we can resolve the array to a
11971 // non-weak declaration, and so on.
11972 }
11973
11974 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11975 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11976 unsigned Result;
11977 switch (Opc) {
11978 case BO_EQ:
11979 case BO_LE:
11980 case BO_GE:
11981 Result = AlwaysTrue;
11982 break;
11983 case BO_NE:
11984 case BO_LT:
11985 case BO_GT:
11986 Result = AlwaysFalse;
11987 break;
11988 case BO_Cmp:
11989 Result = AlwaysEqual;
11990 break;
11991 default:
11992 Result = AlwaysConstant;
11993 break;
11994 }
11995 S.DiagRuntimeBehavior(Loc, nullptr,
11996 S.PDiag(diag::warn_comparison_always)
11997 << 0 /*self-comparison*/
11998 << Result);
11999 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12000 // What is it always going to evaluate to?
12001 unsigned Result;
12002 switch (Opc) {
12003 case BO_EQ: // e.g. array1 == array2
12004 Result = AlwaysFalse;
12005 break;
12006 case BO_NE: // e.g. array1 != array2
12007 Result = AlwaysTrue;
12008 break;
12009 default: // e.g. array1 <= array2
12010 // The best we can say is 'a constant'
12011 Result = AlwaysConstant;
12012 break;
12013 }
12014 S.DiagRuntimeBehavior(Loc, nullptr,
12015 S.PDiag(diag::warn_comparison_always)
12016 << 1 /*array comparison*/
12017 << Result);
12018 }
12019 }
12020
12021 if (isa<CastExpr>(LHSStripped))
12022 LHSStripped = LHSStripped->IgnoreParenCasts();
12023 if (isa<CastExpr>(RHSStripped))
12024 RHSStripped = RHSStripped->IgnoreParenCasts();
12025
12026 // Warn about comparisons against a string constant (unless the other
12027 // operand is null); the user probably wants string comparison function.
12028 Expr *LiteralString = nullptr;
12029 Expr *LiteralStringStripped = nullptr;
12030 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12031 !RHSStripped->isNullPointerConstant(S.Context,
12032 Expr::NPC_ValueDependentIsNull)) {
12033 LiteralString = LHS;
12034 LiteralStringStripped = LHSStripped;
12035 } else if ((isa<StringLiteral>(RHSStripped) ||
12036 isa<ObjCEncodeExpr>(RHSStripped)) &&
12037 !LHSStripped->isNullPointerConstant(S.Context,
12038 Expr::NPC_ValueDependentIsNull)) {
12039 LiteralString = RHS;
12040 LiteralStringStripped = RHSStripped;
12041 }
12042
12043 if (LiteralString) {
12044 S.DiagRuntimeBehavior(Loc, nullptr,
12045 S.PDiag(diag::warn_stringcompare)
12046 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12047 << LiteralString->getSourceRange());
12048 }
12049}
12050
12051static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12052 switch (CK) {
12053 default: {
12054#ifndef NDEBUG
12055 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12056 << "\n";
12057#endif
12058 llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "clang/lib/Sema/SemaExpr.cpp"
, 12058)
;
12059 }
12060 case CK_UserDefinedConversion:
12061 return ICK_Identity;
12062 case CK_LValueToRValue:
12063 return ICK_Lvalue_To_Rvalue;
12064 case CK_ArrayToPointerDecay:
12065 return ICK_Array_To_Pointer;
12066 case CK_FunctionToPointerDecay:
12067 return ICK_Function_To_Pointer;
12068 case CK_IntegralCast:
12069 return ICK_Integral_Conversion;
12070 case CK_FloatingCast:
12071 return ICK_Floating_Conversion;
12072 case CK_IntegralToFloating:
12073 case CK_FloatingToIntegral:
12074 return ICK_Floating_Integral;
12075 case CK_IntegralComplexCast:
12076 case CK_FloatingComplexCast:
12077 case CK_FloatingComplexToIntegralComplex:
12078 case CK_IntegralComplexToFloatingComplex:
12079 return ICK_Complex_Conversion;
12080 case CK_FloatingComplexToReal:
12081 case CK_FloatingRealToComplex:
12082 case CK_IntegralComplexToReal:
12083 case CK_IntegralRealToComplex:
12084 return ICK_Complex_Real;
12085 }
12086}
12087
12088static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12089 QualType FromType,
12090 SourceLocation Loc) {
12091 // Check for a narrowing implicit conversion.
12092 StandardConversionSequence SCS;
12093 SCS.setAsIdentityConversion();
12094 SCS.setToType(0, FromType);
12095 SCS.setToType(1, ToType);
12096 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12097 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12098
12099 APValue PreNarrowingValue;
12100 QualType PreNarrowingType;
12101 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12102 PreNarrowingType,
12103 /*IgnoreFloatToIntegralConversion*/ true)) {
12104 case NK_Dependent_Narrowing:
12105 // Implicit conversion to a narrower type, but the expression is
12106 // value-dependent so we can't tell whether it's actually narrowing.
12107 case NK_Not_Narrowing:
12108 return false;
12109
12110 case NK_Constant_Narrowing:
12111 // Implicit conversion to a narrower type, and the value is not a constant
12112 // expression.
12113 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12114 << /*Constant*/ 1
12115 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12116 return true;
12117
12118 case NK_Variable_Narrowing:
12119 // Implicit conversion to a narrower type, and the value is not a constant
12120 // expression.
12121 case NK_Type_Narrowing:
12122 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12123 << /*Constant*/ 0 << FromType << ToType;
12124 // TODO: It's not a constant expression, but what if the user intended it
12125 // to be? Can we produce notes to help them figure out why it isn't?
12126 return true;
12127 }
12128 llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch",
"clang/lib/Sema/SemaExpr.cpp", 12128)
;
12129}
12130
12131static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12132 ExprResult &LHS,
12133 ExprResult &RHS,
12134 SourceLocation Loc) {
12135 QualType LHSType = LHS.get()->getType();
12136 QualType RHSType = RHS.get()->getType();
12137 // Dig out the original argument type and expression before implicit casts
12138 // were applied. These are the types/expressions we need to check the
12139 // [expr.spaceship] requirements against.
12140 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12141 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12142 QualType LHSStrippedType = LHSStripped.get()->getType();
12143 QualType RHSStrippedType = RHSStripped.get()->getType();
12144
12145 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12146 // other is not, the program is ill-formed.
12147 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12148 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12149 return QualType();
12150 }
12151
12152 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12153 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12154 RHSStrippedType->isEnumeralType();
12155 if (NumEnumArgs == 1) {
12156 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12157 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12158 if (OtherTy->hasFloatingRepresentation()) {
12159 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12160 return QualType();
12161 }
12162 }
12163 if (NumEnumArgs == 2) {
12164 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12165 // type E, the operator yields the result of converting the operands
12166 // to the underlying type of E and applying <=> to the converted operands.
12167 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12168 S.InvalidOperands(Loc, LHS, RHS);
12169 return QualType();
12170 }
12171 QualType IntType =
12172 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12173 assert(IntType->isArithmeticType())(static_cast <bool> (IntType->isArithmeticType()) ? void
(0) : __assert_fail ("IntType->isArithmeticType()", "clang/lib/Sema/SemaExpr.cpp"
, 12173, __extension__ __PRETTY_FUNCTION__))
;
12174
12175 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12176 // promote the boolean type, and all other promotable integer types, to
12177 // avoid this.
12178 if (IntType->isPromotableIntegerType())
12179 IntType = S.Context.getPromotedIntegerType(IntType);
12180
12181 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12182 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12183 LHSType = RHSType = IntType;
12184 }
12185
12186 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12187 // usual arithmetic conversions are applied to the operands.
12188 QualType Type =
12189 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12190 if (LHS.isInvalid() || RHS.isInvalid())
12191 return QualType();
12192 if (Type.isNull())
12193 return S.InvalidOperands(Loc, LHS, RHS);
12194
12195 Optional<ComparisonCategoryType> CCT =
12196 getComparisonCategoryForBuiltinCmp(Type);
12197 if (!CCT)
12198 return S.InvalidOperands(Loc, LHS, RHS);
12199
12200 bool HasNarrowing = checkThreeWayNarrowingConversion(
12201 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12202 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12203 RHS.get()->getBeginLoc());
12204 if (HasNarrowing)
12205 return QualType();
12206
12207 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", 12207, __extension__ __PRETTY_FUNCTION__
))
;
12208
12209 return S.CheckComparisonCategoryType(
12210 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12211}
12212
12213static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12214 ExprResult &RHS,
12215 SourceLocation Loc,
12216 BinaryOperatorKind Opc) {
12217 if (Opc == BO_Cmp)
12218 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12219
12220 // C99 6.5.8p3 / C99 6.5.9p4
12221 QualType Type =
12222 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12223 if (LHS.isInvalid() || RHS.isInvalid())
12224 return QualType();
12225 if (Type.isNull())
12226 return S.InvalidOperands(Loc, LHS, RHS);
12227 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", 12227, __extension__ __PRETTY_FUNCTION__
))
;
12228
12229 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12230 return S.InvalidOperands(Loc, LHS, RHS);
12231
12232 // Check for comparisons of floating point operands using != and ==.
12233 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
12234 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12235
12236 // The result of comparisons is 'bool' in C++, 'int' in C.
12237 return S.Context.getLogicalOperationType();
12238}
12239
12240void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12241 if (!NullE.get()->getType()->isAnyPointerType())
12242 return;
12243 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12244 if (!E.get()->getType()->isAnyPointerType() &&
12245 E.get()->isNullPointerConstant(Context,
12246 Expr::NPC_ValueDependentIsNotNull) ==
12247 Expr::NPCK_ZeroExpression) {
12248 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12249 if (CL->getValue() == 0)
12250 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12251 << NullValue
12252 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12253 NullValue ? "NULL" : "(void *)0");
12254 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12255 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12256 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12257 if (T == Context.CharTy)
12258 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12259 << NullValue
12260 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12261 NullValue ? "NULL" : "(void *)0");
12262 }
12263 }
12264}
12265
12266// C99 6.5.8, C++ [expr.rel]
12267QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12268 SourceLocation Loc,
12269 BinaryOperatorKind Opc) {
12270 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12271 bool IsThreeWay = Opc == BO_Cmp;
12272 bool IsOrdered = IsRelational || IsThreeWay;
12273 auto IsAnyPointerType = [](ExprResult E) {
12274 QualType Ty = E.get()->getType();
12275 return Ty->isPointerType() || Ty->isMemberPointerType();
12276 };
12277
12278 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12279 // type, array-to-pointer, ..., conversions are performed on both operands to
12280 // bring them to their composite type.
12281 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12282 // any type-related checks.
12283 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12284 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12285 if (LHS.isInvalid())
12286 return QualType();
12287 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12288 if (RHS.isInvalid())
12289 return QualType();
12290 } else {
12291 LHS = DefaultLvalueConversion(LHS.get());
12292 if (LHS.isInvalid())
12293 return QualType();
12294 RHS = DefaultLvalueConversion(RHS.get());
12295 if (RHS.isInvalid())
12296 return QualType();
12297 }
12298
12299 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12300 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12301 CheckPtrComparisonWithNullChar(LHS, RHS);
12302 CheckPtrComparisonWithNullChar(RHS, LHS);
12303 }
12304
12305 // Handle vector comparisons separately.
12306 if (LHS.get()->getType()->isVectorType() ||
12307 RHS.get()->getType()->isVectorType())
12308 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12309
12310 if (LHS.get()->getType()->isVLSTBuiltinType() ||
12311 RHS.get()->getType()->isVLSTBuiltinType())
12312 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12313
12314 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12315 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12316
12317 QualType LHSType = LHS.get()->getType();
12318 QualType RHSType = RHS.get()->getType();
12319 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12320 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12321 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12322
12323 const Expr::NullPointerConstantKind LHSNullKind =
12324 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12325 const Expr::NullPointerConstantKind RHSNullKind =
12326 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12327 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12328 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12329
12330 auto computeResultTy = [&]() {
12331 if (Opc != BO_Cmp)
12332 return Context.getLogicalOperationType();
12333 assert(getLangOpts().CPlusPlus)(static_cast <bool> (getLangOpts().CPlusPlus) ? void (0
) : __assert_fail ("getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 12333, __extension__ __PRETTY_FUNCTION__))
;
12334 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", 12334, __extension__ __PRETTY_FUNCTION__
))
;
12335
12336 QualType CompositeTy = LHS.get()->getType();
12337 assert(!CompositeTy->isReferenceType())(static_cast <bool> (!CompositeTy->isReferenceType()
) ? void (0) : __assert_fail ("!CompositeTy->isReferenceType()"
, "clang/lib/Sema/SemaExpr.cpp", 12337, __extension__ __PRETTY_FUNCTION__
))
;
12338
12339 Optional<ComparisonCategoryType> CCT =
12340 getComparisonCategoryForBuiltinCmp(CompositeTy);
12341 if (!CCT)
12342 return InvalidOperands(Loc, LHS, RHS);
12343
12344 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12345 // P0946R0: Comparisons between a null pointer constant and an object
12346 // pointer result in std::strong_equality, which is ill-formed under
12347 // P1959R0.
12348 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12349 << (LHSIsNull ? LHS.get()->getSourceRange()
12350 : RHS.get()->getSourceRange());
12351 return QualType();
12352 }
12353
12354 return CheckComparisonCategoryType(
12355 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12356 };
12357
12358 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12359 bool IsEquality = Opc == BO_EQ;
12360 if (RHSIsNull)
12361 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12362 RHS.get()->getSourceRange());
12363 else
12364 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12365 LHS.get()->getSourceRange());
12366 }
12367
12368 if (IsOrdered && LHSType->isFunctionPointerType() &&
12369 RHSType->isFunctionPointerType()) {
12370 // Valid unless a relational comparison of function pointers
12371 bool IsError = Opc == BO_Cmp;
12372 auto DiagID =
12373 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12374 : getLangOpts().CPlusPlus
12375 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12376 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12377 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12378 << RHS.get()->getSourceRange();
12379 if (IsError)
12380 return QualType();
12381 }
12382
12383 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12384 (RHSType->isIntegerType() && !RHSIsNull)) {
12385 // Skip normal pointer conversion checks in this case; we have better
12386 // diagnostics for this below.
12387 } else if (getLangOpts().CPlusPlus) {
12388 // Equality comparison of a function pointer to a void pointer is invalid,
12389 // but we allow it as an extension.
12390 // FIXME: If we really want to allow this, should it be part of composite
12391 // pointer type computation so it works in conditionals too?
12392 if (!IsOrdered &&
12393 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12394 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12395 // This is a gcc extension compatibility comparison.
12396 // In a SFINAE context, we treat this as a hard error to maintain
12397 // conformance with the C++ standard.
12398 diagnoseFunctionPointerToVoidComparison(
12399 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12400
12401 if (isSFINAEContext())
12402 return QualType();
12403
12404 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12405 return computeResultTy();
12406 }
12407
12408 // C++ [expr.eq]p2:
12409 // If at least one operand is a pointer [...] bring them to their
12410 // composite pointer type.
12411 // C++ [expr.spaceship]p6
12412 // If at least one of the operands is of pointer type, [...] bring them
12413 // to their composite pointer type.
12414 // C++ [expr.rel]p2:
12415 // If both operands are pointers, [...] bring them to their composite
12416 // pointer type.
12417 // For <=>, the only valid non-pointer types are arrays and functions, and
12418 // we already decayed those, so this is really the same as the relational
12419 // comparison rule.
12420 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12421 (IsOrdered ? 2 : 1) &&
12422 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12423 RHSType->isObjCObjectPointerType()))) {
12424 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12425 return QualType();
12426 return computeResultTy();
12427 }
12428 } else if (LHSType->isPointerType() &&
12429 RHSType->isPointerType()) { // C99 6.5.8p2
12430 // All of the following pointer-related warnings are GCC extensions, except
12431 // when handling null pointer constants.
12432 QualType LCanPointeeTy =
12433 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12434 QualType RCanPointeeTy =
12435 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12436
12437 // C99 6.5.9p2 and C99 6.5.8p2
12438 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12439 RCanPointeeTy.getUnqualifiedType())) {
12440 if (IsRelational) {
12441 // Pointers both need to point to complete or incomplete types
12442 if ((LCanPointeeTy->isIncompleteType() !=
12443 RCanPointeeTy->isIncompleteType()) &&
12444 !getLangOpts().C11) {
12445 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12446 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12447 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12448 << RCanPointeeTy->isIncompleteType();
12449 }
12450 }
12451 } else if (!IsRelational &&
12452 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12453 // Valid unless comparison between non-null pointer and function pointer
12454 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12455 && !LHSIsNull && !RHSIsNull)
12456 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12457 /*isError*/false);
12458 } else {
12459 // Invalid
12460 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12461 }
12462 if (LCanPointeeTy != RCanPointeeTy) {
12463 // Treat NULL constant as a special case in OpenCL.
12464 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12465 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12466 Diag(Loc,
12467 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12468 << LHSType << RHSType << 0 /* comparison */
12469 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12470 }
12471 }
12472 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12473 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12474 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12475 : CK_BitCast;
12476 if (LHSIsNull && !RHSIsNull)
12477 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12478 else
12479 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12480 }
12481 return computeResultTy();
12482 }
12483
12484 if (getLangOpts().CPlusPlus) {
12485 // C++ [expr.eq]p4:
12486 // Two operands of type std::nullptr_t or one operand of type
12487 // std::nullptr_t and the other a null pointer constant compare equal.
12488 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12489 if (LHSType->isNullPtrType()) {
12490 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12491 return computeResultTy();
12492 }
12493 if (RHSType->isNullPtrType()) {
12494 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12495 return computeResultTy();
12496 }
12497 }
12498
12499 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12500 // These aren't covered by the composite pointer type rules.
12501 if (!IsOrdered && RHSType->isNullPtrType() &&
12502 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12503 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12504 return computeResultTy();
12505 }
12506 if (!IsOrdered && LHSType->isNullPtrType() &&
12507 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12508 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12509 return computeResultTy();
12510 }
12511
12512 if (IsRelational &&
12513 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12514 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12515 // HACK: Relational comparison of nullptr_t against a pointer type is
12516 // invalid per DR583, but we allow it within std::less<> and friends,
12517 // since otherwise common uses of it break.
12518 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12519 // friends to have std::nullptr_t overload candidates.
12520 DeclContext *DC = CurContext;
12521 if (isa<FunctionDecl>(DC))
12522 DC = DC->getParent();
12523 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12524 if (CTSD->isInStdNamespace() &&
12525 llvm::StringSwitch<bool>(CTSD->getName())
12526 .Cases("less", "less_equal", "greater", "greater_equal", true)
12527 .Default(false)) {
12528 if (RHSType->isNullPtrType())
12529 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12530 else
12531 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12532 return computeResultTy();
12533 }
12534 }
12535 }
12536
12537 // C++ [expr.eq]p2:
12538 // If at least one operand is a pointer to member, [...] bring them to
12539 // their composite pointer type.
12540 if (!IsOrdered &&
12541 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12542 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12543 return QualType();
12544 else
12545 return computeResultTy();
12546 }
12547 }
12548
12549 // Handle block pointer types.
12550 if (!IsOrdered && LHSType->isBlockPointerType() &&
12551 RHSType->isBlockPointerType()) {
12552 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12553 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12554
12555 if (!LHSIsNull && !RHSIsNull &&
12556 !Context.typesAreCompatible(lpointee, rpointee)) {
12557 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12558 << LHSType << RHSType << LHS.get()->getSourceRange()
12559 << RHS.get()->getSourceRange();
12560 }
12561 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12562 return computeResultTy();
12563 }
12564
12565 // Allow block pointers to be compared with null pointer constants.
12566 if (!IsOrdered
12567 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12568 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12569 if (!LHSIsNull && !RHSIsNull) {
12570 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12571 ->getPointeeType()->isVoidType())
12572 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12573 ->getPointeeType()->isVoidType())))
12574 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12575 << LHSType << RHSType << LHS.get()->getSourceRange()
12576 << RHS.get()->getSourceRange();
12577 }
12578 if (LHSIsNull && !RHSIsNull)
12579 LHS = ImpCastExprToType(LHS.get(), RHSType,
12580 RHSType->isPointerType() ? CK_BitCast
12581 : CK_AnyPointerToBlockPointerCast);
12582 else
12583 RHS = ImpCastExprToType(RHS.get(), LHSType,
12584 LHSType->isPointerType() ? CK_BitCast
12585 : CK_AnyPointerToBlockPointerCast);
12586 return computeResultTy();
12587 }
12588
12589 if (LHSType->isObjCObjectPointerType() ||
12590 RHSType->isObjCObjectPointerType()) {
12591 const PointerType *LPT = LHSType->getAs<PointerType>();
12592 const PointerType *RPT = RHSType->getAs<PointerType>();
12593 if (LPT || RPT) {
12594 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12595 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12596
12597 if (!LPtrToVoid && !RPtrToVoid &&
12598 !Context.typesAreCompatible(LHSType, RHSType)) {
12599 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12600 /*isError*/false);
12601 }
12602 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12603 // the RHS, but we have test coverage for this behavior.
12604 // FIXME: Consider using convertPointersToCompositeType in C++.
12605 if (LHSIsNull && !RHSIsNull) {
12606 Expr *E = LHS.get();
12607 if (getLangOpts().ObjCAutoRefCount)
12608 CheckObjCConversion(SourceRange(), RHSType, E,
12609 CCK_ImplicitConversion);
12610 LHS = ImpCastExprToType(E, RHSType,
12611 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12612 }
12613 else {
12614 Expr *E = RHS.get();
12615 if (getLangOpts().ObjCAutoRefCount)
12616 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12617 /*Diagnose=*/true,
12618 /*DiagnoseCFAudited=*/false, Opc);
12619 RHS = ImpCastExprToType(E, LHSType,
12620 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12621 }
12622 return computeResultTy();
12623 }
12624 if (LHSType->isObjCObjectPointerType() &&
12625 RHSType->isObjCObjectPointerType()) {
12626 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12627 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12628 /*isError*/false);
12629 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12630 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12631
12632 if (LHSIsNull && !RHSIsNull)
12633 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12634 else
12635 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12636 return computeResultTy();
12637 }
12638
12639 if (!IsOrdered && LHSType->isBlockPointerType() &&
12640 RHSType->isBlockCompatibleObjCPointerType(Context)) {
12641 LHS = ImpCastExprToType(LHS.get(), RHSType,
12642 CK_BlockPointerToObjCPointerCast);
12643 return computeResultTy();
12644 } else if (!IsOrdered &&
12645 LHSType->isBlockCompatibleObjCPointerType(Context) &&
12646 RHSType->isBlockPointerType()) {
12647 RHS = ImpCastExprToType(RHS.get(), LHSType,
12648 CK_BlockPointerToObjCPointerCast);
12649 return computeResultTy();
12650 }
12651 }
12652 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12653 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12654 unsigned DiagID = 0;
12655 bool isError = false;
12656 if (LangOpts.DebuggerSupport) {
12657 // Under a debugger, allow the comparison of pointers to integers,
12658 // since users tend to want to compare addresses.
12659 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12660 (RHSIsNull && RHSType->isIntegerType())) {
12661 if (IsOrdered) {
12662 isError = getLangOpts().CPlusPlus;
12663 DiagID =
12664 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12665 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12666 }
12667 } else if (getLangOpts().CPlusPlus) {
12668 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12669 isError = true;
12670 } else if (IsOrdered)
12671 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12672 else
12673 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12674
12675 if (DiagID) {
12676 Diag(Loc, DiagID)
12677 << LHSType << RHSType << LHS.get()->getSourceRange()
12678 << RHS.get()->getSourceRange();
12679 if (isError)
12680 return QualType();
12681 }
12682
12683 if (LHSType->isIntegerType())
12684 LHS = ImpCastExprToType(LHS.get(), RHSType,
12685 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12686 else
12687 RHS = ImpCastExprToType(RHS.get(), LHSType,
12688 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12689 return computeResultTy();
12690 }
12691
12692 // Handle block pointers.
12693 if (!IsOrdered && RHSIsNull
12694 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12695 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12696 return computeResultTy();
12697 }
12698 if (!IsOrdered && LHSIsNull
12699 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12700 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12701 return computeResultTy();
12702 }
12703
12704 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12705 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12706 return computeResultTy();
12707 }
12708
12709 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12710 return computeResultTy();
12711 }
12712
12713 if (LHSIsNull && RHSType->isQueueT()) {
12714 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12715 return computeResultTy();
12716 }
12717
12718 if (LHSType->isQueueT() && RHSIsNull) {
12719 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12720 return computeResultTy();
12721 }
12722 }
12723
12724 return InvalidOperands(Loc, LHS, RHS);
12725}
12726
12727// Return a signed ext_vector_type that is of identical size and number of
12728// elements. For floating point vectors, return an integer type of identical
12729// size and number of elements. In the non ext_vector_type case, search from
12730// the largest type to the smallest type to avoid cases where long long == long,
12731// where long gets picked over long long.
12732QualType Sema::GetSignedVectorType(QualType V) {
12733 const VectorType *VTy = V->castAs<VectorType>();
12734 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12735
12736 if (isa<ExtVectorType>(VTy)) {
12737 if (VTy->isExtVectorBoolType())
12738 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
12739 if (TypeSize == Context.getTypeSize(Context.CharTy))
12740 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12741 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12742 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12743 if (TypeSize == Context.getTypeSize(Context.IntTy))
12744 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12745 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12746 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12747 if (TypeSize == Context.getTypeSize(Context.LongTy))
12748 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12749 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", 12750, __extension__ __PRETTY_FUNCTION__
))
12750 "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", 12750, __extension__ __PRETTY_FUNCTION__
))
;
12751 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12752 }
12753
12754 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12755 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12756 VectorType::GenericVector);
12757 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12758 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12759 VectorType::GenericVector);
12760 if (TypeSize == Context.getTypeSize(Context.LongTy))
12761 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12762 VectorType::GenericVector);
12763 if (TypeSize == Context.getTypeSize(Context.IntTy))
12764 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12765 VectorType::GenericVector);
12766 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12767 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12768 VectorType::GenericVector);
12769 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", 12770, __extension__ __PRETTY_FUNCTION__
))
12770 "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", 12770, __extension__ __PRETTY_FUNCTION__
))
;
12771 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12772 VectorType::GenericVector);
12773}
12774
12775QualType Sema::GetSignedSizelessVectorType(QualType V) {
12776 const BuiltinType *VTy = V->castAs<BuiltinType>();
12777 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", 12777, __extension__ __PRETTY_FUNCTION__
))
;
12778
12779 const QualType ETy = V->getSveEltType(Context);
12780 const auto TypeSize = Context.getTypeSize(ETy);
12781
12782 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12783 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12784 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12785}
12786
12787/// CheckVectorCompareOperands - vector comparisons are a clang extension that
12788/// operates on extended vector types. Instead of producing an IntTy result,
12789/// like a scalar comparison, a vector comparison produces a vector of integer
12790/// types.
12791QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12792 SourceLocation Loc,
12793 BinaryOperatorKind Opc) {
12794 if (Opc == BO_Cmp) {
12795 Diag(Loc, diag::err_three_way_vector_comparison);
12796 return QualType();
12797 }
12798
12799 // Check to make sure we're operating on vectors of the same type and width,
12800 // Allowing one side to be a scalar of element type.
12801 QualType vType =
12802 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12803 /*AllowBothBool*/ true,
12804 /*AllowBoolConversions*/ getLangOpts().ZVector,
12805 /*AllowBooleanOperation*/ true,
12806 /*ReportInvalid*/ true);
12807 if (vType.isNull())
12808 return vType;
12809
12810 QualType LHSType = LHS.get()->getType();
12811
12812 // Determine the return type of a vector compare. By default clang will return
12813 // a scalar for all vector compares except vector bool and vector pixel.
12814 // With the gcc compiler we will always return a vector type and with the xl
12815 // compiler we will always return a scalar type. This switch allows choosing
12816 // which behavior is prefered.
12817 if (getLangOpts().AltiVec) {
12818 switch (getLangOpts().getAltivecSrcCompat()) {
12819 case LangOptions::AltivecSrcCompatKind::Mixed:
12820 // If AltiVec, the comparison results in a numeric type, i.e.
12821 // bool for C++, int for C
12822 if (vType->castAs<VectorType>()->getVectorKind() ==
12823 VectorType::AltiVecVector)
12824 return Context.getLogicalOperationType();
12825 else
12826 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12827 break;
12828 case LangOptions::AltivecSrcCompatKind::GCC:
12829 // For GCC we always return the vector type.
12830 break;
12831 case LangOptions::AltivecSrcCompatKind::XL:
12832 return Context.getLogicalOperationType();
12833 break;
12834 }
12835 }
12836
12837 // For non-floating point types, check for self-comparisons of the form
12838 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12839 // often indicate logic errors in the program.
12840 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12841
12842 // Check for comparisons of floating point operands using != and ==.
12843 if (BinaryOperator::isEqualityOp(Opc) &&
12844 LHSType->hasFloatingRepresentation()) {
12845 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", 12845, __extension__ __PRETTY_FUNCTION__
))
;
12846 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12847 }
12848
12849 // Return a signed type for the vector.
12850 return GetSignedVectorType(vType);
12851}
12852
12853QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
12854 ExprResult &RHS,
12855 SourceLocation Loc,
12856 BinaryOperatorKind Opc) {
12857 if (Opc == BO_Cmp) {
12858 Diag(Loc, diag::err_three_way_vector_comparison);
12859 return QualType();
12860 }
12861
12862 // Check to make sure we're operating on vectors of the same type and width,
12863 // Allowing one side to be a scalar of element type.
12864 QualType vType = CheckSizelessVectorOperands(
12865 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12866
12867 if (vType.isNull())
12868 return vType;
12869
12870 QualType LHSType = LHS.get()->getType();
12871
12872 // For non-floating point types, check for self-comparisons of the form
12873 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12874 // often indicate logic errors in the program.
12875 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12876
12877 // Check for comparisons of floating point operands using != and ==.
12878 if (BinaryOperator::isEqualityOp(Opc) &&
12879 LHSType->hasFloatingRepresentation()) {
12880 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", 12880, __extension__ __PRETTY_FUNCTION__
))
;
12881 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12882 }
12883
12884 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12885 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12886
12887 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12888 RHSBuiltinTy->isSVEBool())
12889 return LHSType;
12890
12891 // Return a signed type for the vector.
12892 return GetSignedSizelessVectorType(vType);
12893}
12894
12895static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12896 const ExprResult &XorRHS,
12897 const SourceLocation Loc) {
12898 // Do not diagnose macros.
12899 if (Loc.isMacroID())
12900 return;
12901
12902 // Do not diagnose if both LHS and RHS are macros.
12903 if (XorLHS.get()->getExprLoc().isMacroID() &&
12904 XorRHS.get()->getExprLoc().isMacroID())
12905 return;
12906
12907 bool Negative = false;
12908 bool ExplicitPlus = false;
12909 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12910 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12911
12912 if (!LHSInt)
12913 return;
12914 if (!RHSInt) {
12915 // Check negative literals.
12916 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12917 UnaryOperatorKind Opc = UO->getOpcode();
12918 if (Opc != UO_Minus && Opc != UO_Plus)
12919 return;
12920 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12921 if (!RHSInt)
12922 return;
12923 Negative = (Opc == UO_Minus);
12924 ExplicitPlus = !Negative;
12925 } else {
12926 return;
12927 }
12928 }
12929
12930 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12931 llvm::APInt RightSideValue = RHSInt->getValue();
12932 if (LeftSideValue != 2 && LeftSideValue != 10)
12933 return;
12934
12935 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12936 return;
12937
12938 CharSourceRange ExprRange = CharSourceRange::getCharRange(
12939 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12940 llvm::StringRef ExprStr =
12941 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12942
12943 CharSourceRange XorRange =
12944 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12945 llvm::StringRef XorStr =
12946 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12947 // Do not diagnose if xor keyword/macro is used.
12948 if (XorStr == "xor")
12949 return;
12950
12951 std::string LHSStr = std::string(Lexer::getSourceText(
12952 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12953 S.getSourceManager(), S.getLangOpts()));
12954 std::string RHSStr = std::string(Lexer::getSourceText(
12955 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12956 S.getSourceManager(), S.getLangOpts()));
12957
12958 if (Negative) {
12959 RightSideValue = -RightSideValue;
12960 RHSStr = "-" + RHSStr;
12961 } else if (ExplicitPlus) {
12962 RHSStr = "+" + RHSStr;
12963 }
12964
12965 StringRef LHSStrRef = LHSStr;
12966 StringRef RHSStrRef = RHSStr;
12967 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12968 // literals.
12969 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12970 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12971 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12972 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12973 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12974 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12975 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12976 return;
12977
12978 bool SuggestXor =
12979 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12980 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12981 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12982 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12983 std::string SuggestedExpr = "1 << " + RHSStr;
12984 bool Overflow = false;
12985 llvm::APInt One = (LeftSideValue - 1);
12986 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12987 if (Overflow) {
12988 if (RightSideIntValue < 64)
12989 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12990 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12991 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12992 else if (RightSideIntValue == 64)
12993 S.Diag(Loc, diag::warn_xor_used_as_pow)
12994 << ExprStr << toString(XorValue, 10, true);
12995 else
12996 return;
12997 } else {
12998 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12999 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13000 << toString(PowValue, 10, true)
13001 << FixItHint::CreateReplacement(
13002 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13003 }
13004
13005 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13006 << ("0x2 ^ " + RHSStr) << SuggestXor;
13007 } else if (LeftSideValue == 10) {
13008 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13009 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13010 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13011 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13012 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13013 << ("0xA ^ " + RHSStr) << SuggestXor;
13014 }
13015}
13016
13017QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13018 SourceLocation Loc) {
13019 // Ensure that either both operands are of the same vector type, or
13020 // one operand is of a vector type and the other is of its element type.
13021 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13022 /*AllowBothBool*/ true,
13023 /*AllowBoolConversions*/ false,
13024 /*AllowBooleanOperation*/ false,
13025 /*ReportInvalid*/ false);
13026 if (vType.isNull())
13027 return InvalidOperands(Loc, LHS, RHS);
13028 if (getLangOpts().OpenCL &&
13029 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13030 vType->hasFloatingRepresentation())
13031 return InvalidOperands(Loc, LHS, RHS);
13032 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13033 // usage of the logical operators && and || with vectors in C. This
13034 // check could be notionally dropped.
13035 if (!getLangOpts().CPlusPlus &&
13036 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13037 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13038
13039 return GetSignedVectorType(LHS.get()->getType());
13040}
13041
13042QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13043 SourceLocation Loc,
13044 bool IsCompAssign) {
13045 if (!IsCompAssign) {
13046 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13047 if (LHS.isInvalid())
13048 return QualType();
13049 }
13050 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13051 if (RHS.isInvalid())
13052 return QualType();
13053
13054 // For conversion purposes, we ignore any qualifiers.
13055 // For example, "const float" and "float" are equivalent.
13056 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13057 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13058
13059 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13060 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13061 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", 13061, __extension__ __PRETTY_FUNCTION__
))
;
13062
13063 if (Context.hasSameType(LHSType, RHSType))
13064 return LHSType;
13065
13066 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13067 // case we have to return InvalidOperands.
13068 ExprResult OriginalLHS = LHS;
13069 ExprResult OriginalRHS = RHS;
13070 if (LHSMatType && !RHSMatType) {
13071 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13072 if (!RHS.isInvalid())
13073 return LHSType;
13074
13075 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13076 }
13077
13078 if (!LHSMatType && RHSMatType) {
13079 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13080 if (!LHS.isInvalid())
13081 return RHSType;
13082 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13083 }
13084
13085 return InvalidOperands(Loc, LHS, RHS);
13086}
13087
13088QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13089 SourceLocation Loc,
13090 bool IsCompAssign) {
13091 if (!IsCompAssign) {
13092 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13093 if (LHS.isInvalid())
13094 return QualType();
13095 }
13096 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13097 if (RHS.isInvalid())
13098 return QualType();
13099
13100 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13101 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13102 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", 13102, __extension__ __PRETTY_FUNCTION__
))
;
13103
13104 if (LHSMatType && RHSMatType) {
13105 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13106 return InvalidOperands(Loc, LHS, RHS);
13107
13108 if (!Context.hasSameType(LHSMatType->getElementType(),
13109 RHSMatType->getElementType()))
13110 return InvalidOperands(Loc, LHS, RHS);
13111
13112 return Context.getConstantMatrixType(LHSMatType->getElementType(),
13113 LHSMatType->getNumRows(),
13114 RHSMatType->getNumColumns());
13115 }
13116 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13117}
13118
13119static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13120 switch (Opc) {
13121 default:
13122 return false;
13123 case BO_And:
13124 case BO_AndAssign:
13125 case BO_Or:
13126 case BO_OrAssign:
13127 case BO_Xor:
13128 case BO_XorAssign:
13129 return true;
13130 }
13131}
13132
13133inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13134 SourceLocation Loc,
13135 BinaryOperatorKind Opc) {
13136 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13137
13138 bool IsCompAssign =
13139 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13140
13141 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13142
13143 if (LHS.get()->getType()->isVectorType() ||
13144 RHS.get()->getType()->isVectorType()) {
13145 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13146 RHS.get()->getType()->hasIntegerRepresentation())
13147 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13148 /*AllowBothBool*/ true,
13149 /*AllowBoolConversions*/ getLangOpts().ZVector,
13150 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13151 /*ReportInvalid*/ true);
13152 return InvalidOperands(Loc, LHS, RHS);
13153 }
13154
13155 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13156 RHS.get()->getType()->isVLSTBuiltinType()) {
13157 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13158 RHS.get()->getType()->hasIntegerRepresentation())
13159 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13160 ACK_BitwiseOp);
13161 return InvalidOperands(Loc, LHS, RHS);
13162 }
13163
13164 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13165 RHS.get()->getType()->isVLSTBuiltinType()) {
13166 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13167 RHS.get()->getType()->hasIntegerRepresentation())
13168 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13169 ACK_BitwiseOp);
13170 return InvalidOperands(Loc, LHS, RHS);
13171 }
13172
13173 if (Opc == BO_And)
13174 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13175
13176 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13177 RHS.get()->getType()->hasFloatingRepresentation())
13178 return InvalidOperands(Loc, LHS, RHS);
13179
13180 ExprResult LHSResult = LHS, RHSResult = RHS;
13181 QualType compType = UsualArithmeticConversions(
13182 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13183 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13184 return QualType();
13185 LHS = LHSResult.get();
13186 RHS = RHSResult.get();
13187
13188 if (Opc == BO_Xor)
13189 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13190
13191 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13192 return compType;
13193 return InvalidOperands(Loc, LHS, RHS);
13194}
13195
13196// C99 6.5.[13,14]
13197inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13198 SourceLocation Loc,
13199 BinaryOperatorKind Opc) {
13200 // Check vector operands differently.
13201 if (LHS.get()->getType()->isVectorType() ||
13202 RHS.get()->getType()->isVectorType())
13203 return CheckVectorLogicalOperands(LHS, RHS, Loc);
13204
13205 bool EnumConstantInBoolContext = false;
13206 for (const ExprResult &HS : {LHS, RHS}) {
13207 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13208 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13209 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13210 EnumConstantInBoolContext = true;
13211 }
13212 }
13213
13214 if (EnumConstantInBoolContext)
13215 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13216
13217 // Diagnose cases where the user write a logical and/or but probably meant a
13218 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13219 // is a constant.
13220 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13221 !LHS.get()->getType()->isBooleanType() &&
13222 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13223 // Don't warn in macros or template instantiations.
13224 !Loc.isMacroID() && !inTemplateInstantiation()) {
13225 // If the RHS can be constant folded, and if it constant folds to something
13226 // that isn't 0 or 1 (which indicate a potential logical operation that
13227 // happened to fold to true/false) then warn.
13228 // Parens on the RHS are ignored.
13229 Expr::EvalResult EVResult;
13230 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13231 llvm::APSInt Result = EVResult.Val.getInt();
13232 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13233 !RHS.get()->getExprLoc().isMacroID()) ||
13234 (Result != 0 && Result != 1)) {
13235 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13236 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13237 // Suggest replacing the logical operator with the bitwise version
13238 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13239 << (Opc == BO_LAnd ? "&" : "|")
13240 << FixItHint::CreateReplacement(
13241 SourceRange(Loc, getLocForEndOfToken(Loc)),
13242 Opc == BO_LAnd ? "&" : "|");
13243 if (Opc == BO_LAnd)
13244 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13245 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13246 << FixItHint::CreateRemoval(
13247 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13248 RHS.get()->getEndLoc()));
13249 }
13250 }
13251 }
13252
13253 if (!Context.getLangOpts().CPlusPlus) {
13254 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13255 // not operate on the built-in scalar and vector float types.
13256 if (Context.getLangOpts().OpenCL &&
13257 Context.getLangOpts().OpenCLVersion < 120) {
13258 if (LHS.get()->getType()->isFloatingType() ||
13259 RHS.get()->getType()->isFloatingType())
13260 return InvalidOperands(Loc, LHS, RHS);
13261 }
13262
13263 LHS = UsualUnaryConversions(LHS.get());
13264 if (LHS.isInvalid())
13265 return QualType();
13266
13267 RHS = UsualUnaryConversions(RHS.get());
13268 if (RHS.isInvalid())
13269 return QualType();
13270
13271 if (!LHS.get()->getType()->isScalarType() ||
13272 !RHS.get()->getType()->isScalarType())
13273 return InvalidOperands(Loc, LHS, RHS);
13274
13275 return Context.IntTy;
13276 }
13277
13278 // The following is safe because we only use this method for
13279 // non-overloadable operands.
13280
13281 // C++ [expr.log.and]p1
13282 // C++ [expr.log.or]p1
13283 // The operands are both contextually converted to type bool.
13284 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13285 if (LHSRes.isInvalid())
13286 return InvalidOperands(Loc, LHS, RHS);
13287 LHS = LHSRes;
13288
13289 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13290 if (RHSRes.isInvalid())
13291 return InvalidOperands(Loc, LHS, RHS);
13292 RHS = RHSRes;
13293
13294 // C++ [expr.log.and]p2
13295 // C++ [expr.log.or]p2
13296 // The result is a bool.
13297 return Context.BoolTy;
13298}
13299
13300static bool IsReadonlyMessage(Expr *E, Sema &S) {
13301 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13302 if (!ME) return false;
13303 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13304 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13305 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13306 if (!Base) return false;
13307 return Base->getMethodDecl() != nullptr;
13308}
13309
13310/// Is the given expression (which must be 'const') a reference to a
13311/// variable which was originally non-const, but which has become
13312/// 'const' due to being captured within a block?
13313enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13314static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13315 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", 13315, __extension__ __PRETTY_FUNCTION__
))
;
13316 E = E->IgnoreParens();
13317
13318 // Must be a reference to a declaration from an enclosing scope.
13319 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13320 if (!DRE) return NCCK_None;
13321 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13322
13323 // The declaration must be a variable which is not declared 'const'.
13324 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13325 if (!var) return NCCK_None;
13326 if (var->getType().isConstQualified()) return NCCK_None;
13327 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", 13327, __extension__ __PRETTY_FUNCTION__
))
;
13328
13329 // Decide whether the first capture was for a block or a lambda.
13330 DeclContext *DC = S.CurContext, *Prev = nullptr;
13331 // Decide whether the first capture was for a block or a lambda.
13332 while (DC) {
13333 // For init-capture, it is possible that the variable belongs to the
13334 // template pattern of the current context.
13335 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13336 if (var->isInitCapture() &&
13337 FD->getTemplateInstantiationPattern() == var->getDeclContext())
13338 break;
13339 if (DC == var->getDeclContext())
13340 break;
13341 Prev = DC;
13342 DC = DC->getParent();
13343 }
13344 // Unless we have an init-capture, we've gone one step too far.
13345 if (!var->isInitCapture())
13346 DC = Prev;
13347 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13348}
13349
13350static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13351 Ty = Ty.getNonReferenceType();
13352 if (IsDereference && Ty->isPointerType())
13353 Ty = Ty->getPointeeType();
13354 return !Ty.isConstQualified();
13355}
13356
13357// Update err_typecheck_assign_const and note_typecheck_assign_const
13358// when this enum is changed.
13359enum {
13360 ConstFunction,
13361 ConstVariable,
13362 ConstMember,
13363 ConstMethod,
13364 NestedConstMember,
13365 ConstUnknown, // Keep as last element
13366};
13367
13368/// Emit the "read-only variable not assignable" error and print notes to give
13369/// more information about why the variable is not assignable, such as pointing
13370/// to the declaration of a const variable, showing that a method is const, or
13371/// that the function is returning a const reference.
13372static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13373 SourceLocation Loc) {
13374 SourceRange ExprRange = E->getSourceRange();
13375
13376 // Only emit one error on the first const found. All other consts will emit
13377 // a note to the error.
13378 bool DiagnosticEmitted = false;
13379
13380 // Track if the current expression is the result of a dereference, and if the
13381 // next checked expression is the result of a dereference.
13382 bool IsDereference = false;
13383 bool NextIsDereference = false;
13384
13385 // Loop to process MemberExpr chains.
13386 while (true) {
13387 IsDereference = NextIsDereference;
13388
13389 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13390 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13391 NextIsDereference = ME->isArrow();
13392 const ValueDecl *VD = ME->getMemberDecl();
13393 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13394 // Mutable fields can be modified even if the class is const.
13395 if (Field->isMutable()) {
13396 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", 13396, __extension__ __PRETTY_FUNCTION__
))
;
13397 break;
13398 }
13399
13400 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13401 if (!DiagnosticEmitted) {
13402 S.Diag(Loc, diag::err_typecheck_assign_const)
13403 << ExprRange << ConstMember << false /*static*/ << Field
13404 << Field->getType();
13405 DiagnosticEmitted = true;
13406 }
13407 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13408 << ConstMember << false /*static*/ << Field << Field->getType()
13409 << Field->getSourceRange();
13410 }
13411 E = ME->getBase();
13412 continue;
13413 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13414 if (VDecl->getType().isConstQualified()) {
13415 if (!DiagnosticEmitted) {
13416 S.Diag(Loc, diag::err_typecheck_assign_const)
13417 << ExprRange << ConstMember << true /*static*/ << VDecl
13418 << VDecl->getType();
13419 DiagnosticEmitted = true;
13420 }
13421 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13422 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13423 << VDecl->getSourceRange();
13424 }
13425 // Static fields do not inherit constness from parents.
13426 break;
13427 }
13428 break; // End MemberExpr
13429 } else if (const ArraySubscriptExpr *ASE =
13430 dyn_cast<ArraySubscriptExpr>(E)) {
13431 E = ASE->getBase()->IgnoreParenImpCasts();
13432 continue;
13433 } else if (const ExtVectorElementExpr *EVE =
13434 dyn_cast<ExtVectorElementExpr>(E)) {
13435 E = EVE->getBase()->IgnoreParenImpCasts();
13436 continue;
13437 }
13438 break;
13439 }
13440
13441 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13442 // Function calls
13443 const FunctionDecl *FD = CE->getDirectCallee();
13444 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13445 if (!DiagnosticEmitted) {
13446 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13447 << ConstFunction << FD;
13448 DiagnosticEmitted = true;
13449 }
13450 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13451 diag::note_typecheck_assign_const)
13452 << ConstFunction << FD << FD->getReturnType()
13453 << FD->getReturnTypeSourceRange();
13454 }
13455 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13456 // Point to variable declaration.
13457 if (const ValueDecl *VD = DRE->getDecl()) {
13458 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13459 if (!DiagnosticEmitted) {
13460 S.Diag(Loc, diag::err_typecheck_assign_const)
13461 << ExprRange << ConstVariable << VD << VD->getType();
13462 DiagnosticEmitted = true;
13463 }
13464 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13465 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13466 }
13467 }
13468 } else if (isa<CXXThisExpr>(E)) {
13469 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13470 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13471 if (MD->isConst()) {
13472 if (!DiagnosticEmitted) {
13473 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13474 << ConstMethod << MD;
13475 DiagnosticEmitted = true;
13476 }
13477 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13478 << ConstMethod << MD << MD->getSourceRange();
13479 }
13480 }
13481 }
13482 }
13483
13484 if (DiagnosticEmitted)
13485 return;
13486
13487 // Can't determine a more specific message, so display the generic error.
13488 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13489}
13490
13491enum OriginalExprKind {
13492 OEK_Variable,
13493 OEK_Member,
13494 OEK_LValue
13495};
13496
13497static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13498 const RecordType *Ty,
13499 SourceLocation Loc, SourceRange Range,
13500 OriginalExprKind OEK,
13501 bool &DiagnosticEmitted) {
13502 std::vector<const RecordType *> RecordTypeList;
13503 RecordTypeList.push_back(Ty);
13504 unsigned NextToCheckIndex = 0;
13505 // We walk the record hierarchy breadth-first to ensure that we print
13506 // diagnostics in field nesting order.
13507 while (RecordTypeList.size() > NextToCheckIndex) {
13508 bool IsNested = NextToCheckIndex > 0;
13509 for (const FieldDecl *Field :
13510 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13511 // First, check every field for constness.
13512 QualType FieldTy = Field->getType();
13513 if (FieldTy.isConstQualified()) {
13514 if (!DiagnosticEmitted) {
13515 S.Diag(Loc, diag::err_typecheck_assign_const)
13516 << Range << NestedConstMember << OEK << VD
13517 << IsNested << Field;
13518 DiagnosticEmitted = true;
13519 }
13520 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13521 << NestedConstMember << IsNested << Field
13522 << FieldTy << Field->getSourceRange();
13523 }
13524
13525 // Then we append it to the list to check next in order.
13526 FieldTy = FieldTy.getCanonicalType();
13527 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13528 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13529 RecordTypeList.push_back(FieldRecTy);
13530 }
13531 }
13532 ++NextToCheckIndex;
13533 }
13534}
13535
13536/// Emit an error for the case where a record we are trying to assign to has a
13537/// const-qualified field somewhere in its hierarchy.
13538static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13539 SourceLocation Loc) {
13540 QualType Ty = E->getType();
13541 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", 13541, __extension__ __PRETTY_FUNCTION__
))
;
13542 SourceRange Range = E->getSourceRange();
13543 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13544 bool DiagEmitted = false;
13545
13546 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13547 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13548 Range, OEK_Member, DiagEmitted);
13549 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13550 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13551 Range, OEK_Variable, DiagEmitted);
13552 else
13553 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13554 Range, OEK_LValue, DiagEmitted);
13555 if (!DiagEmitted)
13556 DiagnoseConstAssignment(S, E, Loc);
13557}
13558
13559/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13560/// emit an error and return true. If so, return false.
13561static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13562 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", 13562, __extension__ __PRETTY_FUNCTION__
))
;
13563
13564 S.CheckShadowingDeclModification(E, Loc);
13565
13566 SourceLocation OrigLoc = Loc;
13567 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13568 &Loc);
13569 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13570 IsLV = Expr::MLV_InvalidMessageExpression;
13571 if (IsLV == Expr::MLV_Valid)
13572 return false;
13573
13574 unsigned DiagID = 0;
13575 bool NeedType = false;
13576 switch (IsLV) { // C99 6.5.16p2
13577 case Expr::MLV_ConstQualified:
13578 // Use a specialized diagnostic when we're assigning to an object
13579 // from an enclosing function or block.
13580 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13581 if (NCCK == NCCK_Block)
13582 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13583 else
13584 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13585 break;
13586 }
13587
13588 // In ARC, use some specialized diagnostics for occasions where we
13589 // infer 'const'. These are always pseudo-strong variables.
13590 if (S.getLangOpts().ObjCAutoRefCount) {
13591 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13592 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13593 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13594
13595 // Use the normal diagnostic if it's pseudo-__strong but the
13596 // user actually wrote 'const'.
13597 if (var->isARCPseudoStrong() &&
13598 (!var->getTypeSourceInfo() ||
13599 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13600 // There are three pseudo-strong cases:
13601 // - self
13602 ObjCMethodDecl *method = S.getCurMethodDecl();
13603 if (method && var == method->getSelfDecl()) {
13604 DiagID = method->isClassMethod()
13605 ? diag::err_typecheck_arc_assign_self_class_method
13606 : diag::err_typecheck_arc_assign_self;
13607
13608 // - Objective-C externally_retained attribute.
13609 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13610 isa<ParmVarDecl>(var)) {
13611 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13612
13613 // - fast enumeration variables
13614 } else {
13615 DiagID = diag::err_typecheck_arr_assign_enumeration;
13616 }
13617
13618 SourceRange Assign;
13619 if (Loc != OrigLoc)
13620 Assign = SourceRange(OrigLoc, OrigLoc);
13621 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13622 // We need to preserve the AST regardless, so migration tool
13623 // can do its job.
13624 return false;
13625 }
13626 }
13627 }
13628
13629 // If none of the special cases above are triggered, then this is a
13630 // simple const assignment.
13631 if (DiagID == 0) {
13632 DiagnoseConstAssignment(S, E, Loc);
13633 return true;
13634 }
13635
13636 break;
13637 case Expr::MLV_ConstAddrSpace:
13638 DiagnoseConstAssignment(S, E, Loc);
13639 return true;
13640 case Expr::MLV_ConstQualifiedField:
13641 DiagnoseRecursiveConstFields(S, E, Loc);
13642 return true;
13643 case Expr::MLV_ArrayType:
13644 case Expr::MLV_ArrayTemporary:
13645 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13646 NeedType = true;
13647 break;
13648 case Expr::MLV_NotObjectType:
13649 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13650 NeedType = true;
13651 break;
13652 case Expr::MLV_LValueCast:
13653 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13654 break;
13655 case Expr::MLV_Valid:
13656 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", 13656)
;
13657 case Expr::MLV_InvalidExpression:
13658 case Expr::MLV_MemberFunction:
13659 case Expr::MLV_ClassTemporary:
13660 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13661 break;
13662 case Expr::MLV_IncompleteType:
13663 case Expr::MLV_IncompleteVoidType:
13664 return S.RequireCompleteType(Loc, E->getType(),
13665 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13666 case Expr::MLV_DuplicateVectorComponents:
13667 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13668 break;
13669 case Expr::MLV_NoSetterProperty:
13670 llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently"
, "clang/lib/Sema/SemaExpr.cpp", 13670)
;
13671 case Expr::MLV_InvalidMessageExpression:
13672 DiagID = diag::err_readonly_message_assignment;
13673 break;
13674 case Expr::MLV_SubObjCPropertySetting:
13675 DiagID = diag::err_no_subobject_property_setting;
13676 break;
13677 }
13678
13679 SourceRange Assign;
13680 if (Loc != OrigLoc)
13681 Assign = SourceRange(OrigLoc, OrigLoc);
13682 if (NeedType)
13683 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13684 else
13685 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13686 return true;
13687}
13688
13689static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13690 SourceLocation Loc,
13691 Sema &Sema) {
13692 if (Sema.inTemplateInstantiation())
13693 return;
13694 if (Sema.isUnevaluatedContext())
13695 return;
13696 if (Loc.isInvalid() || Loc.isMacroID())
13697 return;
13698 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13699 return;
13700
13701 // C / C++ fields
13702 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13703 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13704 if (ML && MR) {
13705 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13706 return;
13707 const ValueDecl *LHSDecl =
13708 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13709 const ValueDecl *RHSDecl =
13710 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13711 if (LHSDecl != RHSDecl)
13712 return;
13713 if (LHSDecl->getType().isVolatileQualified())
13714 return;
13715 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13716 if (RefTy->getPointeeType().isVolatileQualified())
13717 return;
13718
13719 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13720 }
13721
13722 // Objective-C instance variables
13723 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13724 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13725 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13726 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13727 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13728 if (RL && RR && RL->getDecl() == RR->getDecl())
13729 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13730 }
13731}
13732
13733// C99 6.5.16.1
13734QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13735 SourceLocation Loc,
13736 QualType CompoundType) {
13737 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", 13737, __extension__ __PRETTY_FUNCTION__
))
;
13738
13739 // Verify that LHS is a modifiable lvalue, and emit error if not.
13740 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13741 return QualType();
13742
13743 QualType LHSType = LHSExpr->getType();
13744 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13745 CompoundType;
13746 // OpenCL v1.2 s6.1.1.1 p2:
13747 // The half data type can only be used to declare a pointer to a buffer that
13748 // contains half values
13749 if (getLangOpts().OpenCL &&
13750 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13751 LHSType->isHalfType()) {
13752 Diag(Loc, diag::err_opencl_half_load_store) << 1
13753 << LHSType.getUnqualifiedType();
13754 return QualType();
13755 }
13756
13757 AssignConvertType ConvTy;
13758 if (CompoundType.isNull()) {
13759 Expr *RHSCheck = RHS.get();
13760
13761 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13762
13763 QualType LHSTy(LHSType);
13764 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13765 if (RHS.isInvalid())
13766 return QualType();
13767 // Special case of NSObject attributes on c-style pointer types.
13768 if (ConvTy == IncompatiblePointer &&
13769 ((Context.isObjCNSObjectType(LHSType) &&
13770 RHSType->isObjCObjectPointerType()) ||
13771 (Context.isObjCNSObjectType(RHSType) &&
13772 LHSType->isObjCObjectPointerType())))
13773 ConvTy = Compatible;
13774
13775 if (ConvTy == Compatible &&
13776 LHSType->isObjCObjectType())
13777 Diag(Loc, diag::err_objc_object_assignment)
13778 << LHSType;
13779
13780 // If the RHS is a unary plus or minus, check to see if they = and + are
13781 // right next to each other. If so, the user may have typo'd "x =+ 4"
13782 // instead of "x += 4".
13783 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13784 RHSCheck = ICE->getSubExpr();
13785 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13786 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13787 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13788 // Only if the two operators are exactly adjacent.
13789 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13790 // And there is a space or other character before the subexpr of the
13791 // unary +/-. We don't want to warn on "x=-1".
13792 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13793 UO->getSubExpr()->getBeginLoc().isFileID()) {
13794 Diag(Loc, diag::warn_not_compound_assign)
13795 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13796 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13797 }
13798 }
13799
13800 if (ConvTy == Compatible) {
13801 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13802 // Warn about retain cycles where a block captures the LHS, but
13803 // not if the LHS is a simple variable into which the block is
13804 // being stored...unless that variable can be captured by reference!
13805 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13806 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13807 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13808 checkRetainCycles(LHSExpr, RHS.get());
13809 }
13810
13811 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13812 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13813 // It is safe to assign a weak reference into a strong variable.
13814 // Although this code can still have problems:
13815 // id x = self.weakProp;
13816 // id y = self.weakProp;
13817 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13818 // paths through the function. This should be revisited if
13819 // -Wrepeated-use-of-weak is made flow-sensitive.
13820 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13821 // variable, which will be valid for the current autorelease scope.
13822 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13823 RHS.get()->getBeginLoc()))
13824 getCurFunction()->markSafeWeakUse(RHS.get());
13825
13826 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13827 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13828 }
13829 }
13830 } else {
13831 // Compound assignment "x += y"
13832 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13833 }
13834
13835 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13836 RHS.get(), AA_Assigning))
13837 return QualType();
13838
13839 CheckForNullPointerDereference(*this, LHSExpr);
13840
13841 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13842 if (CompoundType.isNull()) {
13843 // C++2a [expr.ass]p5:
13844 // A simple-assignment whose left operand is of a volatile-qualified
13845 // type is deprecated unless the assignment is either a discarded-value
13846 // expression or an unevaluated operand
13847 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13848 } else {
13849 // C++2a [expr.ass]p6:
13850 // [Compound-assignment] expressions are deprecated if E1 has
13851 // volatile-qualified type
13852 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13853 }
13854 }
13855
13856 // C11 6.5.16p3: The type of an assignment expression is the type of the
13857 // left operand would have after lvalue conversion.
13858 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13859 // qualified type, the value has the unqualified version of the type of the
13860 // lvalue; additionally, if the lvalue has atomic type, the value has the
13861 // non-atomic version of the type of the lvalue.
13862 // C++ 5.17p1: the type of the assignment expression is that of its left
13863 // operand.
13864 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13865}
13866
13867// Only ignore explicit casts to void.
13868static bool IgnoreCommaOperand(const Expr *E) {
13869 E = E->IgnoreParens();
13870
13871 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13872 if (CE->getCastKind() == CK_ToVoid) {
13873 return true;
13874 }
13875
13876 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13877 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13878 CE->getSubExpr()->getType()->isDependentType()) {
13879 return true;
13880 }
13881 }
13882
13883 return false;
13884}
13885
13886// Look for instances where it is likely the comma operator is confused with
13887// another operator. There is an explicit list of acceptable expressions for
13888// the left hand side of the comma operator, otherwise emit a warning.
13889void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13890 // No warnings in macros
13891 if (Loc.isMacroID())
13892 return;
13893
13894 // Don't warn in template instantiations.
13895 if (inTemplateInstantiation())
13896 return;
13897
13898 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13899 // instead, skip more than needed, then call back into here with the
13900 // CommaVisitor in SemaStmt.cpp.
13901 // The listed locations are the initialization and increment portions
13902 // of a for loop. The additional checks are on the condition of
13903 // if statements, do/while loops, and for loops.
13904 // Differences in scope flags for C89 mode requires the extra logic.
13905 const unsigned ForIncrementFlags =
13906 getLangOpts().C99 || getLangOpts().CPlusPlus
13907 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13908 : Scope::ContinueScope | Scope::BreakScope;
13909 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13910 const unsigned ScopeFlags = getCurScope()->getFlags();
13911 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13912 (ScopeFlags & ForInitFlags) == ForInitFlags)
13913 return;
13914
13915 // If there are multiple comma operators used together, get the RHS of the
13916 // of the comma operator as the LHS.
13917 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13918 if (BO->getOpcode() != BO_Comma)
13919 break;
13920 LHS = BO->getRHS();
13921 }
13922
13923 // Only allow some expressions on LHS to not warn.
13924 if (IgnoreCommaOperand(LHS))
13925 return;
13926
13927 Diag(Loc, diag::warn_comma_operator);
13928 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13929 << LHS->getSourceRange()
13930 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13931 LangOpts.CPlusPlus ? "static_cast<void>("
13932 : "(void)(")
13933 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13934 ")");
13935}
13936
13937// C99 6.5.17
13938static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13939 SourceLocation Loc) {
13940 LHS = S.CheckPlaceholderExpr(LHS.get());
13941 RHS = S.CheckPlaceholderExpr(RHS.get());
13942 if (LHS.isInvalid() || RHS.isInvalid())
13943 return QualType();
13944
13945 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13946 // operands, but not unary promotions.
13947 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13948
13949 // So we treat the LHS as a ignored value, and in C++ we allow the
13950 // containing site to determine what should be done with the RHS.
13951 LHS = S.IgnoredValueConversions(LHS.get());
13952 if (LHS.isInvalid())
13953 return QualType();
13954
13955 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13956
13957 if (!S.getLangOpts().CPlusPlus) {
13958 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13959 if (RHS.isInvalid())
13960 return QualType();
13961 if (!RHS.get()->getType()->isVoidType())
13962 S.RequireCompleteType(Loc, RHS.get()->getType(),
13963 diag::err_incomplete_type);
13964 }
13965
13966 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13967 S.DiagnoseCommaOperator(LHS.get(), Loc);
13968
13969 return RHS.get()->getType();
13970}
13971
13972/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13973/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13974static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13975 ExprValueKind &VK,
13976 ExprObjectKind &OK,
13977 SourceLocation OpLoc,
13978 bool IsInc, bool IsPrefix) {
13979 if (Op->isTypeDependent())
13980 return S.Context.DependentTy;
13981
13982 QualType ResType = Op->getType();
13983 // Atomic types can be used for increment / decrement where the non-atomic
13984 // versions can, so ignore the _Atomic() specifier for the purpose of
13985 // checking.
13986 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13987 ResType = ResAtomicType->getValueType();
13988
13989 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", 13989, __extension__ __PRETTY_FUNCTION__
))
;
13990
13991 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13992 // Decrement of bool is not allowed.
13993 if (!IsInc) {
13994 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13995 return QualType();
13996 }
13997 // Increment of bool sets it to true, but is deprecated.
13998 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13999 : diag::warn_increment_bool)
14000 << Op->getSourceRange();
14001 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14002 // Error on enum increments and decrements in C++ mode
14003 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14004 return QualType();
14005 } else if (ResType->isRealType()) {
14006 // OK!
14007 } else if (ResType->isPointerType()) {
14008 // C99 6.5.2.4p2, 6.5.6p2
14009 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14010 return QualType();
14011 } else if (ResType->isObjCObjectPointerType()) {
14012 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14013 // Otherwise, we just need a complete type.
14014 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14015 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14016 return QualType();
14017 } else if (ResType->isAnyComplexType()) {
14018 // C99 does not support ++/-- on complex types, we allow as an extension.
14019 S.Diag(OpLoc, diag::ext_integer_increment_complex)
14020 << ResType << Op->getSourceRange();
14021 } else if (ResType->isPlaceholderType()) {
14022 ExprResult PR = S.CheckPlaceholderExpr(Op);
14023 if (PR.isInvalid()) return QualType();
14024 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14025 IsInc, IsPrefix);
14026 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14027 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14028 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14029 (ResType->castAs<VectorType>()->getVectorKind() !=
14030 VectorType::AltiVecBool)) {
14031 // The z vector extensions allow ++ and -- for non-bool vectors.
14032 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
14033 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14034 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14035 } else {
14036 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14037 << ResType << int(IsInc) << Op->getSourceRange();
14038 return QualType();
14039 }
14040 // At this point, we know we have a real, complex or pointer type.
14041 // Now make sure the operand is a modifiable lvalue.
14042 if (CheckForModifiableLvalue(Op, OpLoc, S))
14043 return QualType();
14044 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14045 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14046 // An operand with volatile-qualified type is deprecated
14047 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14048 << IsInc << ResType;
14049 }
14050 // In C++, a prefix increment is the same type as the operand. Otherwise
14051 // (in C or with postfix), the increment is the unqualified type of the
14052 // operand.
14053 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14054 VK = VK_LValue;
14055 OK = Op->getObjectKind();
14056 return ResType;
14057 } else {
14058 VK = VK_PRValue;
14059 return ResType.getUnqualifiedType();
14060 }
14061}
14062
14063
14064/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14065/// This routine allows us to typecheck complex/recursive expressions
14066/// where the declaration is needed for type checking. We only need to
14067/// handle cases when the expression references a function designator
14068/// or is an lvalue. Here are some examples:
14069/// - &(x) => x
14070/// - &*****f => f for f a function designator.
14071/// - &s.xx => s
14072/// - &s.zz[1].yy -> s, if zz is an array
14073/// - *(x + 1) -> x, if x is an array
14074/// - &"123"[2] -> 0
14075/// - & __real__ x -> x
14076///
14077/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14078/// members.
14079static ValueDecl *getPrimaryDecl(Expr *E) {
14080 switch (E->getStmtClass()) {
14081 case Stmt::DeclRefExprClass:
14082 return cast<DeclRefExpr>(E)->getDecl();
14083 case Stmt::MemberExprClass:
14084 // If this is an arrow operator, the address is an offset from
14085 // the base's value, so the object the base refers to is
14086 // irrelevant.
14087 if (cast<MemberExpr>(E)->isArrow())
14088 return nullptr;
14089 // Otherwise, the expression refers to a part of the base
14090 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14091 case Stmt::ArraySubscriptExprClass: {
14092 // FIXME: This code shouldn't be necessary! We should catch the implicit
14093 // promotion of register arrays earlier.
14094 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14095 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14096 if (ICE->getSubExpr()->getType()->isArrayType())
14097 return getPrimaryDecl(ICE->getSubExpr());
14098 }
14099 return nullptr;
14100 }
14101 case Stmt::UnaryOperatorClass: {
14102 UnaryOperator *UO = cast<UnaryOperator>(E);
14103
14104 switch(UO->getOpcode()) {
14105 case UO_Real:
14106 case UO_Imag:
14107 case UO_Extension:
14108 return getPrimaryDecl(UO->getSubExpr());
14109 default:
14110 return nullptr;
14111 }
14112 }
14113 case Stmt::ParenExprClass:
14114 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14115 case Stmt::ImplicitCastExprClass:
14116 // If the result of an implicit cast is an l-value, we care about
14117 // the sub-expression; otherwise, the result here doesn't matter.
14118 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14119 case Stmt::CXXUuidofExprClass:
14120 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14121 default:
14122 return nullptr;
14123 }
14124}
14125
14126namespace {
14127enum {
14128 AO_Bit_Field = 0,
14129 AO_Vector_Element = 1,
14130 AO_Property_Expansion = 2,
14131 AO_Register_Variable = 3,
14132 AO_Matrix_Element = 4,
14133 AO_No_Error = 5
14134};
14135}
14136/// Diagnose invalid operand for address of operations.
14137///
14138/// \param Type The type of operand which cannot have its address taken.
14139static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14140 Expr *E, unsigned Type) {
14141 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14142}
14143
14144/// CheckAddressOfOperand - The operand of & must be either a function
14145/// designator or an lvalue designating an object. If it is an lvalue, the
14146/// object cannot be declared with storage class register or be a bit field.
14147/// Note: The usual conversions are *not* applied to the operand of the &
14148/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14149/// In C++, the operand might be an overloaded function name, in which case
14150/// we allow the '&' but retain the overloaded-function type.
14151QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14152 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14153 if (PTy->getKind() == BuiltinType::Overload) {
14154 Expr *E = OrigOp.get()->IgnoreParens();
14155 if (!isa<OverloadExpr>(E)) {
14156 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", 14156, __extension__ __PRETTY_FUNCTION__
))
;
14157 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14158 << OrigOp.get()->getSourceRange();
14159 return QualType();
14160 }
14161
14162 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14163 if (isa<UnresolvedMemberExpr>(Ovl))
14164 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14165 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14166 << OrigOp.get()->getSourceRange();
14167 return QualType();
14168 }
14169
14170 return Context.OverloadTy;
14171 }
14172
14173 if (PTy->getKind() == BuiltinType::UnknownAny)
14174 return Context.UnknownAnyTy;
14175
14176 if (PTy->getKind() == BuiltinType::BoundMember) {
14177 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14178 << OrigOp.get()->getSourceRange();
14179 return QualType();
14180 }
14181
14182 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14183 if (OrigOp.isInvalid()) return QualType();
14184 }
14185
14186 if (OrigOp.get()->isTypeDependent())
14187 return Context.DependentTy;
14188
14189 assert(!OrigOp.get()->hasPlaceholderType())(static_cast <bool> (!OrigOp.get()->hasPlaceholderType
()) ? void (0) : __assert_fail ("!OrigOp.get()->hasPlaceholderType()"
, "clang/lib/Sema/SemaExpr.cpp", 14189, __extension__ __PRETTY_FUNCTION__
))
;
14190
14191 // Make sure to ignore parentheses in subsequent checks
14192 Expr *op = OrigOp.get()->IgnoreParens();
14193
14194 // In OpenCL captures for blocks called as lambda functions
14195 // are located in the private address space. Blocks used in
14196 // enqueue_kernel can be located in a different address space
14197 // depending on a vendor implementation. Thus preventing
14198 // taking an address of the capture to avoid invalid AS casts.
14199 if (LangOpts.OpenCL) {
14200 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14201 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14202 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14203 return QualType();
14204 }
14205 }
14206
14207 if (getLangOpts().C99) {
14208 // Implement C99-only parts of addressof rules.
14209 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14210 if (uOp->getOpcode() == UO_Deref)
14211 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14212 // (assuming the deref expression is valid).
14213 return uOp->getSubExpr()->getType();
14214 }
14215 // Technically, there should be a check for array subscript
14216 // expressions here, but the result of one is always an lvalue anyway.
14217 }
14218 ValueDecl *dcl = getPrimaryDecl(op);
14219
14220 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14221 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14222 op->getBeginLoc()))
14223 return QualType();
14224
14225 Expr::LValueClassification lval = op->ClassifyLValue(Context);
14226 unsigned AddressOfError = AO_No_Error;
14227
14228 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14229 bool sfinae = (bool)isSFINAEContext();
14230 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14231 : diag::ext_typecheck_addrof_temporary)
14232 << op->getType() << op->getSourceRange();
14233 if (sfinae)
14234 return QualType();
14235 // Materialize the temporary as an lvalue so that we can take its address.
14236 OrigOp = op =
14237 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14238 } else if (isa<ObjCSelectorExpr>(op)) {
14239 return Context.getPointerType(op->getType());
14240 } else if (lval == Expr::LV_MemberFunction) {
14241 // If it's an instance method, make a member pointer.
14242 // The expression must have exactly the form &A::foo.
14243
14244 // If the underlying expression isn't a decl ref, give up.
14245 if (!isa<DeclRefExpr>(op)) {
14246 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14247 << OrigOp.get()->getSourceRange();
14248 return QualType();
14249 }
14250 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14251 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14252
14253 // The id-expression was parenthesized.
14254 if (OrigOp.get() != DRE) {
14255 Diag(OpLoc, diag::err_parens_pointer_member_function)
14256 << OrigOp.get()->getSourceRange();
14257
14258 // The method was named without a qualifier.
14259 } else if (!DRE->getQualifier()) {
14260 if (MD->getParent()->getName().empty())
14261 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14262 << op->getSourceRange();
14263 else {
14264 SmallString<32> Str;
14265 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14266 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14267 << op->getSourceRange()
14268 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14269 }
14270 }
14271
14272 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14273 if (isa<CXXDestructorDecl>(MD))
14274 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14275
14276 QualType MPTy = Context.getMemberPointerType(
14277 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14278 // Under the MS ABI, lock down the inheritance model now.
14279 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14280 (void)isCompleteType(OpLoc, MPTy);
14281 return MPTy;
14282 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14283 // C99 6.5.3.2p1
14284 // The operand must be either an l-value or a function designator
14285 if (!op->getType()->isFunctionType()) {
14286 // Use a special diagnostic for loads from property references.
14287 if (isa<PseudoObjectExpr>(op)) {
14288 AddressOfError = AO_Property_Expansion;
14289 } else {
14290 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14291 << op->getType() << op->getSourceRange();
14292 return QualType();
14293 }
14294 }
14295 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14296 // The operand cannot be a bit-field
14297 AddressOfError = AO_Bit_Field;
14298 } else if (op->getObjectKind() == OK_VectorComponent) {
14299 // The operand cannot be an element of a vector
14300 AddressOfError = AO_Vector_Element;
14301 } else if (op->getObjectKind() == OK_MatrixComponent) {
14302 // The operand cannot be an element of a matrix.
14303 AddressOfError = AO_Matrix_Element;
14304 } else if (dcl) { // C99 6.5.3.2p1
14305 // We have an lvalue with a decl. Make sure the decl is not declared
14306 // with the register storage-class specifier.
14307 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14308 // in C++ it is not error to take address of a register
14309 // variable (c++03 7.1.1P3)
14310 if (vd->getStorageClass() == SC_Register &&
14311 !getLangOpts().CPlusPlus) {
14312 AddressOfError = AO_Register_Variable;
14313 }
14314 } else if (isa<MSPropertyDecl>(dcl)) {
14315 AddressOfError = AO_Property_Expansion;
14316 } else if (isa<FunctionTemplateDecl>(dcl)) {
14317 return Context.OverloadTy;
14318 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14319 // Okay: we can take the address of a field.
14320 // Could be a pointer to member, though, if there is an explicit
14321 // scope qualifier for the class.
14322 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14323 DeclContext *Ctx = dcl->getDeclContext();
14324 if (Ctx && Ctx->isRecord()) {
14325 if (dcl->getType()->isReferenceType()) {
14326 Diag(OpLoc,
14327 diag::err_cannot_form_pointer_to_member_of_reference_type)
14328 << dcl->getDeclName() << dcl->getType();
14329 return QualType();
14330 }
14331
14332 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14333 Ctx = Ctx->getParent();
14334
14335 QualType MPTy = Context.getMemberPointerType(
14336 op->getType(),
14337 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14338 // Under the MS ABI, lock down the inheritance model now.
14339 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14340 (void)isCompleteType(OpLoc, MPTy);
14341 return MPTy;
14342 }
14343 }
14344 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
14345 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
14346 llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type"
, "clang/lib/Sema/SemaExpr.cpp", 14346)
;
14347 }
14348
14349 if (AddressOfError != AO_No_Error) {
14350 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14351 return QualType();
14352 }
14353
14354 if (lval == Expr::LV_IncompleteVoidType) {
14355 // Taking the address of a void variable is technically illegal, but we
14356 // allow it in cases which are otherwise valid.
14357 // Example: "extern void x; void* y = &x;".
14358 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14359 }
14360
14361 // If the operand has type "type", the result has type "pointer to type".
14362 if (op->getType()->isObjCObjectType())
14363 return Context.getObjCObjectPointerType(op->getType());
14364
14365 CheckAddressOfPackedMember(op);
14366
14367 return Context.getPointerType(op->getType());
14368}
14369
14370static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14371 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14372 if (!DRE)
14373 return;
14374 const Decl *D = DRE->getDecl();
14375 if (!D)
14376 return;
14377 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14378 if (!Param)
14379 return;
14380 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14381 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14382 return;
14383 if (FunctionScopeInfo *FD = S.getCurFunction())
14384 if (!FD->ModifiedNonNullParams.count(Param))
14385 FD->ModifiedNonNullParams.insert(Param);
14386}
14387
14388/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14389static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14390 SourceLocation OpLoc) {
14391 if (Op->isTypeDependent())
14392 return S.Context.DependentTy;
14393
14394 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14395 if (ConvResult.isInvalid())
14396 return QualType();
14397 Op = ConvResult.get();
14398 QualType OpTy = Op->getType();
14399 QualType Result;
14400
14401 if (isa<CXXReinterpretCastExpr>(Op)) {
14402 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14403 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14404 Op->getSourceRange());
14405 }
14406
14407 if (const PointerType *PT = OpTy->getAs<PointerType>())
14408 {
14409 Result = PT->getPointeeType();
14410 }
14411 else if (const ObjCObjectPointerType *OPT =
14412 OpTy->getAs<ObjCObjectPointerType>())
14413 Result = OPT->getPointeeType();
14414 else {
14415 ExprResult PR = S.CheckPlaceholderExpr(Op);
14416 if (PR.isInvalid()) return QualType();
14417 if (PR.get() != Op)
14418 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14419 }
14420
14421 if (Result.isNull()) {
14422 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14423 << OpTy << Op->getSourceRange();
14424 return QualType();
14425 }
14426
14427 // Note that per both C89 and C99, indirection is always legal, even if Result
14428 // is an incomplete type or void. It would be possible to warn about
14429 // dereferencing a void pointer, but it's completely well-defined, and such a
14430 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
14431 // for pointers to 'void' but is fine for any other pointer type:
14432 //
14433 // C++ [expr.unary.op]p1:
14434 // [...] the expression to which [the unary * operator] is applied shall
14435 // be a pointer to an object type, or a pointer to a function type
14436 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
14437 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14438 << OpTy << Op->getSourceRange();
14439
14440 // Dereferences are usually l-values...
14441 VK = VK_LValue;
14442
14443 // ...except that certain expressions are never l-values in C.
14444 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14445 VK = VK_PRValue;
14446
14447 return Result;
14448}
14449
14450BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14451 BinaryOperatorKind Opc;
14452 switch (Kind) {
14453 default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "clang/lib/Sema/SemaExpr.cpp"
, 14453)
;
14454 case tok::periodstar: Opc = BO_PtrMemD; break;
14455 case tok::arrowstar: Opc = BO_PtrMemI; break;
14456 case tok::star: Opc = BO_Mul; break;
14457 case tok::slash: Opc = BO_Div; break;
14458 case tok::percent: Opc = BO_Rem; break;
14459 case tok::plus: Opc = BO_Add; break;
14460 case tok::minus: Opc = BO_Sub; break;
14461 case tok::lessless: Opc = BO_Shl; break;
14462 case tok::greatergreater: Opc = BO_Shr; break;
14463 case tok::lessequal: Opc = BO_LE; break;
14464 case tok::less: Opc = BO_LT; break;
14465 case tok::greaterequal: Opc = BO_GE; break;
14466 case tok::greater: Opc = BO_GT; break;
14467 case tok::exclaimequal: Opc = BO_NE; break;
14468 case tok::equalequal: Opc = BO_EQ; break;
14469 case tok::spaceship: Opc = BO_Cmp; break;
14470 case tok::amp: Opc = BO_And; break;
14471 case tok::caret: Opc = BO_Xor; break;
14472 case tok::pipe: Opc = BO_Or; break;
14473 case tok::ampamp: Opc = BO_LAnd; break;
14474 case tok::pipepipe: Opc = BO_LOr; break;
14475 case tok::equal: Opc = BO_Assign; break;
14476 case tok::starequal: Opc = BO_MulAssign; break;
14477 case tok::slashequal: Opc = BO_DivAssign; break;
14478 case tok::percentequal: Opc = BO_RemAssign; break;
14479 case tok::plusequal: Opc = BO_AddAssign; break;
14480 case tok::minusequal: Opc = BO_SubAssign; break;
14481 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14482 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14483 case tok::ampequal: Opc = BO_AndAssign; break;
14484 case tok::caretequal: Opc = BO_XorAssign; break;
14485 case tok::pipeequal: Opc = BO_OrAssign; break;
14486 case tok::comma: Opc = BO_Comma; break;
14487 }
14488 return Opc;
14489}
14490
14491static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14492 tok::TokenKind Kind) {
14493 UnaryOperatorKind Opc;
14494 switch (Kind) {
14495 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp"
, 14495)
;
14496 case tok::plusplus: Opc = UO_PreInc; break;
14497 case tok::minusminus: Opc = UO_PreDec; break;
14498 case tok::amp: Opc = UO_AddrOf; break;
14499 case tok::star: Opc = UO_Deref; break;
14500 case tok::plus: Opc = UO_Plus; break;
14501 case tok::minus: Opc = UO_Minus; break;
14502 case tok::tilde: Opc = UO_Not; break;
14503 case tok::exclaim: Opc = UO_LNot; break;
14504 case tok::kw___real: Opc = UO_Real; break;
14505 case tok::kw___imag: Opc = UO_Imag; break;
14506 case tok::kw___extension__: Opc = UO_Extension; break;
14507 }
14508 return Opc;
14509}
14510
14511/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14512/// This warning suppressed in the event of macro expansions.
14513static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14514 SourceLocation OpLoc, bool IsBuiltin) {
14515 if (S.inTemplateInstantiation())
14516 return;
14517 if (S.isUnevaluatedContext())
14518 return;
14519 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14520 return;
14521 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14522 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14523 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14524 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14525 if (!LHSDeclRef || !RHSDeclRef ||
14526 LHSDeclRef->getLocation().isMacroID() ||
14527 RHSDeclRef->getLocation().isMacroID())
14528 return;
14529 const ValueDecl *LHSDecl =
14530 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14531 const ValueDecl *RHSDecl =
14532 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14533 if (LHSDecl != RHSDecl)
14534 return;
14535 if (LHSDecl->getType().isVolatileQualified())
14536 return;
14537 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14538 if (RefTy->getPointeeType().isVolatileQualified())
14539 return;
14540
14541 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14542 : diag::warn_self_assignment_overloaded)
14543 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14544 << RHSExpr->getSourceRange();
14545}
14546
14547/// Check if a bitwise-& is performed on an Objective-C pointer. This
14548/// is usually indicative of introspection within the Objective-C pointer.
14549static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14550 SourceLocation OpLoc) {
14551 if (!S.getLangOpts().ObjC)
14552 return;
14553
14554 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14555 const Expr *LHS = L.get();
14556 const Expr *RHS = R.get();
14557
14558 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14559 ObjCPointerExpr = LHS;
14560 OtherExpr = RHS;
14561 }
14562 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14563 ObjCPointerExpr = RHS;
14564 OtherExpr = LHS;
14565 }
14566
14567 // This warning is deliberately made very specific to reduce false
14568 // positives with logic that uses '&' for hashing. This logic mainly
14569 // looks for code trying to introspect into tagged pointers, which
14570 // code should generally never do.
14571 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14572 unsigned Diag = diag::warn_objc_pointer_masking;
14573 // Determine if we are introspecting the result of performSelectorXXX.
14574 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14575 // Special case messages to -performSelector and friends, which
14576 // can return non-pointer values boxed in a pointer value.
14577 // Some clients may wish to silence warnings in this subcase.
14578 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14579 Selector S = ME->getSelector();
14580 StringRef SelArg0 = S.getNameForSlot(0);
14581 if (SelArg0.startswith("performSelector"))
14582 Diag = diag::warn_objc_pointer_masking_performSelector;
14583 }
14584
14585 S.Diag(OpLoc, Diag)
14586 << ObjCPointerExpr->getSourceRange();
14587 }
14588}
14589
14590static NamedDecl *getDeclFromExpr(Expr *E) {
14591 if (!E)
14592 return nullptr;
14593 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14594 return DRE->getDecl();
14595 if (auto *ME = dyn_cast<MemberExpr>(E))
14596 return ME->getMemberDecl();
14597 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14598 return IRE->getDecl();
14599 return nullptr;
14600}
14601
14602// This helper function promotes a binary operator's operands (which are of a
14603// half vector type) to a vector of floats and then truncates the result to
14604// a vector of either half or short.
14605static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14606 BinaryOperatorKind Opc, QualType ResultTy,
14607 ExprValueKind VK, ExprObjectKind OK,
14608 bool IsCompAssign, SourceLocation OpLoc,
14609 FPOptionsOverride FPFeatures) {
14610 auto &Context = S.getASTContext();
14611 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", 14613, __extension__ __PRETTY_FUNCTION__
))
14612 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", 14613, __extension__ __PRETTY_FUNCTION__
))
14613 "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", 14613, __extension__ __PRETTY_FUNCTION__
))
;
14614 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", 14616, __extension__ __PRETTY_FUNCTION__
))
14615 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", 14616, __extension__ __PRETTY_FUNCTION__
))
14616 "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", 14616, __extension__ __PRETTY_FUNCTION__
))
;
14617
14618 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14619 QualType BinOpResTy = RHS.get()->getType();
14620
14621 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14622 // change BinOpResTy to a vector of ints.
14623 if (isVector(ResultTy, Context.ShortTy))
14624 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14625
14626 if (IsCompAssign)
14627 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14628 ResultTy, VK, OK, OpLoc, FPFeatures,
14629 BinOpResTy, BinOpResTy);
14630
14631 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14632 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14633 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14634 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14635}
14636
14637static std::pair<ExprResult, ExprResult>
14638CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14639 Expr *RHSExpr) {
14640 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14641 if (!S.Context.isDependenceAllowed()) {
14642 // C cannot handle TypoExpr nodes on either side of a binop because it
14643 // doesn't handle dependent types properly, so make sure any TypoExprs have
14644 // been dealt with before checking the operands.
14645 LHS = S.CorrectDelayedTyposInExpr(LHS);
14646 RHS = S.CorrectDelayedTyposInExpr(
14647 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14648 [Opc, LHS](Expr *E) {
14649 if (Opc != BO_Assign)
14650 return ExprResult(E);
14651 // Avoid correcting the RHS to the same Expr as the LHS.
14652 Decl *D = getDeclFromExpr(E);
14653 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14654 });
14655 }
14656 return std::make_pair(LHS, RHS);
14657}
14658
14659/// Returns true if conversion between vectors of halfs and vectors of floats
14660/// is needed.
14661static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14662 Expr *E0, Expr *E1 = nullptr) {
14663 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14664 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14665 return false;
14666
14667 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14668 QualType Ty = E->IgnoreImplicit()->getType();
14669
14670 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14671 // to vectors of floats. Although the element type of the vectors is __fp16,
14672 // the vectors shouldn't be treated as storage-only types. See the
14673 // discussion here: https://reviews.llvm.org/rG825235c140e7
14674 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14675 if (VT->getVectorKind() == VectorType::NeonVector)
14676 return false;
14677 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14678 }
14679 return false;
14680 };
14681
14682 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14683}
14684
14685/// CreateBuiltinBinOp - Creates a new built-in binary operation with
14686/// operator @p Opc at location @c TokLoc. This routine only supports
14687/// built-in operations; ActOnBinOp handles overloaded operators.
14688ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14689 BinaryOperatorKind Opc,
14690 Expr *LHSExpr, Expr *RHSExpr) {
14691 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14692 // The syntax only allows initializer lists on the RHS of assignment,
14693 // so we don't need to worry about accepting invalid code for
14694 // non-assignment operators.
14695 // C++11 5.17p9:
14696 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14697 // of x = {} is x = T().
14698 InitializationKind Kind = InitializationKind::CreateDirectList(
14699 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14700 InitializedEntity Entity =
14701 InitializedEntity::InitializeTemporary(LHSExpr->getType());
14702 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14703 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14704 if (Init.isInvalid())
14705 return Init;
14706 RHSExpr = Init.get();
14707 }
14708
14709 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14710 QualType ResultTy; // Result type of the binary operator.
14711 // The following two variables are used for compound assignment operators
14712 QualType CompLHSTy; // Type of LHS after promotions for computation
14713 QualType CompResultTy; // Type of computation result
14714 ExprValueKind VK = VK_PRValue;
14715 ExprObjectKind OK = OK_Ordinary;
14716 bool ConvertHalfVec = false;
14717
14718 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14719 if (!LHS.isUsable() || !RHS.isUsable())
14720 return ExprError();
14721
14722 if (getLangOpts().OpenCL) {
14723 QualType LHSTy = LHSExpr->getType();
14724 QualType RHSTy = RHSExpr->getType();
14725 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14726 // the ATOMIC_VAR_INIT macro.
14727 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14728 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14729 if (BO_Assign == Opc)
14730 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14731 else
14732 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14733 return ExprError();
14734 }
14735
14736 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14737 // only with a builtin functions and therefore should be disallowed here.
14738 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14739 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14740 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14741 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14742 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14743 return ExprError();
14744 }
14745 }
14746
14747 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14748 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14749
14750 switch (Opc) {
14751 case BO_Assign:
14752 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14753 if (getLangOpts().CPlusPlus &&
14754 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14755 VK = LHS.get()->getValueKind();
14756 OK = LHS.get()->getObjectKind();
14757 }
14758 if (!ResultTy.isNull()) {
14759 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14760 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14761
14762 // Avoid copying a block to the heap if the block is assigned to a local
14763 // auto variable that is declared in the same scope as the block. This
14764 // optimization is unsafe if the local variable is declared in an outer
14765 // scope. For example:
14766 //
14767 // BlockTy b;
14768 // {
14769 // b = ^{...};
14770 // }
14771 // // It is unsafe to invoke the block here if it wasn't copied to the
14772 // // heap.
14773 // b();
14774
14775 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14776 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14777 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14778 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14779 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14780
14781 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14782 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14783 NTCUC_Assignment, NTCUK_Copy);
14784 }
14785 RecordModifiableNonNullParam(*this, LHS.get());
14786 break;
14787 case BO_PtrMemD:
14788 case BO_PtrMemI:
14789 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14790 Opc == BO_PtrMemI);
14791 break;
14792 case BO_Mul:
14793 case BO_Div:
14794 ConvertHalfVec = true;
14795 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14796 Opc == BO_Div);
14797 break;
14798 case BO_Rem:
14799 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14800 break;
14801 case BO_Add:
14802 ConvertHalfVec = true;
14803 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14804 break;
14805 case BO_Sub:
14806 ConvertHalfVec = true;
14807 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14808 break;
14809 case BO_Shl:
14810 case BO_Shr:
14811 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14812 break;
14813 case BO_LE:
14814 case BO_LT:
14815 case BO_GE:
14816 case BO_GT:
14817 ConvertHalfVec = true;
14818 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14819 break;
14820 case BO_EQ:
14821 case BO_NE:
14822 ConvertHalfVec = true;
14823 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14824 break;
14825 case BO_Cmp:
14826 ConvertHalfVec = true;
14827 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14828 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", 14828, __extension__ __PRETTY_FUNCTION__
))
;
14829 break;
14830 case BO_And:
14831 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14832 LLVM_FALLTHROUGH[[gnu::fallthrough]];
14833 case BO_Xor:
14834 case BO_Or:
14835 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14836 break;
14837 case BO_LAnd:
14838 case BO_LOr:
14839 ConvertHalfVec = true;
14840 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14841 break;
14842 case BO_MulAssign:
14843 case BO_DivAssign:
14844 ConvertHalfVec = true;
14845 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14846 Opc == BO_DivAssign);
14847 CompLHSTy = CompResultTy;
14848 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14849 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14850 break;
14851 case BO_RemAssign:
14852 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14853 CompLHSTy = CompResultTy;
14854 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14855 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14856 break;
14857 case BO_AddAssign:
14858 ConvertHalfVec = true;
14859 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14860 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14861 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14862 break;
14863 case BO_SubAssign:
14864 ConvertHalfVec = true;
14865 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14866 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14867 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14868 break;
14869 case BO_ShlAssign:
14870 case BO_ShrAssign:
14871 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14872 CompLHSTy = CompResultTy;
14873 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14874 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14875 break;
14876 case BO_AndAssign:
14877 case BO_OrAssign: // fallthrough
14878 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14879 LLVM_FALLTHROUGH[[gnu::fallthrough]];
14880 case BO_XorAssign:
14881 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14882 CompLHSTy = CompResultTy;
14883 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14884 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14885 break;
14886 case BO_Comma:
14887 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14888 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14889 VK = RHS.get()->getValueKind();
14890 OK = RHS.get()->getObjectKind();
14891 }
14892 break;
14893 }
14894 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14895 return ExprError();
14896
14897 // Some of the binary operations require promoting operands of half vector to
14898 // float vectors and truncating the result back to half vector. For now, we do
14899 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14900 // arm64).
14901 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", 14904, __extension__ __PRETTY_FUNCTION__
))
14902 (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", 14904, __extension__ __PRETTY_FUNCTION__
))
14903 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", 14904, __extension__ __PRETTY_FUNCTION__
))
14904 "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", 14904, __extension__ __PRETTY_FUNCTION__
))
;
14905 ConvertHalfVec =
14906 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14907
14908 // Check for array bounds violations for both sides of the BinaryOperator
14909 CheckArrayAccess(LHS.get());
14910 CheckArrayAccess(RHS.get());
14911
14912 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14913 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14914 &Context.Idents.get("object_setClass"),
14915 SourceLocation(), LookupOrdinaryName);
14916 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14917 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14918 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14919 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14920 "object_setClass(")
14921 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14922 ",")
14923 << FixItHint::CreateInsertion(RHSLocEnd, ")");
14924 }
14925 else
14926 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14927 }
14928 else if (const ObjCIvarRefExpr *OIRE =
14929 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14930 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14931
14932 // Opc is not a compound assignment if CompResultTy is null.
14933 if (CompResultTy.isNull()) {
14934 if (ConvertHalfVec)
14935 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14936 OpLoc, CurFPFeatureOverrides());
14937 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14938 VK, OK, OpLoc, CurFPFeatureOverrides());
14939 }
14940
14941 // Handle compound assignments.
14942 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14943 OK_ObjCProperty) {
14944 VK = VK_LValue;
14945 OK = LHS.get()->getObjectKind();
14946 }
14947
14948 // The LHS is not converted to the result type for fixed-point compound
14949 // assignment as the common type is computed on demand. Reset the CompLHSTy
14950 // to the LHS type we would have gotten after unary conversions.
14951 if (CompResultTy->isFixedPointType())
14952 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14953
14954 if (ConvertHalfVec)
14955 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14956 OpLoc, CurFPFeatureOverrides());
14957
14958 return CompoundAssignOperator::Create(
14959 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14960 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14961}
14962
14963/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14964/// operators are mixed in a way that suggests that the programmer forgot that
14965/// comparison operators have higher precedence. The most typical example of
14966/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14967static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14968 SourceLocation OpLoc, Expr *LHSExpr,
14969 Expr *RHSExpr) {
14970 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14971 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14972
14973 // Check that one of the sides is a comparison operator and the other isn't.
14974 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14975 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14976 if (isLeftComp == isRightComp)
14977 return;
14978
14979 // Bitwise operations are sometimes used as eager logical ops.
14980 // Don't diagnose this.
14981 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14982 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14983 if (isLeftBitwise || isRightBitwise)
14984 return;
14985
14986 SourceRange DiagRange = isLeftComp
14987 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14988 : SourceRange(OpLoc, RHSExpr->getEndLoc());
14989 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14990 SourceRange ParensRange =
14991 isLeftComp
14992 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14993 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14994
14995 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14996 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14997 SuggestParentheses(Self, OpLoc,
14998 Self.PDiag(diag::note_precedence_silence) << OpStr,
14999 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15000 SuggestParentheses(Self, OpLoc,
15001 Self.PDiag(diag::note_precedence_bitwise_first)
15002 << BinaryOperator::getOpcodeStr(Opc),
15003 ParensRange);
15004}
15005
15006/// It accepts a '&&' expr that is inside a '||' one.
15007/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15008/// in parentheses.
15009static void
15010EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15011 BinaryOperator *Bop) {
15012 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"
, 15012, __extension__ __PRETTY_FUNCTION__))
;
15013 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15014 << Bop->getSourceRange() << OpLoc;
15015 SuggestParentheses(Self, Bop->getOperatorLoc(),
15016 Self.PDiag(diag::note_precedence_silence)
15017 << Bop->getOpcodeStr(),
15018 Bop->getSourceRange());
15019}
15020
15021/// Returns true if the given expression can be evaluated as a constant
15022/// 'true'.
15023static bool EvaluatesAsTrue(Sema &S, Expr *E) {
15024 bool Res;
15025 return !E->isValueDependent() &&
15026 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
15027}
15028
15029/// Returns true if the given expression can be evaluated as a constant
15030/// 'false'.
15031static bool EvaluatesAsFalse(Sema &S, Expr *E) {
15032 bool Res;
15033 return !E->isValueDependent() &&
15034 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
15035}
15036
15037/// Look for '&&' in the left hand of a '||' expr.
15038static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15039 Expr *LHSExpr, Expr *RHSExpr) {
15040 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15041 if (Bop->getOpcode() == BO_LAnd) {
15042 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
15043 if (EvaluatesAsFalse(S, RHSExpr))
15044 return;
15045 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
15046 if (!EvaluatesAsTrue(S, Bop->getLHS()))
15047 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15048 } else if (Bop->getOpcode() == BO_LOr) {
15049 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15050 // If it's "a || b && 1 || c" we didn't warn earlier for
15051 // "a || b && 1", but warn now.
15052 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
15053 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15054 }
15055 }
15056 }
15057}
15058
15059/// Look for '&&' in the right hand of a '||' expr.
15060static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15061 Expr *LHSExpr, Expr *RHSExpr) {
15062 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15063 if (Bop->getOpcode() == BO_LAnd) {
15064 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
15065 if (EvaluatesAsFalse(S, LHSExpr))
15066 return;
15067 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
15068 if (!EvaluatesAsTrue(S, Bop->getRHS()))
15069 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15070 }
15071 }
15072}
15073
15074/// Look for bitwise op in the left or right hand of a bitwise op with
15075/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15076/// the '&' expression in parentheses.
15077static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15078 SourceLocation OpLoc, Expr *SubExpr) {
15079 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15080 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15081 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15082 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15083 << Bop->getSourceRange() << OpLoc;
15084 SuggestParentheses(S, Bop->getOperatorLoc(),
15085 S.PDiag(diag::note_precedence_silence)
15086 << Bop->getOpcodeStr(),
15087 Bop->getSourceRange());
15088 }
15089 }
15090}
15091
15092static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15093 Expr *SubExpr, StringRef Shift) {
15094 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15095 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15096 StringRef Op = Bop->getOpcodeStr();
15097 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15098 << Bop->getSourceRange() << OpLoc << Shift << Op;
15099 SuggestParentheses(S, Bop->getOperatorLoc(),
15100 S.PDiag(diag::note_precedence_silence) << Op,
15101 Bop->getSourceRange());
15102 }
15103 }
15104}
15105
15106static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15107 Expr *LHSExpr, Expr *RHSExpr) {
15108 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15109 if (!OCE)
15110 return;
15111
15112 FunctionDecl *FD = OCE->getDirectCallee();
15113 if (!FD || !FD->isOverloadedOperator())
15114 return;
15115
15116 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15117 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15118 return;
15119
15120 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15121 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15122 << (Kind == OO_LessLess);
15123 SuggestParentheses(S, OCE->getOperatorLoc(),
15124 S.PDiag(diag::note_precedence_silence)
15125 << (Kind == OO_LessLess ? "<<" : ">>"),
15126 OCE->getSourceRange());
15127 SuggestParentheses(
15128 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15129 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15130}
15131
15132/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15133/// precedence.
15134static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15135 SourceLocation OpLoc, Expr *LHSExpr,
15136 Expr *RHSExpr){
15137 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15138 if (BinaryOperator::isBitwiseOp(Opc))
15139 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15140
15141 // Diagnose "arg1 & arg2 | arg3"
15142 if ((Opc == BO_Or || Opc == BO_Xor) &&
15143 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15144 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15145 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15146 }
15147
15148 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15149 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15150 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15151 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15152 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15153 }
15154
15155 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15156 || Opc == BO_Shr) {
15157 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15158 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15159 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15160 }
15161
15162 // Warn on overloaded shift operators and comparisons, such as:
15163 // cout << 5 == 4;
15164 if (BinaryOperator::isComparisonOp(Opc))
15165 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15166}
15167
15168// Binary Operators. 'Tok' is the token for the operator.
15169ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15170 tok::TokenKind Kind,
15171 Expr *LHSExpr, Expr *RHSExpr) {
15172 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15173 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", 15173, __extension__ __PRETTY_FUNCTION__
))
;
15174 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", 15174, __extension__ __PRETTY_FUNCTION__
))
;
15175
15176 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15177 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15178
15179 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15180}
15181
15182void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15183 UnresolvedSetImpl &Functions) {
15184 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15185 if (OverOp != OO_None && OverOp != OO_Equal)
15186 LookupOverloadedOperatorName(OverOp, S, Functions);
15187
15188 // In C++20 onwards, we may have a second operator to look up.
15189 if (getLangOpts().CPlusPlus20) {
15190 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15191 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15192 }
15193}
15194
15195/// Build an overloaded binary operator expression in the given scope.
15196static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15197 BinaryOperatorKind Opc,
15198 Expr *LHS, Expr *RHS) {
15199 switch (Opc) {
15200 case BO_Assign:
15201 case BO_DivAssign:
15202 case BO_RemAssign:
15203 case BO_SubAssign:
15204 case BO_AndAssign:
15205 case BO_OrAssign:
15206 case BO_XorAssign:
15207 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15208 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15209 break;
15210 default:
15211 break;
15212 }
15213
15214 // Find all of the overloaded operators visible from this point.
15215 UnresolvedSet<16> Functions;
15216 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15217
15218 // Build the (potentially-overloaded, potentially-dependent)
15219 // binary operation.
15220 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15221}
15222
15223ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15224 BinaryOperatorKind Opc,
15225 Expr *LHSExpr, Expr *RHSExpr) {
15226 ExprResult LHS, RHS;
15227 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15228 if (!LHS.isUsable() || !RHS.isUsable())
15229 return ExprError();
15230 LHSExpr = LHS.get();
15231 RHSExpr = RHS.get();
15232
15233 // We want to end up calling one of checkPseudoObjectAssignment
15234 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15235 // both expressions are overloadable or either is type-dependent),
15236 // or CreateBuiltinBinOp (in any other case). We also want to get
15237 // any placeholder types out of the way.
15238
15239 // Handle pseudo-objects in the LHS.
15240 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15241 // Assignments with a pseudo-object l-value need special analysis.
15242 if (pty->getKind() == BuiltinType::PseudoObject &&
15243 BinaryOperator::isAssignmentOp(Opc))
15244 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15245
15246 // Don't resolve overloads if the other type is overloadable.
15247 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15248 // We can't actually test that if we still have a placeholder,
15249 // though. Fortunately, none of the exceptions we see in that
15250 // code below are valid when the LHS is an overload set. Note
15251 // that an overload set can be dependently-typed, but it never
15252 // instantiates to having an overloadable type.
15253 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15254 if (resolvedRHS.isInvalid()) return ExprError();
15255 RHSExpr = resolvedRHS.get();
15256
15257 if (RHSExpr->isTypeDependent() ||
15258 RHSExpr->getType()->isOverloadableType())
15259 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15260 }
15261
15262 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15263 // template, diagnose the missing 'template' keyword instead of diagnosing
15264 // an invalid use of a bound member function.
15265 //
15266 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15267 // to C++1z [over.over]/1.4, but we already checked for that case above.
15268 if (Opc == BO_LT && inTemplateInstantiation() &&
15269 (pty->getKind() == BuiltinType::BoundMember ||
15270 pty->getKind() == BuiltinType::Overload)) {
15271 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15272 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15273 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
15274 return isa<FunctionTemplateDecl>(ND);
15275 })) {
15276 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15277 : OE->getNameLoc(),
15278 diag::err_template_kw_missing)
15279 << OE->getName().getAsString() << "";
15280 return ExprError();
15281 }
15282 }
15283
15284 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15285 if (LHS.isInvalid()) return ExprError();
15286 LHSExpr = LHS.get();
15287 }
15288
15289 // Handle pseudo-objects in the RHS.
15290 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15291 // An overload in the RHS can potentially be resolved by the type
15292 // being assigned to.
15293 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15294 if (getLangOpts().CPlusPlus &&
15295 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15296 LHSExpr->getType()->isOverloadableType()))
15297 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15298
15299 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15300 }
15301
15302 // Don't resolve overloads if the other type is overloadable.
15303 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15304 LHSExpr->getType()->isOverloadableType())
15305 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15306
15307 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15308 if (!resolvedRHS.isUsable()) return ExprError();
15309 RHSExpr = resolvedRHS.get();
15310 }
15311
15312 if (getLangOpts().CPlusPlus) {
15313 // If either expression is type-dependent, always build an
15314 // overloaded op.
15315 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15316 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15317
15318 // Otherwise, build an overloaded op if either expression has an
15319 // overloadable type.
15320 if (LHSExpr->getType()->isOverloadableType() ||
15321 RHSExpr->getType()->isOverloadableType())
15322 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15323 }
15324
15325 if (getLangOpts().RecoveryAST &&
15326 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15327 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 15327, __extension__ __PRETTY_FUNCTION__))
;
15328 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", 15329, __extension__ __PRETTY_FUNCTION__
))
15329 "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", 15329, __extension__ __PRETTY_FUNCTION__
))
;
15330 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15331 // C [6.15.16] p3:
15332 // An assignment expression has the value of the left operand after the
15333 // assignment, but is not an lvalue.
15334 return CompoundAssignOperator::Create(
15335 Context, LHSExpr, RHSExpr, Opc,
15336 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15337 OpLoc, CurFPFeatureOverrides());
15338 QualType ResultType;
15339 switch (Opc) {
15340 case BO_Assign:
15341 ResultType = LHSExpr->getType().getUnqualifiedType();
15342 break;
15343 case BO_LT:
15344 case BO_GT:
15345 case BO_LE:
15346 case BO_GE:
15347 case BO_EQ:
15348 case BO_NE:
15349 case BO_LAnd:
15350 case BO_LOr:
15351 // These operators have a fixed result type regardless of operands.
15352 ResultType = Context.IntTy;
15353 break;
15354 case BO_Comma:
15355 ResultType = RHSExpr->getType();
15356 break;
15357 default:
15358 ResultType = Context.DependentTy;
15359 break;
15360 }
15361 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15362 VK_PRValue, OK_Ordinary, OpLoc,
15363 CurFPFeatureOverrides());
15364 }
15365
15366 // Build a built-in binary operation.
15367 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15368}
15369
15370static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15371 if (T.isNull() || T->isDependentType())
15372 return false;
15373
15374 if (!T->isPromotableIntegerType())
15375 return true;
15376
15377 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15378}
15379
15380ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15381 UnaryOperatorKind Opc,
15382 Expr *InputExpr) {
15383 ExprResult Input = InputExpr;
15384 ExprValueKind VK = VK_PRValue;
15385 ExprObjectKind OK = OK_Ordinary;
15386 QualType resultType;
15387 bool CanOverflow = false;
15388
15389 bool ConvertHalfVec = false;
15390 if (getLangOpts().OpenCL) {
15391 QualType Ty = InputExpr->getType();
15392 // The only legal unary operation for atomics is '&'.
15393 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15394 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15395 // only with a builtin functions and therefore should be disallowed here.
15396 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15397 || Ty->isBlockPointerType())) {
15398 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15399 << InputExpr->getType()
15400 << Input.get()->getSourceRange());
15401 }
15402 }
15403
15404 if (getLangOpts().HLSL) {
15405 if (Opc == UO_AddrOf)
15406 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15407 if (Opc == UO_Deref)
15408 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15409 }
15410
15411 switch (Opc) {
15412 case UO_PreInc:
15413 case UO_PreDec:
15414 case UO_PostInc:
15415 case UO_PostDec:
15416 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15417 OpLoc,
15418 Opc == UO_PreInc ||
15419 Opc == UO_PostInc,
15420 Opc == UO_PreInc ||
15421 Opc == UO_PreDec);
15422 CanOverflow = isOverflowingIntegerType(Context, resultType);
15423 break;
15424 case UO_AddrOf:
15425 resultType = CheckAddressOfOperand(Input, OpLoc);
15426 CheckAddressOfNoDeref(InputExpr);
15427 RecordModifiableNonNullParam(*this, InputExpr);
15428 break;
15429 case UO_Deref: {
15430 Input = DefaultFunctionArrayLvalueConversion(Input.get());
15431 if (Input.isInvalid()) return ExprError();
15432 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
15433 break;
15434 }
15435 case UO_Plus:
15436 case UO_Minus:
15437 CanOverflow = Opc == UO_Minus &&
15438 isOverflowingIntegerType(Context, Input.get()->getType());
15439 Input = UsualUnaryConversions(Input.get());
15440 if (Input.isInvalid()) return ExprError();
15441 // Unary plus and minus require promoting an operand of half vector to a
15442 // float vector and truncating the result back to a half vector. For now, we
15443 // do this only when HalfArgsAndReturns is set (that is, when the target is
15444 // arm or arm64).
15445 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15446
15447 // If the operand is a half vector, promote it to a float vector.
15448 if (ConvertHalfVec)
15449 Input = convertVector(Input.get(), Context.FloatTy, *this);
15450 resultType = Input.get()->getType();
15451 if (resultType->isDependentType())
15452 break;
15453 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15454 break;
15455 else if (resultType->isVectorType() &&
15456 // The z vector extensions don't allow + or - with bool vectors.
15457 (!Context.getLangOpts().ZVector ||
15458 resultType->castAs<VectorType>()->getVectorKind() !=
15459 VectorType::AltiVecBool))
15460 break;
15461 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15462 Opc == UO_Plus &&
15463 resultType->isPointerType())
15464 break;
15465
15466 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15467 << resultType << Input.get()->getSourceRange());
15468
15469 case UO_Not: // bitwise complement
15470 Input = UsualUnaryConversions(Input.get());
15471 if (Input.isInvalid())
15472 return ExprError();
15473 resultType = Input.get()->getType();
15474 if (resultType->isDependentType())
15475 break;
15476 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15477 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15478 // C99 does not support '~' for complex conjugation.
15479 Diag(OpLoc, diag::ext_integer_complement_complex)
15480 << resultType << Input.get()->getSourceRange();
15481 else if (resultType->hasIntegerRepresentation())
15482 break;
15483 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15484 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15485 // on vector float types.
15486 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15487 if (!T->isIntegerType())
15488 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15489 << resultType << Input.get()->getSourceRange());
15490 } else {
15491 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15492 << resultType << Input.get()->getSourceRange());
15493 }
15494 break;
15495
15496 case UO_LNot: // logical negation
15497 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15498 Input = DefaultFunctionArrayLvalueConversion(Input.get());
15499 if (Input.isInvalid()) return ExprError();
15500 resultType = Input.get()->getType();
15501
15502 // Though we still have to promote half FP to float...
15503 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15504 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15505 resultType = Context.FloatTy;
15506 }
15507
15508 if (resultType->isDependentType())
15509 break;
15510 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15511 // C99 6.5.3.3p1: ok, fallthrough;
15512 if (Context.getLangOpts().CPlusPlus) {
15513 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15514 // operand contextually converted to bool.
15515 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15516 ScalarTypeToBooleanCastKind(resultType));
15517 } else if (Context.getLangOpts().OpenCL &&
15518 Context.getLangOpts().OpenCLVersion < 120) {
15519 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15520 // operate on scalar float types.
15521 if (!resultType->isIntegerType() && !resultType->isPointerType())
15522 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15523 << resultType << Input.get()->getSourceRange());
15524 }
15525 } else if (resultType->isExtVectorType()) {
15526 if (Context.getLangOpts().OpenCL &&
15527 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15528 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15529 // operate on vector float types.
15530 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15531 if (!T->isIntegerType())
15532 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15533 << resultType << Input.get()->getSourceRange());
15534 }
15535 // Vector logical not returns the signed variant of the operand type.
15536 resultType = GetSignedVectorType(resultType);
15537 break;
15538 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15539 const VectorType *VTy = resultType->castAs<VectorType>();
15540 if (VTy->getVectorKind() != VectorType::GenericVector)
15541 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15542 << resultType << Input.get()->getSourceRange());
15543
15544 // Vector logical not returns the signed variant of the operand type.
15545 resultType = GetSignedVectorType(resultType);
15546 break;
15547 } else {
15548 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15549 << resultType << Input.get()->getSourceRange());
15550 }
15551
15552 // LNot always has type int. C99 6.5.3.3p5.
15553 // In C++, it's bool. C++ 5.3.1p8
15554 resultType = Context.getLogicalOperationType();
15555 break;
15556 case UO_Real:
15557 case UO_Imag:
15558 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15559 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15560 // complex l-values to ordinary l-values and all other values to r-values.
15561 if (Input.isInvalid()) return ExprError();
15562 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15563 if (Input.get()->isGLValue() &&
15564 Input.get()->getObjectKind() == OK_Ordinary)
15565 VK = Input.get()->getValueKind();
15566 } else if (!getLangOpts().CPlusPlus) {
15567 // In C, a volatile scalar is read by __imag. In C++, it is not.
15568 Input = DefaultLvalueConversion(Input.get());
15569 }
15570 break;
15571 case UO_Extension:
15572 resultType = Input.get()->getType();
15573 VK = Input.get()->getValueKind();
15574 OK = Input.get()->getObjectKind();
15575 break;
15576 case UO_Coawait:
15577 // It's unnecessary to represent the pass-through operator co_await in the
15578 // AST; just return the input expression instead.
15579 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", 15581, __extension__ __PRETTY_FUNCTION__
))
15580 "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", 15581, __extension__ __PRETTY_FUNCTION__
))
15581 "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", 15581, __extension__ __PRETTY_FUNCTION__
))
;
15582 return Input;
15583 }
15584 if (resultType.isNull() || Input.isInvalid())
15585 return ExprError();
15586
15587 // Check for array bounds violations in the operand of the UnaryOperator,
15588 // except for the '*' and '&' operators that have to be handled specially
15589 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15590 // that are explicitly defined as valid by the standard).
15591 if (Opc != UO_AddrOf && Opc != UO_Deref)
15592 CheckArrayAccess(Input.get());
15593
15594 auto *UO =
15595 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15596 OpLoc, CanOverflow, CurFPFeatureOverrides());
15597
15598 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15599 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15600 !isUnevaluatedContext())
15601 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15602
15603 // Convert the result back to a half vector.
15604 if (ConvertHalfVec)
15605 return convertVector(UO, Context.HalfTy, *this);
15606 return UO;
15607}
15608
15609/// Determine whether the given expression is a qualified member
15610/// access expression, of a form that could be turned into a pointer to member
15611/// with the address-of operator.
15612bool Sema::isQualifiedMemberAccess(Expr *E) {
15613 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15614 if (!DRE->getQualifier())
15615 return false;
15616
15617 ValueDecl *VD = DRE->getDecl();
15618 if (!VD->isCXXClassMember())
15619 return false;
15620
15621 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15622 return true;
15623 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15624 return Method->isInstance();
15625
15626 return false;
15627 }
15628
15629 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15630 if (!ULE->getQualifier())
15631 return false;
15632
15633 for (NamedDecl *D : ULE->decls()) {
15634 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15635 if (Method->isInstance())
15636 return true;
15637 } else {
15638 // Overload set does not contain methods.
15639 break;
15640 }
15641 }
15642
15643 return false;
15644 }
15645
15646 return false;
15647}
15648
15649ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15650 UnaryOperatorKind Opc, Expr *Input) {
15651 // First things first: handle placeholders so that the
15652 // overloaded-operator check considers the right type.
15653 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15654 // Increment and decrement of pseudo-object references.
15655 if (pty->getKind() == BuiltinType::PseudoObject &&
15656 UnaryOperator::isIncrementDecrementOp(Opc))
15657 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15658
15659 // extension is always a builtin operator.
15660 if (Opc == UO_Extension)
15661 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15662
15663 // & gets special logic for several kinds of placeholder.
15664 // The builtin code knows what to do.
15665 if (Opc == UO_AddrOf &&
15666 (pty->getKind() == BuiltinType::Overload ||
15667 pty->getKind() == BuiltinType::UnknownAny ||
15668 pty->getKind() == BuiltinType::BoundMember))
15669 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15670
15671 // Anything else needs to be handled now.
15672 ExprResult Result = CheckPlaceholderExpr(Input);
15673 if (Result.isInvalid()) return ExprError();
15674 Input = Result.get();
15675 }
15676
15677 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15678 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15679 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15680 // Find all of the overloaded operators visible from this point.
15681 UnresolvedSet<16> Functions;
15682 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15683 if (S && OverOp != OO_None)
15684 LookupOverloadedOperatorName(OverOp, S, Functions);
15685
15686 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15687 }
15688
15689 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15690}
15691
15692// Unary Operators. 'Tok' is the token for the operator.
15693ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15694 tok::TokenKind Op, Expr *Input) {
15695 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15696}
15697
15698/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15699ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15700 LabelDecl *TheDecl) {
15701 TheDecl->markUsed(Context);
15702 // Create the AST node. The address of a label always has type 'void*'.
15703 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15704 Context.getPointerType(Context.VoidTy));
15705}
15706
15707void Sema::ActOnStartStmtExpr() {
15708 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15709}
15710
15711void Sema::ActOnStmtExprError() {
15712 // Note that function is also called by TreeTransform when leaving a
15713 // StmtExpr scope without rebuilding anything.
15714
15715 DiscardCleanupsInEvaluationContext();
15716 PopExpressionEvaluationContext();
15717}
15718
15719ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15720 SourceLocation RPLoc) {
15721 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15722}
15723
15724ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15725 SourceLocation RPLoc, unsigned TemplateDepth) {
15726 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", 15726, __extension__ __PRETTY_FUNCTION__
))
;
15727 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15728
15729 if (hasAnyUnrecoverableErrorsInThisFunction())
15730 DiscardCleanupsInEvaluationContext();
15731 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", 15732, __extension__ __PRETTY_FUNCTION__
))
15732 "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", 15732, __extension__ __PRETTY_FUNCTION__
))
;
15733 PopExpressionEvaluationContext();
15734
15735 // FIXME: there are a variety of strange constraints to enforce here, for
15736 // example, it is not possible to goto into a stmt expression apparently.
15737 // More semantic analysis is needed.
15738
15739 // If there are sub-stmts in the compound stmt, take the type of the last one
15740 // as the type of the stmtexpr.
15741 QualType Ty = Context.VoidTy;
15742 bool StmtExprMayBindToTemp = false;
15743 if (!Compound->body_empty()) {
15744 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15745 if (const auto *LastStmt =
15746 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15747 if (const Expr *Value = LastStmt->getExprStmt()) {
15748 StmtExprMayBindToTemp = true;
15749 Ty = Value->getType();
15750 }
15751 }
15752 }
15753
15754 // FIXME: Check that expression type is complete/non-abstract; statement
15755 // expressions are not lvalues.
15756 Expr *ResStmtExpr =
15757 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15758 if (StmtExprMayBindToTemp)
15759 return MaybeBindToTemporary(ResStmtExpr);
15760 return ResStmtExpr;
15761}
15762
15763ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15764 if (ER.isInvalid())
15765 return ExprError();
15766
15767 // Do function/array conversion on the last expression, but not
15768 // lvalue-to-rvalue. However, initialize an unqualified type.
15769 ER = DefaultFunctionArrayConversion(ER.get());
15770 if (ER.isInvalid())
15771 return ExprError();
15772 Expr *E = ER.get();
15773
15774 if (E->isTypeDependent())
15775 return E;
15776
15777 // In ARC, if the final expression ends in a consume, splice
15778 // the consume out and bind it later. In the alternate case
15779 // (when dealing with a retainable type), the result
15780 // initialization will create a produce. In both cases the
15781 // result will be +1, and we'll need to balance that out with
15782 // a bind.
15783 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15784 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15785 return Cast->getSubExpr();
15786
15787 // FIXME: Provide a better location for the initialization.
15788 return PerformCopyInitialization(
15789 InitializedEntity::InitializeStmtExprResult(
15790 E->getBeginLoc(), E->getType().getUnqualifiedType()),
15791 SourceLocation(), E);
15792}
15793
15794ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15795 TypeSourceInfo *TInfo,
15796 ArrayRef<OffsetOfComponent> Components,
15797 SourceLocation RParenLoc) {
15798 QualType ArgTy = TInfo->getType();
15799 bool Dependent = ArgTy->isDependentType();
15800 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15801
15802 // We must have at least one component that refers to the type, and the first
15803 // one is known to be a field designator. Verify that the ArgTy represents
15804 // a struct/union/class.
15805 if (!Dependent && !ArgTy->isRecordType())
15806 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15807 << ArgTy << TypeRange);
15808
15809 // Type must be complete per C99 7.17p3 because a declaring a variable
15810 // with an incomplete type would be ill-formed.
15811 if (!Dependent
15812 && RequireCompleteType(BuiltinLoc, ArgTy,
15813 diag::err_offsetof_incomplete_type, TypeRange))
15814 return ExprError();
15815
15816 bool DidWarnAboutNonPOD = false;
15817 QualType CurrentType = ArgTy;
15818 SmallVector<OffsetOfNode, 4> Comps;
15819 SmallVector<Expr*, 4> Exprs;
15820 for (const OffsetOfComponent &OC : Components) {
15821 if (OC.isBrackets) {
15822 // Offset of an array sub-field. TODO: Should we allow vector elements?
15823 if (!CurrentType->isDependentType()) {
15824 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15825 if(!AT)
15826 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15827 << CurrentType);
15828 CurrentType = AT->getElementType();
15829 } else
15830 CurrentType = Context.DependentTy;
15831
15832 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15833 if (IdxRval.isInvalid())
15834 return ExprError();
15835 Expr *Idx = IdxRval.get();
15836
15837 // The expression must be an integral expression.
15838 // FIXME: An integral constant expression?
15839 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15840 !Idx->getType()->isIntegerType())
15841 return ExprError(
15842 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15843 << Idx->getSourceRange());
15844
15845 // Record this array index.
15846 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15847 Exprs.push_back(Idx);
15848 continue;
15849 }
15850
15851 // Offset of a field.
15852 if (CurrentType->isDependentType()) {
15853 // We have the offset of a field, but we can't look into the dependent
15854 // type. Just record the identifier of the field.
15855 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15856 CurrentType = Context.DependentTy;
15857 continue;
15858 }
15859
15860 // We need to have a complete type to look into.
15861 if (RequireCompleteType(OC.LocStart, CurrentType,
15862 diag::err_offsetof_incomplete_type))
15863 return ExprError();
15864
15865 // Look for the designated field.
15866 const RecordType *RC = CurrentType->getAs<RecordType>();
15867 if (!RC)
15868 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15869 << CurrentType);
15870 RecordDecl *RD = RC->getDecl();
15871
15872 // C++ [lib.support.types]p5:
15873 // The macro offsetof accepts a restricted set of type arguments in this
15874 // International Standard. type shall be a POD structure or a POD union
15875 // (clause 9).
15876 // C++11 [support.types]p4:
15877 // If type is not a standard-layout class (Clause 9), the results are
15878 // undefined.
15879 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15880 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15881 unsigned DiagID =
15882 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15883 : diag::ext_offsetof_non_pod_type;
15884
15885 if (!IsSafe && !DidWarnAboutNonPOD &&
15886 DiagRuntimeBehavior(BuiltinLoc, nullptr,
15887 PDiag(DiagID)
15888 << SourceRange(Components[0].LocStart, OC.LocEnd)
15889 << CurrentType))
15890 DidWarnAboutNonPOD = true;
15891 }
15892
15893 // Look for the field.
15894 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15895 LookupQualifiedName(R, RD);
15896 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15897 IndirectFieldDecl *IndirectMemberDecl = nullptr;
15898 if (!MemberDecl) {
15899 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15900 MemberDecl = IndirectMemberDecl->getAnonField();
15901 }
15902
15903 if (!MemberDecl)
15904 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15905 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15906 OC.LocEnd));
15907
15908 // C99 7.17p3:
15909 // (If the specified member is a bit-field, the behavior is undefined.)
15910 //
15911 // We diagnose this as an error.
15912 if (MemberDecl->isBitField()) {
15913 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15914 << MemberDecl->getDeclName()
15915 << SourceRange(BuiltinLoc, RParenLoc);
15916 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15917 return ExprError();
15918 }
15919
15920 RecordDecl *Parent = MemberDecl->getParent();
15921 if (IndirectMemberDecl)
15922 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15923
15924 // If the member was found in a base class, introduce OffsetOfNodes for
15925 // the base class indirections.
15926 CXXBasePaths Paths;
15927 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15928 Paths)) {
15929 if (Paths.getDetectedVirtual()) {
15930 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15931 << MemberDecl->getDeclName()
15932 << SourceRange(BuiltinLoc, RParenLoc);
15933 return ExprError();
15934 }
15935
15936 CXXBasePath &Path = Paths.front();
15937 for (const CXXBasePathElement &B : Path)
15938 Comps.push_back(OffsetOfNode(B.Base));
15939 }
15940
15941 if (IndirectMemberDecl) {
15942 for (auto *FI : IndirectMemberDecl->chain()) {
15943 assert(isa<FieldDecl>(FI))(static_cast <bool> (isa<FieldDecl>(FI)) ? void (
0) : __assert_fail ("isa<FieldDecl>(FI)", "clang/lib/Sema/SemaExpr.cpp"
, 15943, __extension__ __PRETTY_FUNCTION__))
;
15944 Comps.push_back(OffsetOfNode(OC.LocStart,
15945 cast<FieldDecl>(FI), OC.LocEnd));
15946 }
15947 } else
15948 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15949
15950 CurrentType = MemberDecl->getType().getNonReferenceType();
15951 }
15952
15953 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15954 Comps, Exprs, RParenLoc);
15955}
15956
15957ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15958 SourceLocation BuiltinLoc,
15959 SourceLocation TypeLoc,
15960 ParsedType ParsedArgTy,
15961 ArrayRef<OffsetOfComponent> Components,
15962 SourceLocation RParenLoc) {
15963
15964 TypeSourceInfo *ArgTInfo;
15965 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15966 if (ArgTy.isNull())
15967 return ExprError();
15968
15969 if (!ArgTInfo)
15970 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15971
15972 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15973}
15974
15975
15976ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15977 Expr *CondExpr,
15978 Expr *LHSExpr, Expr *RHSExpr,
15979 SourceLocation RPLoc) {
15980 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", 15980, __extension__ __PRETTY_FUNCTION__
))
;
15981
15982 ExprValueKind VK = VK_PRValue;
15983 ExprObjectKind OK = OK_Ordinary;
15984 QualType resType;
15985 bool CondIsTrue = false;
15986 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15987 resType = Context.DependentTy;
15988 } else {
15989 // The conditional expression is required to be a constant expression.
15990 llvm::APSInt condEval(32);
15991 ExprResult CondICE = VerifyIntegerConstantExpression(
15992 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15993 if (CondICE.isInvalid())
15994 return ExprError();
15995 CondExpr = CondICE.get();
15996 CondIsTrue = condEval.getZExtValue();
15997
15998 // If the condition is > zero, then the AST type is the same as the LHSExpr.
15999 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16000
16001 resType = ActiveExpr->getType();
16002 VK = ActiveExpr->getValueKind();
16003 OK = ActiveExpr->getObjectKind();
16004 }
16005
16006 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16007 resType, VK, OK, RPLoc, CondIsTrue);
16008}
16009
16010//===----------------------------------------------------------------------===//
16011// Clang Extensions.
16012//===----------------------------------------------------------------------===//
16013
16014/// ActOnBlockStart - This callback is invoked when a block literal is started.
16015void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16016 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16017
16018 if (LangOpts.CPlusPlus) {
16019 MangleNumberingContext *MCtx;
16020 Decl *ManglingContextDecl;
16021 std::tie(MCtx, ManglingContextDecl) =
16022 getCurrentMangleNumberContext(Block->getDeclContext());
16023 if (MCtx) {
16024 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16025 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16026 }
16027 }
16028
16029 PushBlockScope(CurScope, Block);
16030 CurContext->addDecl(Block);
16031 if (CurScope)
16032 PushDeclContext(CurScope, Block);
16033 else
16034 CurContext = Block;
16035
16036 getCurBlock()->HasImplicitReturnType = true;
16037
16038 // Enter a new evaluation context to insulate the block from any
16039 // cleanups from the enclosing full-expression.
16040 PushExpressionEvaluationContext(
16041 ExpressionEvaluationContext::PotentiallyEvaluated);
16042}
16043
16044void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16045 Scope *CurScope) {
16046 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", 16047, __extension__ __PRETTY_FUNCTION__
))
16047 "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", 16047, __extension__ __PRETTY_FUNCTION__
))
;
16048 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", 16048, __extension__ __PRETTY_FUNCTION__
))
;
16049 BlockScopeInfo *CurBlock = getCurBlock();
16050
16051 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16052 QualType T = Sig->getType();
16053
16054 // FIXME: We should allow unexpanded parameter packs here, but that would,
16055 // in turn, make the block expression contain unexpanded parameter packs.
16056 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16057 // Drop the parameters.
16058 FunctionProtoType::ExtProtoInfo EPI;
16059 EPI.HasTrailingReturn = false;
16060 EPI.TypeQuals.addConst();
16061 T = Context.getFunctionType(Context.DependentTy, None, EPI);
16062 Sig = Context.getTrivialTypeSourceInfo(T);
16063 }
16064
16065 // GetTypeForDeclarator always produces a function type for a block
16066 // literal signature. Furthermore, it is always a FunctionProtoType
16067 // unless the function was written with a typedef.
16068 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", 16069, __extension__ __PRETTY_FUNCTION__
))
16069 "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", 16069, __extension__ __PRETTY_FUNCTION__
))
;
16070
16071 // Look for an explicit signature in that function type.
16072 FunctionProtoTypeLoc ExplicitSignature;
16073
16074 if ((ExplicitSignature = Sig->getTypeLoc()
16075 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16076
16077 // Check whether that explicit signature was synthesized by
16078 // GetTypeForDeclarator. If so, don't save that as part of the
16079 // written signature.
16080 if (ExplicitSignature.getLocalRangeBegin() ==
16081 ExplicitSignature.getLocalRangeEnd()) {
16082 // This would be much cheaper if we stored TypeLocs instead of
16083 // TypeSourceInfos.
16084 TypeLoc Result = ExplicitSignature.getReturnLoc();
16085 unsigned Size = Result.getFullDataSize();
16086 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16087 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16088
16089 ExplicitSignature = FunctionProtoTypeLoc();
16090 }
16091 }
16092
16093 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16094 CurBlock->FunctionType = T;
16095
16096 const auto *Fn = T->castAs<FunctionType>();
16097 QualType RetTy = Fn->getReturnType();
16098 bool isVariadic =
16099 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16100
16101 CurBlock->TheDecl->setIsVariadic(isVariadic);
16102
16103 // Context.DependentTy is used as a placeholder for a missing block
16104 // return type. TODO: what should we do with declarators like:
16105 // ^ * { ... }
16106 // If the answer is "apply template argument deduction"....
16107 if (RetTy != Context.DependentTy) {
16108 CurBlock->ReturnType = RetTy;
16109 CurBlock->TheDecl->setBlockMissingReturnType(false);
16110 CurBlock->HasImplicitReturnType = false;
16111 }
16112
16113 // Push block parameters from the declarator if we had them.
16114 SmallVector<ParmVarDecl*, 8> Params;
16115 if (ExplicitSignature) {
16116 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16117 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16118 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16119 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16120 // Diagnose this as an extension in C17 and earlier.
16121 if (!getLangOpts().C2x)
16122 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
16123 }
16124 Params.push_back(Param);
16125 }
16126
16127 // Fake up parameter variables if we have a typedef, like
16128 // ^ fntype { ... }
16129 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16130 for (const auto &I : Fn->param_types()) {
16131 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16132 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16133 Params.push_back(Param);
16134 }
16135 }
16136
16137 // Set the parameters on the block decl.
16138 if (!Params.empty()) {
16139 CurBlock->TheDecl->setParams(Params);
16140 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16141 /*CheckParameterNames=*/false);
16142 }
16143
16144 // Finally we can process decl attributes.
16145 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16146
16147 // Put the parameter variables in scope.
16148 for (auto AI : CurBlock->TheDecl->parameters()) {
16149 AI->setOwningFunction(CurBlock->TheDecl);
16150
16151 // If this has an identifier, add it to the scope stack.
16152 if (AI->getIdentifier()) {
16153 CheckShadow(CurBlock->TheScope, AI);
16154
16155 PushOnScopeChains(AI, CurBlock->TheScope);
16156 }
16157 }
16158}
16159
16160/// ActOnBlockError - If there is an error parsing a block, this callback
16161/// is invoked to pop the information about the block from the action impl.
16162void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16163 // Leave the expression-evaluation context.
16164 DiscardCleanupsInEvaluationContext();
16165 PopExpressionEvaluationContext();
16166
16167 // Pop off CurBlock, handle nested blocks.
16168 PopDeclContext();
16169 PopFunctionScopeInfo();
16170}
16171
16172/// ActOnBlockStmtExpr - This is called when the body of a block statement
16173/// literal was successfully completed. ^(int x){...}
16174ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16175 Stmt *Body, Scope *CurScope) {
16176 // If blocks are disabled, emit an error.
16177 if (!LangOpts.Blocks)
16178 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16179
16180 // Leave the expression-evaluation context.
16181 if (hasAnyUnrecoverableErrorsInThisFunction())
16182 DiscardCleanupsInEvaluationContext();
16183 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", 16184, __extension__ __PRETTY_FUNCTION__
))
16184 "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", 16184, __extension__ __PRETTY_FUNCTION__
))
;
16185 PopExpressionEvaluationContext();
16186
16187 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16188 BlockDecl *BD = BSI->TheDecl;
16189
16190 if (BSI->HasImplicitReturnType)
16191 deduceClosureReturnType(*BSI);
16192
16193 QualType RetTy = Context.VoidTy;
16194 if (!BSI->ReturnType.isNull())
16195 RetTy = BSI->ReturnType;
16196
16197 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16198 QualType BlockTy;
16199
16200 // If the user wrote a function type in some form, try to use that.
16201 if (!BSI->FunctionType.isNull()) {
16202 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16203
16204 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16205 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16206
16207 // Turn protoless block types into nullary block types.
16208 if (isa<FunctionNoProtoType>(FTy)) {
16209 FunctionProtoType::ExtProtoInfo EPI;
16210 EPI.ExtInfo = Ext;
16211 BlockTy = Context.getFunctionType(RetTy, None, EPI);
16212
16213 // Otherwise, if we don't need to change anything about the function type,
16214 // preserve its sugar structure.
16215 } else if (FTy->getReturnType() == RetTy &&
16216 (!NoReturn || FTy->getNoReturnAttr())) {
16217 BlockTy = BSI->FunctionType;
16218
16219 // Otherwise, make the minimal modifications to the function type.
16220 } else {
16221 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16222 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16223 EPI.TypeQuals = Qualifiers();
16224 EPI.ExtInfo = Ext;
16225 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16226 }
16227
16228 // If we don't have a function type, just build one from nothing.
16229 } else {
16230 FunctionProtoType::ExtProtoInfo EPI;
16231 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16232 BlockTy = Context.getFunctionType(RetTy, None, EPI);
16233 }
16234
16235 DiagnoseUnusedParameters(BD->parameters());
16236 BlockTy = Context.getBlockPointerType(BlockTy);
16237
16238 // If needed, diagnose invalid gotos and switches in the block.
16239 if (getCurFunction()->NeedsScopeChecking() &&
16240 !PP.isCodeCompletionEnabled())
16241 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16242
16243 BD->setBody(cast<CompoundStmt>(Body));
16244
16245 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16246 DiagnoseUnguardedAvailabilityViolations(BD);
16247
16248 // Try to apply the named return value optimization. We have to check again
16249 // if we can do this, though, because blocks keep return statements around
16250 // to deduce an implicit return type.
16251 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16252 !BD->isDependentContext())
16253 computeNRVO(Body, BSI);
16254
16255 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16256 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16257 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16258 NTCUK_Destruct|NTCUK_Copy);
16259
16260 PopDeclContext();
16261
16262 // Set the captured variables on the block.
16263 SmallVector<BlockDecl::Capture, 4> Captures;
16264 for (Capture &Cap : BSI->Captures) {
16265 if (Cap.isInvalid() || Cap.isThisCapture())
16266 continue;
16267
16268 VarDecl *Var = Cap.getVariable();
16269 Expr *CopyExpr = nullptr;
16270 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16271 if (const RecordType *Record =
16272 Cap.getCaptureType()->getAs<RecordType>()) {
16273 // The capture logic needs the destructor, so make sure we mark it.
16274 // Usually this is unnecessary because most local variables have
16275 // their destructors marked at declaration time, but parameters are
16276 // an exception because it's technically only the call site that
16277 // actually requires the destructor.
16278 if (isa<ParmVarDecl>(Var))
16279 FinalizeVarWithDestructor(Var, Record);
16280
16281 // Enter a separate potentially-evaluated context while building block
16282 // initializers to isolate their cleanups from those of the block
16283 // itself.
16284 // FIXME: Is this appropriate even when the block itself occurs in an
16285 // unevaluated operand?
16286 EnterExpressionEvaluationContext EvalContext(
16287 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16288
16289 SourceLocation Loc = Cap.getLocation();
16290
16291 ExprResult Result = BuildDeclarationNameExpr(
16292 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16293
16294 // According to the blocks spec, the capture of a variable from
16295 // the stack requires a const copy constructor. This is not true
16296 // of the copy/move done to move a __block variable to the heap.
16297 if (!Result.isInvalid() &&
16298 !Result.get()->getType().isConstQualified()) {
16299 Result = ImpCastExprToType(Result.get(),
16300 Result.get()->getType().withConst(),
16301 CK_NoOp, VK_LValue);
16302 }
16303
16304 if (!Result.isInvalid()) {
16305 Result = PerformCopyInitialization(
16306 InitializedEntity::InitializeBlock(Var->getLocation(),
16307 Cap.getCaptureType()),
16308 Loc, Result.get());
16309 }
16310
16311 // Build a full-expression copy expression if initialization
16312 // succeeded and used a non-trivial constructor. Recover from
16313 // errors by pretending that the copy isn't necessary.
16314 if (!Result.isInvalid() &&
16315 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16316 ->isTrivial()) {
16317 Result = MaybeCreateExprWithCleanups(Result);
16318 CopyExpr = Result.get();
16319 }
16320 }
16321 }
16322
16323 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16324 CopyExpr);
16325 Captures.push_back(NewCap);
16326 }
16327 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16328
16329 // Pop the block scope now but keep it alive to the end of this function.
16330 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16331 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16332
16333 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16334
16335 // If the block isn't obviously global, i.e. it captures anything at
16336 // all, then we need to do a few things in the surrounding context:
16337 if (Result->getBlockDecl()->hasCaptures()) {
16338 // First, this expression has a new cleanup object.
16339 ExprCleanupObjects.push_back(Result->getBlockDecl());
16340 Cleanup.setExprNeedsCleanups(true);
16341
16342 // It also gets a branch-protected scope if any of the captured
16343 // variables needs destruction.
16344 for (const auto &CI : Result->getBlockDecl()->captures()) {
16345 const VarDecl *var = CI.getVariable();
16346 if (var->getType().isDestructedType() != QualType::DK_none) {
16347 setFunctionHasBranchProtectedScope();
16348 break;
16349 }
16350 }
16351 }
16352
16353 if (getCurFunction())
16354 getCurFunction()->addBlock(BD);
16355
16356 return Result;
16357}
16358
16359ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16360 SourceLocation RPLoc) {
16361 TypeSourceInfo *TInfo;
16362 GetTypeFromParser(Ty, &TInfo);
16363 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16364}
16365
16366ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16367 Expr *E, TypeSourceInfo *TInfo,
16368 SourceLocation RPLoc) {
16369 Expr *OrigExpr = E;
16370 bool IsMS = false;
16371
16372 // CUDA device code does not support varargs.
16373 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16374 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16375 CUDAFunctionTarget T = IdentifyCUDATarget(F);
16376 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16377 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16378 }
16379 }
16380
16381 // NVPTX does not support va_arg expression.
16382 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16383 Context.getTargetInfo().getTriple().isNVPTX())
16384 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16385
16386 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16387 // as Microsoft ABI on an actual Microsoft platform, where
16388 // __builtin_ms_va_list and __builtin_va_list are the same.)
16389 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16390 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16391 QualType MSVaListType = Context.getBuiltinMSVaListType();
16392 if (Context.hasSameType(MSVaListType, E->getType())) {
16393 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16394 return ExprError();
16395 IsMS = true;
16396 }
16397 }
16398
16399 // Get the va_list type
16400 QualType VaListType = Context.getBuiltinVaListType();
16401 if (!IsMS) {
16402 if (VaListType->isArrayType()) {
16403 // Deal with implicit array decay; for example, on x86-64,
16404 // va_list is an array, but it's supposed to decay to
16405 // a pointer for va_arg.
16406 VaListType = Context.getArrayDecayedType(VaListType);
16407 // Make sure the input expression also decays appropriately.
16408 ExprResult Result = UsualUnaryConversions(E);
16409 if (Result.isInvalid())
16410 return ExprError();
16411 E = Result.get();
16412 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16413 // If va_list is a record type and we are compiling in C++ mode,
16414 // check the argument using reference binding.
16415 InitializedEntity Entity = InitializedEntity::InitializeParameter(
16416 Context, Context.getLValueReferenceType(VaListType), false);
16417 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16418 if (Init.isInvalid())
16419 return ExprError();
16420 E = Init.getAs<Expr>();
16421 } else {
16422 // Otherwise, the va_list argument must be an l-value because
16423 // it is modified by va_arg.
16424 if (!E->isTypeDependent() &&
16425 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16426 return ExprError();
16427 }
16428 }
16429
16430 if (!IsMS && !E->isTypeDependent() &&
16431 !Context.hasSameType(VaListType, E->getType()))
16432 return ExprError(
16433 Diag(E->getBeginLoc(),
16434 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16435 << OrigExpr->getType() << E->getSourceRange());
16436
16437 if (!TInfo->getType()->isDependentType()) {
16438 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16439 diag::err_second_parameter_to_va_arg_incomplete,
16440 TInfo->getTypeLoc()))
16441 return ExprError();
16442
16443 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16444 TInfo->getType(),
16445 diag::err_second_parameter_to_va_arg_abstract,
16446 TInfo->getTypeLoc()))
16447 return ExprError();
16448
16449 if (!TInfo->getType().isPODType(Context)) {
16450 Diag(TInfo->getTypeLoc().getBeginLoc(),
16451 TInfo->getType()->isObjCLifetimeType()
16452 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16453 : diag::warn_second_parameter_to_va_arg_not_pod)
16454 << TInfo->getType()
16455 << TInfo->getTypeLoc().getSourceRange();
16456 }
16457
16458 // Check for va_arg where arguments of the given type will be promoted
16459 // (i.e. this va_arg is guaranteed to have undefined behavior).
16460 QualType PromoteType;
16461 if (TInfo->getType()->isPromotableIntegerType()) {
16462 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16463 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16464 // and C2x 7.16.1.1p2 says, in part:
16465 // If type is not compatible with the type of the actual next argument
16466 // (as promoted according to the default argument promotions), the
16467 // behavior is undefined, except for the following cases:
16468 // - both types are pointers to qualified or unqualified versions of
16469 // compatible types;
16470 // - one type is a signed integer type, the other type is the
16471 // corresponding unsigned integer type, and the value is
16472 // representable in both types;
16473 // - one type is pointer to qualified or unqualified void and the
16474 // other is a pointer to a qualified or unqualified character type.
16475 // Given that type compatibility is the primary requirement (ignoring
16476 // qualifications), you would think we could call typesAreCompatible()
16477 // directly to test this. However, in C++, that checks for *same type*,
16478 // which causes false positives when passing an enumeration type to
16479 // va_arg. Instead, get the underlying type of the enumeration and pass
16480 // that.
16481 QualType UnderlyingType = TInfo->getType();
16482 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16483 UnderlyingType = ET->getDecl()->getIntegerType();
16484 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16485 /*CompareUnqualified*/ true))
16486 PromoteType = QualType();
16487
16488 // If the types are still not compatible, we need to test whether the
16489 // promoted type and the underlying type are the same except for
16490 // signedness. Ask the AST for the correctly corresponding type and see
16491 // if that's compatible.
16492 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16493 PromoteType->isUnsignedIntegerType() !=
16494 UnderlyingType->isUnsignedIntegerType()) {
16495 UnderlyingType =
16496 UnderlyingType->isUnsignedIntegerType()
16497 ? Context.getCorrespondingSignedType(UnderlyingType)
16498 : Context.getCorrespondingUnsignedType(UnderlyingType);
16499 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16500 /*CompareUnqualified*/ true))
16501 PromoteType = QualType();
16502 }
16503 }
16504 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16505 PromoteType = Context.DoubleTy;
16506 if (!PromoteType.isNull())
16507 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16508 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16509 << TInfo->getType()
16510 << PromoteType
16511 << TInfo->getTypeLoc().getSourceRange());
16512 }
16513
16514 QualType T = TInfo->getType().getNonLValueExprType(Context);
16515 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16516}
16517
16518ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16519 // The type of __null will be int or long, depending on the size of
16520 // pointers on the target.
16521 QualType Ty;
16522 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
16523 if (pw == Context.getTargetInfo().getIntWidth())
16524 Ty = Context.IntTy;
16525 else if (pw == Context.getTargetInfo().getLongWidth())
16526 Ty = Context.LongTy;
16527 else if (pw == Context.getTargetInfo().getLongLongWidth())
16528 Ty = Context.LongLongTy;
16529 else {
16530 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", 16530)
;
16531 }
16532
16533 return new (Context) GNUNullExpr(Ty, TokenLoc);
16534}
16535
16536static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
16537 CXXRecordDecl *ImplDecl = nullptr;
16538
16539 // Fetch the std::source_location::__impl decl.
16540 if (NamespaceDecl *Std = S.getStdNamespace()) {
16541 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16542 Loc, Sema::LookupOrdinaryName);
16543 if (S.LookupQualifiedName(ResultSL, Std)) {
16544 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16545 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16546 Loc, Sema::LookupOrdinaryName);
16547 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16548 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16549 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16550 }
16551 }
16552 }
16553 }
16554
16555 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16556 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16557 return nullptr;
16558 }
16559
16560 // Verify that __impl is a trivial struct type, with no base classes, and with
16561 // only the four expected fields.
16562 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16563 ImplDecl->getNumBases() != 0) {
16564 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16565 return nullptr;
16566 }
16567
16568 unsigned Count = 0;
16569 for (FieldDecl *F : ImplDecl->fields()) {
16570 StringRef Name = F->getName();
16571
16572 if (Name == "_M_file_name") {
16573 if (F->getType() !=
16574 S.Context.getPointerType(S.Context.CharTy.withConst()))
16575 break;
16576 Count++;
16577 } else if (Name == "_M_function_name") {
16578 if (F->getType() !=
16579 S.Context.getPointerType(S.Context.CharTy.withConst()))
16580 break;
16581 Count++;
16582 } else if (Name == "_M_line") {
16583 if (!F->getType()->isIntegerType())
16584 break;
16585 Count++;
16586 } else if (Name == "_M_column") {
16587 if (!F->getType()->isIntegerType())
16588 break;
16589 Count++;
16590 } else {
16591 Count = 100; // invalid
16592 break;
16593 }
16594 }
16595 if (Count != 4) {
16596 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16597 return nullptr;
16598 }
16599
16600 return ImplDecl;
16601}
16602
16603ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
16604 SourceLocation BuiltinLoc,
16605 SourceLocation RPLoc) {
16606 QualType ResultTy;
16607 switch (Kind) {
16608 case SourceLocExpr::File:
16609 case SourceLocExpr::Function: {
16610 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
16611 ResultTy =
16612 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
16613 break;
16614 }
16615 case SourceLocExpr::Line:
16616 case SourceLocExpr::Column:
16617 ResultTy = Context.UnsignedIntTy;
16618 break;
16619 case SourceLocExpr::SourceLocStruct:
16620 if (!StdSourceLocationImplDecl) {
16621 StdSourceLocationImplDecl =
16622 LookupStdSourceLocationImpl(*this, BuiltinLoc);
16623 if (!StdSourceLocationImplDecl)
16624 return ExprError();
16625 }
16626 ResultTy = Context.getPointerType(
16627 Context.getRecordType(StdSourceLocationImplDecl).withConst());
16628 break;
16629 }
16630
16631 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16632}
16633
16634ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
16635 QualType ResultTy,
16636 SourceLocation BuiltinLoc,
16637 SourceLocation RPLoc,
16638 DeclContext *ParentContext) {
16639 return new (Context)
16640 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16641}
16642
16643bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
16644 bool Diagnose) {
16645 if (!getLangOpts().ObjC)
16646 return false;
16647
16648 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
16649 if (!PT)
16650 return false;
16651 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
16652
16653 // Ignore any parens, implicit casts (should only be
16654 // array-to-pointer decays), and not-so-opaque values. The last is
16655 // important for making this trigger for property assignments.
16656 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
16657 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
16658 if (OV->getSourceExpr())
16659 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
16660
16661 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
16662 if (!PT->isObjCIdType() &&
16663 !(ID && ID->getIdentifier()->isStr("NSString")))
16664 return false;
16665 if (!SL->isAscii())
16666 return false;
16667
16668 if (Diagnose) {
16669 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
16670 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
16671 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
16672 }
16673 return true;
16674 }
16675
16676 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16677 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16678 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16679 !SrcExpr->isNullPointerConstant(
16680 getASTContext(), Expr::NPC_NeverValueDependent)) {
16681 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16682 return false;
16683 if (Diagnose) {
16684 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16685 << /*number*/1
16686 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16687 Expr *NumLit =
16688 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16689 if (NumLit)
16690 Exp = NumLit;
16691 }
16692 return true;
16693 }
16694
16695 return false;
16696}
16697
16698static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16699 const Expr *SrcExpr) {
16700 if (!DstType->isFunctionPointerType() ||
16701 !SrcExpr->getType()->isFunctionType())
16702 return false;
16703
16704 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16705 if (!DRE)
16706 return false;
16707
16708 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16709 if (!FD)
16710 return false;
16711
16712 return !S.checkAddressOfFunctionIsAvailable(FD,
16713 /*Complain=*/true,
16714 SrcExpr->getBeginLoc());
16715}
16716
16717bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16718 SourceLocation Loc,
16719 QualType DstType, QualType SrcType,
16720 Expr *SrcExpr, AssignmentAction Action,
16721 bool *Complained) {
16722 if (Complained)
16723 *Complained = false;
16724
16725 // Decode the result (notice that AST's are still created for extensions).
16726 bool CheckInferredResultType = false;
16727 bool isInvalid = false;
16728 unsigned DiagKind = 0;
16729 ConversionFixItGenerator ConvHints;
16730 bool MayHaveConvFixit = false;
16731 bool MayHaveFunctionDiff = false;
16732 const ObjCInterfaceDecl *IFace = nullptr;
16733 const ObjCProtocolDecl *PDecl = nullptr;
16734
16735 switch (ConvTy) {
16736 case Compatible:
16737 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16738 return false;
16739
16740 case PointerToInt:
16741 if (getLangOpts().CPlusPlus) {
16742 DiagKind = diag::err_typecheck_convert_pointer_int;
16743 isInvalid = true;
16744 } else {
16745 DiagKind = diag::ext_typecheck_convert_pointer_int;
16746 }
16747 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16748 MayHaveConvFixit = true;
16749 break;
16750 case IntToPointer:
16751 if (getLangOpts().CPlusPlus) {
16752 DiagKind = diag::err_typecheck_convert_int_pointer;
16753 isInvalid = true;
16754 } else {
16755 DiagKind = diag::ext_typecheck_convert_int_pointer;
16756 }
16757 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16758 MayHaveConvFixit = true;
16759 break;
16760 case IncompatibleFunctionPointer:
16761 if (getLangOpts().CPlusPlus) {
16762 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16763 isInvalid = true;
16764 } else {
16765 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16766 }
16767 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16768 MayHaveConvFixit = true;
16769 break;
16770 case IncompatiblePointer:
16771 if (Action == AA_Passing_CFAudited) {
16772 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16773 } else if (getLangOpts().CPlusPlus) {
16774 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16775 isInvalid = true;
16776 } else {
16777 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16778 }
16779 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16780 SrcType->isObjCObjectPointerType();
16781 if (!CheckInferredResultType) {
16782 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16783 } else if (CheckInferredResultType) {
16784 SrcType = SrcType.getUnqualifiedType();
16785 DstType = DstType.getUnqualifiedType();
16786 }
16787 MayHaveConvFixit = true;
16788 break;
16789 case IncompatiblePointerSign:
16790 if (getLangOpts().CPlusPlus) {
16791 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16792 isInvalid = true;
16793 } else {
16794 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16795 }
16796 break;
16797 case FunctionVoidPointer:
16798 if (getLangOpts().CPlusPlus) {
16799 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16800 isInvalid = true;
16801 } else {
16802 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16803 }
16804 break;
16805 case IncompatiblePointerDiscardsQualifiers: {
16806 // Perform array-to-pointer decay if necessary.
16807 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16808
16809 isInvalid = true;
16810
16811 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16812 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16813 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16814 DiagKind = diag::err_typecheck_incompatible_address_space;
16815 break;
16816
16817 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16818 DiagKind = diag::err_typecheck_incompatible_ownership;
16819 break;
16820 }
16821
16822 llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!"
, "clang/lib/Sema/SemaExpr.cpp", 16822)
;
16823 // fallthrough
16824 }
16825 case CompatiblePointerDiscardsQualifiers:
16826 // If the qualifiers lost were because we were applying the
16827 // (deprecated) C++ conversion from a string literal to a char*
16828 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16829 // Ideally, this check would be performed in
16830 // checkPointerTypesForAssignment. However, that would require a
16831 // bit of refactoring (so that the second argument is an
16832 // expression, rather than a type), which should be done as part
16833 // of a larger effort to fix checkPointerTypesForAssignment for
16834 // C++ semantics.
16835 if (getLangOpts().CPlusPlus &&
16836 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16837 return false;
16838 if (getLangOpts().CPlusPlus) {
16839 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16840 isInvalid = true;
16841 } else {
16842 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16843 }
16844
16845 break;
16846 case IncompatibleNestedPointerQualifiers:
16847 if (getLangOpts().CPlusPlus) {
16848 isInvalid = true;
16849 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16850 } else {
16851 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16852 }
16853 break;
16854 case IncompatibleNestedPointerAddressSpaceMismatch:
16855 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16856 isInvalid = true;
16857 break;
16858 case IntToBlockPointer:
16859 DiagKind = diag::err_int_to_block_pointer;
16860 isInvalid = true;
16861 break;
16862 case IncompatibleBlockPointer:
16863 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16864 isInvalid = true;
16865 break;
16866 case IncompatibleObjCQualifiedId: {
16867 if (SrcType->isObjCQualifiedIdType()) {
16868 const ObjCObjectPointerType *srcOPT =
16869 SrcType->castAs<ObjCObjectPointerType>();
16870 for (auto *srcProto : srcOPT->quals()) {
16871 PDecl = srcProto;
16872 break;
16873 }
16874 if (const ObjCInterfaceType *IFaceT =
16875 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16876 IFace = IFaceT->getDecl();
16877 }
16878 else if (DstType->isObjCQualifiedIdType()) {
16879 const ObjCObjectPointerType *dstOPT =
16880 DstType->castAs<ObjCObjectPointerType>();
16881 for (auto *dstProto : dstOPT->quals()) {
16882 PDecl = dstProto;
16883 break;
16884 }
16885 if (const ObjCInterfaceType *IFaceT =
16886 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16887 IFace = IFaceT->getDecl();
16888 }
16889 if (getLangOpts().CPlusPlus) {
16890 DiagKind = diag::err_incompatible_qualified_id;
16891 isInvalid = true;
16892 } else {
16893 DiagKind = diag::warn_incompatible_qualified_id;
16894 }
16895 break;
16896 }
16897 case IncompatibleVectors:
16898 if (getLangOpts().CPlusPlus) {
16899 DiagKind = diag::err_incompatible_vectors;
16900 isInvalid = true;
16901 } else {
16902 DiagKind = diag::warn_incompatible_vectors;
16903 }
16904 break;
16905 case IncompatibleObjCWeakRef:
16906 DiagKind = diag::err_arc_weak_unavailable_assign;
16907 isInvalid = true;
16908 break;
16909 case Incompatible:
16910 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16911 if (Complained)
16912 *Complained = true;
16913 return true;
16914 }
16915
16916 DiagKind = diag::err_typecheck_convert_incompatible;
16917 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16918 MayHaveConvFixit = true;
16919 isInvalid = true;
16920 MayHaveFunctionDiff = true;
16921 break;
16922 }
16923
16924 QualType FirstType, SecondType;
16925 switch (Action) {
16926 case AA_Assigning:
16927 case AA_Initializing:
16928 // The destination type comes first.
16929 FirstType = DstType;
16930 SecondType = SrcType;
16931 break;
16932
16933 case AA_Returning:
16934 case AA_Passing:
16935 case AA_Passing_CFAudited:
16936 case AA_Converting:
16937 case AA_Sending:
16938 case AA_Casting:
16939 // The source type comes first.
16940 FirstType = SrcType;
16941 SecondType = DstType;
16942 break;
16943 }
16944
16945 PartialDiagnostic FDiag = PDiag(DiagKind);
16946 if (Action == AA_Passing_CFAudited)
16947 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16948 else
16949 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16950
16951 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16952 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16953 auto isPlainChar = [](const clang::Type *Type) {
16954 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16955 Type->isSpecificBuiltinType(BuiltinType::Char_U);
16956 };
16957 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16958 isPlainChar(SecondType->getPointeeOrArrayElementType()));
16959 }
16960
16961 // If we can fix the conversion, suggest the FixIts.
16962 if (!ConvHints.isNull()) {
16963 for (FixItHint &H : ConvHints.Hints)
16964 FDiag << H;
16965 }
16966
16967 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16968
16969 if (MayHaveFunctionDiff)
16970 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16971
16972 Diag(Loc, FDiag);
16973 if ((DiagKind == diag::warn_incompatible_qualified_id ||
16974 DiagKind == diag::err_incompatible_qualified_id) &&
16975 PDecl && IFace && !IFace->hasDefinition())
16976 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16977 << IFace << PDecl;
16978
16979 if (SecondType == Context.OverloadTy)
16980 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16981 FirstType, /*TakingAddress=*/true);
16982
16983 if (CheckInferredResultType)
16984 EmitRelatedResultTypeNote(SrcExpr);
16985
16986 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16987 EmitRelatedResultTypeNoteForReturn(DstType);
16988
16989 if (Complained)
16990 *Complained = true;
16991 return isInvalid;
16992}
16993
16994ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16995 llvm::APSInt *Result,
16996 AllowFoldKind CanFold) {
16997 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16998 public:
16999 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17000 QualType T) override {
17001 return S.Diag(Loc, diag::err_ice_not_integral)
17002 << T << S.LangOpts.CPlusPlus;
17003 }
17004 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17005 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17006 }
17007 } Diagnoser;
17008
17009 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17010}
17011
17012ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17013 llvm::APSInt *Result,
17014 unsigned DiagID,
17015 AllowFoldKind CanFold) {
17016 class IDDiagnoser : public VerifyICEDiagnoser {
17017 unsigned DiagID;
17018
17019 public:
17020 IDDiagnoser(unsigned DiagID)
17021 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17022
17023 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17024 return S.Diag(Loc, DiagID);
17025 }
17026 } Diagnoser(DiagID);
17027
17028 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17029}
17030
17031Sema::SemaDiagnosticBuilder
17032Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17033 QualType T) {
17034 return diagnoseNotICE(S, Loc);
17035}
17036
17037Sema::SemaDiagnosticBuilder
17038Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17039 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17040}
17041
17042ExprResult
17043Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17044 VerifyICEDiagnoser &Diagnoser,
17045 AllowFoldKind CanFold) {
17046 SourceLocation DiagLoc = E->getBeginLoc();
17047
17048 if (getLangOpts().CPlusPlus11) {
17049 // C++11 [expr.const]p5:
17050 // If an expression of literal class type is used in a context where an
17051 // integral constant expression is required, then that class type shall
17052 // have a single non-explicit conversion function to an integral or
17053 // unscoped enumeration type
17054 ExprResult Converted;
17055 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17056 VerifyICEDiagnoser &BaseDiagnoser;
17057 public:
17058 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17059 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17060 BaseDiagnoser.Suppress, true),
17061 BaseDiagnoser(BaseDiagnoser) {}
17062
17063 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17064 QualType T) override {
17065 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17066 }
17067
17068 SemaDiagnosticBuilder diagnoseIncomplete(
17069 Sema &S, SourceLocation Loc, QualType T) override {
17070 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17071 }
17072
17073 SemaDiagnosticBuilder diagnoseExplicitConv(
17074 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17075 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17076 }
17077
17078 SemaDiagnosticBuilder noteExplicitConv(
17079 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17080 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17081 << ConvTy->isEnumeralType() << ConvTy;
17082 }
17083
17084 SemaDiagnosticBuilder diagnoseAmbiguous(
17085 Sema &S, SourceLocation Loc, QualType T) override {
17086 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17087 }
17088
17089 SemaDiagnosticBuilder noteAmbiguous(
17090 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17091 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17092 << ConvTy->isEnumeralType() << ConvTy;
17093 }
17094
17095 SemaDiagnosticBuilder diagnoseConversion(
17096 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17097 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "clang/lib/Sema/SemaExpr.cpp", 17097)
;
17098 }
17099 } ConvertDiagnoser(Diagnoser);
17100
17101 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17102 ConvertDiagnoser);
17103 if (Converted.isInvalid())
17104 return Converted;
17105 E = Converted.get();
17106 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17107 return ExprError();
17108 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17109 // An ICE must be of integral or unscoped enumeration type.
17110 if (!Diagnoser.Suppress)
17111 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17112 << E->getSourceRange();
17113 return ExprError();
17114 }
17115
17116 ExprResult RValueExpr = DefaultLvalueConversion(E);
17117 if (RValueExpr.isInvalid())
17118 return ExprError();
17119
17120 E = RValueExpr.get();
17121
17122 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17123 // in the non-ICE case.
17124 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17125 if (Result)
17126 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
17127 if (!isa<ConstantExpr>(E))
17128 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17129 : ConstantExpr::Create(Context, E);
17130 return E;
17131 }
17132
17133 Expr::EvalResult EvalResult;
17134 SmallVector<PartialDiagnosticAt, 8> Notes;
17135 EvalResult.Diag = &Notes;
17136
17137 // Try to evaluate the expression, and produce diagnostics explaining why it's
17138 // not a constant expression as a side-effect.
17139 bool Folded =
17140 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17141 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17142
17143 if (!isa<ConstantExpr>(E))
17144 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17145
17146 // In C++11, we can rely on diagnostics being produced for any expression
17147 // which is not a constant expression. If no diagnostics were produced, then
17148 // this is a constant expression.
17149 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17150 if (Result)
17151 *Result = EvalResult.Val.getInt();
17152 return E;
17153 }
17154
17155 // If our only note is the usual "invalid subexpression" note, just point
17156 // the caret at its location rather than producing an essentially
17157 // redundant note.
17158 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17159 diag::note_invalid_subexpr_in_const_expr) {
17160 DiagLoc = Notes[0].first;
17161 Notes.clear();
17162 }
17163
17164 if (!Folded || !CanFold) {
17165 if (!Diagnoser.Suppress) {
17166 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17167 for (const PartialDiagnosticAt &Note : Notes)
17168 Diag(Note.first, Note.second);
17169 }
17170
17171 return ExprError();
17172 }
17173
17174 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17175 for (const PartialDiagnosticAt &Note : Notes)
17176 Diag(Note.first, Note.second);
17177
17178 if (Result)
17179 *Result = EvalResult.Val.getInt();
17180 return E;
17181}
17182
17183namespace {
17184 // Handle the case where we conclude a expression which we speculatively
17185 // considered to be unevaluated is actually evaluated.
17186 class TransformToPE : public TreeTransform<TransformToPE> {
17187 typedef TreeTransform<TransformToPE> BaseTransform;
17188
17189 public:
17190 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17191
17192 // Make sure we redo semantic analysis
17193 bool AlwaysRebuild() { return true; }
17194 bool ReplacingOriginal() { return true; }
17195
17196 // We need to special-case DeclRefExprs referring to FieldDecls which
17197 // are not part of a member pointer formation; normal TreeTransforming
17198 // doesn't catch this case because of the way we represent them in the AST.
17199 // FIXME: This is a bit ugly; is it really the best way to handle this
17200 // case?
17201 //
17202 // Error on DeclRefExprs referring to FieldDecls.
17203 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17204 if (isa<FieldDecl>(E->getDecl()) &&
17205 !SemaRef.isUnevaluatedContext())
17206 return SemaRef.Diag(E->getLocation(),
17207 diag::err_invalid_non_static_member_use)
17208 << E->getDecl() << E->getSourceRange();
17209
17210 return BaseTransform::TransformDeclRefExpr(E);
17211 }
17212
17213 // Exception: filter out member pointer formation
17214 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17215 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17216 return E;
17217
17218 return BaseTransform::TransformUnaryOperator(E);
17219 }
17220
17221 // The body of a lambda-expression is in a separate expression evaluation
17222 // context so never needs to be transformed.
17223 // FIXME: Ideally we wouldn't transform the closure type either, and would
17224 // just recreate the capture expressions and lambda expression.
17225 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17226 return SkipLambdaBody(E, Body);
17227 }
17228 };
17229}
17230
17231ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17232 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", 17233, __extension__ __PRETTY_FUNCTION__
))
17233 "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", 17233, __extension__ __PRETTY_FUNCTION__
))
;
17234 ExprEvalContexts.back().Context =
17235 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17236 if (isUnevaluatedContext())
17237 return E;
17238 return TransformToPE(*this).TransformExpr(E);
17239}
17240
17241TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17242 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", 17243, __extension__ __PRETTY_FUNCTION__
))
17243 "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", 17243, __extension__ __PRETTY_FUNCTION__
))
;
17244 ExprEvalContexts.back().Context =
17245 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17246 if (isUnevaluatedContext())
17247 return TInfo;
17248 return TransformToPE(*this).TransformType(TInfo);
17249}
17250
17251void
17252Sema::PushExpressionEvaluationContext(
17253 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17254 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17255 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17256 LambdaContextDecl, ExprContext);
17257
17258 // Discarded statements and immediate contexts nested in other
17259 // discarded statements or immediate context are themselves
17260 // a discarded statement or an immediate context, respectively.
17261 ExprEvalContexts.back().InDiscardedStatement =
17262 ExprEvalContexts[ExprEvalContexts.size() - 2]
17263 .isDiscardedStatementContext();
17264 ExprEvalContexts.back().InImmediateFunctionContext =
17265 ExprEvalContexts[ExprEvalContexts.size() - 2]
17266 .isImmediateFunctionContext();
17267
17268 Cleanup.reset();
17269 if (!MaybeODRUseExprs.empty())
17270 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17271}
17272
17273void
17274Sema::PushExpressionEvaluationContext(
17275 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17276 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17277 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17278 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17279}
17280
17281namespace {
17282
17283const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17284 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17285 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17286 if (E->getOpcode() == UO_Deref)
17287 return CheckPossibleDeref(S, E->getSubExpr());
17288 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17289 return CheckPossibleDeref(S, E->getBase());
17290 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17291 return CheckPossibleDeref(S, E->getBase());
17292 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17293 QualType Inner;
17294 QualType Ty = E->getType();
17295 if (const auto *Ptr = Ty->getAs<PointerType>())
17296 Inner = Ptr->getPointeeType();
17297 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17298 Inner = Arr->getElementType();
17299 else
17300 return nullptr;
17301
17302 if (Inner->hasAttr(attr::NoDeref))
17303 return E;
17304 }
17305 return nullptr;
17306}
17307
17308} // namespace
17309
17310void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17311 for (const Expr *E : Rec.PossibleDerefs) {
17312 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17313 if (DeclRef) {
17314 const ValueDecl *Decl = DeclRef->getDecl();
17315 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17316 << Decl->getName() << E->getSourceRange();
17317 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17318 } else {
17319 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17320 << E->getSourceRange();
17321 }
17322 }
17323 Rec.PossibleDerefs.clear();
17324}
17325
17326/// Check whether E, which is either a discarded-value expression or an
17327/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17328/// and if so, remove it from the list of volatile-qualified assignments that
17329/// we are going to warn are deprecated.
17330void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17331 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17332 return;
17333
17334 // Note: ignoring parens here is not justified by the standard rules, but
17335 // ignoring parentheses seems like a more reasonable approach, and this only
17336 // drives a deprecation warning so doesn't affect conformance.
17337 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17338 if (BO->getOpcode() == BO_Assign) {
17339 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17340 llvm::erase_value(LHSs, BO->getLHS());
17341 }
17342 }
17343}
17344
17345ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17346 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17347 !Decl->isConsteval() || isConstantEvaluated() ||
17348 RebuildingImmediateInvocation || isImmediateFunctionContext())
17349 return E;
17350
17351 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17352 /// It's OK if this fails; we'll also remove this in
17353 /// HandleImmediateInvocations, but catching it here allows us to avoid
17354 /// walking the AST looking for it in simple cases.
17355 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17356 if (auto *DeclRef =
17357 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17358 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17359
17360 E = MaybeCreateExprWithCleanups(E);
17361
17362 ConstantExpr *Res = ConstantExpr::Create(
17363 getASTContext(), E.get(),
17364 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17365 getASTContext()),
17366 /*IsImmediateInvocation*/ true);
17367 /// Value-dependent constant expressions should not be immediately
17368 /// evaluated until they are instantiated.
17369 if (!Res->isValueDependent())
17370 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17371 return Res;
17372}
17373
17374static void EvaluateAndDiagnoseImmediateInvocation(
17375 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17376 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17377 Expr::EvalResult Eval;
17378 Eval.Diag = &Notes;
17379 ConstantExpr *CE = Candidate.getPointer();
17380 bool Result = CE->EvaluateAsConstantExpr(
17381 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17382 if (!Result || !Notes.empty()) {
17383 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17384 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17385 InnerExpr = FunctionalCast->getSubExpr();
17386 FunctionDecl *FD = nullptr;
17387 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17388 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17389 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17390 FD = Call->getConstructor();
17391 else
17392 llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "clang/lib/Sema/SemaExpr.cpp"
, 17392)
;
17393 assert(FD->isConsteval())(static_cast <bool> (FD->isConsteval()) ? void (0) :
__assert_fail ("FD->isConsteval()", "clang/lib/Sema/SemaExpr.cpp"
, 17393, __extension__ __PRETTY_FUNCTION__))
;
17394 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17395 for (auto &Note : Notes)
17396 SemaRef.Diag(Note.first, Note.second);
17397 return;
17398 }
17399 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17400}
17401
17402static void RemoveNestedImmediateInvocation(
17403 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17404 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17405 struct ComplexRemove : TreeTransform<ComplexRemove> {
17406 using Base = TreeTransform<ComplexRemove>;
17407 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17408 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17409 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
17410 CurrentII;
17411 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17412 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
17413 SmallVector<Sema::ImmediateInvocationCandidate,
17414 4>::reverse_iterator Current)
17415 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17416 void RemoveImmediateInvocation(ConstantExpr* E) {
17417 auto It = std::find_if(CurrentII, IISet.rend(),
17418 [E](Sema::ImmediateInvocationCandidate Elem) {
17419 return Elem.getPointer() == E;
17420 });
17421 assert(It != IISet.rend() &&(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "clang/lib/Sema/SemaExpr.cpp", 17423, __extension__ __PRETTY_FUNCTION__
))
17422 "ConstantExpr marked IsImmediateInvocation should "(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "clang/lib/Sema/SemaExpr.cpp", 17423, __extension__ __PRETTY_FUNCTION__
))
17423 "be present")(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "clang/lib/Sema/SemaExpr.cpp", 17423, __extension__ __PRETTY_FUNCTION__
))
;
17424 It->setInt(1); // Mark as deleted
17425 }
17426 ExprResult TransformConstantExpr(ConstantExpr *E) {
17427 if (!E->isImmediateInvocation())
17428 return Base::TransformConstantExpr(E);
17429 RemoveImmediateInvocation(E);
17430 return Base::TransformExpr(E->getSubExpr());
17431 }
17432 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17433 /// we need to remove its DeclRefExpr from the DRSet.
17434 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17435 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
1
The object is a 'DeclRefExpr'
17436 return Base::TransformCXXOperatorCallExpr(E);
2
Calling 'TreeTransform::TransformCXXOperatorCallExpr'
17437 }
17438 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
17439 /// here.
17440 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17441 if (!Init)
17442 return Init;
17443 /// ConstantExpr are the first layer of implicit node to be removed so if
17444 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17445 if (auto *CE = dyn_cast<ConstantExpr>(Init))
17446 if (CE->isImmediateInvocation())
17447 RemoveImmediateInvocation(CE);
17448 return Base::TransformInitializer(Init, NotCopyInit);
17449 }
17450 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17451 DRSet.erase(E);
17452 return E;
17453 }
17454 bool AlwaysRebuild() { return false; }
17455 bool ReplacingOriginal() { return true; }
17456 bool AllowSkippingCXXConstructExpr() {
17457 bool Res = AllowSkippingFirstCXXConstructExpr;
17458 AllowSkippingFirstCXXConstructExpr = true;
17459 return Res;
17460 }
17461 bool AllowSkippingFirstCXXConstructExpr = true;
17462 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17463 Rec.ImmediateInvocationCandidates, It);
17464
17465 /// CXXConstructExpr with a single argument are getting skipped by
17466 /// TreeTransform in some situtation because they could be implicit. This
17467 /// can only occur for the top-level CXXConstructExpr because it is used
17468 /// nowhere in the expression being transformed therefore will not be rebuilt.
17469 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17470 /// skipping the first CXXConstructExpr.
17471 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17472 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17473
17474 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17475 assert(Res.isUsable())(static_cast <bool> (Res.isUsable()) ? void (0) : __assert_fail
("Res.isUsable()", "clang/lib/Sema/SemaExpr.cpp", 17475, __extension__
__PRETTY_FUNCTION__))
;
17476 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17477 It->getPointer()->setSubExpr(Res.get());
17478}
17479
17480static void
17481HandleImmediateInvocations(Sema &SemaRef,
17482 Sema::ExpressionEvaluationContextRecord &Rec) {
17483 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17484 Rec.ReferenceToConsteval.size() == 0) ||
17485 SemaRef.RebuildingImmediateInvocation)
17486 return;
17487
17488 /// When we have more then 1 ImmediateInvocationCandidates we need to check
17489 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17490 /// need to remove ReferenceToConsteval in the immediate invocation.
17491 if (Rec.ImmediateInvocationCandidates.size() > 1) {
17492
17493 /// Prevent sema calls during the tree transform from adding pointers that
17494 /// are already in the sets.
17495 llvm::SaveAndRestore<bool> DisableIITracking(
17496 SemaRef.RebuildingImmediateInvocation, true);
17497
17498 /// Prevent diagnostic during tree transfrom as they are duplicates
17499 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17500
17501 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17502 It != Rec.ImmediateInvocationCandidates.rend(); It++)
17503 if (!It->getInt())
17504 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17505 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17506 Rec.ReferenceToConsteval.size()) {
17507 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17508 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17509 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17510 bool VisitDeclRefExpr(DeclRefExpr *E) {
17511 DRSet.erase(E);
17512 return DRSet.size();
17513 }
17514 } Visitor(Rec.ReferenceToConsteval);
17515 Visitor.TraverseStmt(
17516 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17517 }
17518 for (auto CE : Rec.ImmediateInvocationCandidates)
17519 if (!CE.getInt())
17520 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
17521 for (auto DR : Rec.ReferenceToConsteval) {
17522 auto *FD = cast<FunctionDecl>(DR->getDecl());
17523 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17524 << FD;
17525 SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
17526 }
17527}
17528
17529void Sema::PopExpressionEvaluationContext() {
17530 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
17531 unsigned NumTypos = Rec.NumTypos;
17532
17533 if (!Rec.Lambdas.empty()) {
17534 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
17535 if (!getLangOpts().CPlusPlus20 &&
17536 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17537 Rec.isUnevaluated() ||
17538 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17539 unsigned D;
17540 if (Rec.isUnevaluated()) {
17541 // C++11 [expr.prim.lambda]p2:
17542 // A lambda-expression shall not appear in an unevaluated operand
17543 // (Clause 5).
17544 D = diag::err_lambda_unevaluated_operand;
17545 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17546 // C++1y [expr.const]p2:
17547 // A conditional-expression e is a core constant expression unless the
17548 // evaluation of e, following the rules of the abstract machine, would
17549 // evaluate [...] a lambda-expression.
17550 D = diag::err_lambda_in_constant_expression;
17551 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17552 // C++17 [expr.prim.lamda]p2:
17553 // A lambda-expression shall not appear [...] in a template-argument.
17554 D = diag::err_lambda_in_invalid_context;
17555 } else
17556 llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message."
, "clang/lib/Sema/SemaExpr.cpp", 17556)
;
17557
17558 for (const auto *L : Rec.Lambdas)
17559 Diag(L->getBeginLoc(), D);
17560 }
17561 }
17562
17563 WarnOnPendingNoDerefs(Rec);
17564 HandleImmediateInvocations(*this, Rec);
17565
17566 // Warn on any volatile-qualified simple-assignments that are not discarded-
17567 // value expressions nor unevaluated operands (those cases get removed from
17568 // this list by CheckUnusedVolatileAssignment).
17569 for (auto *BO : Rec.VolatileAssignmentLHSs)
17570 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17571 << BO->getType();
17572
17573 // When are coming out of an unevaluated context, clear out any
17574 // temporaries that we may have created as part of the evaluation of
17575 // the expression in that context: they aren't relevant because they
17576 // will never be constructed.
17577 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17578 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17579 ExprCleanupObjects.end());
17580 Cleanup = Rec.ParentCleanup;
17581 CleanupVarDeclMarking();
17582 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17583 // Otherwise, merge the contexts together.
17584 } else {
17585 Cleanup.mergeFrom(Rec.ParentCleanup);
17586 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17587 Rec.SavedMaybeODRUseExprs.end());
17588 }
17589
17590 // Pop the current expression evaluation context off the stack.
17591 ExprEvalContexts.pop_back();
17592
17593 // The global expression evaluation context record is never popped.
17594 ExprEvalContexts.back().NumTypos += NumTypos;
17595}
17596
17597void Sema::DiscardCleanupsInEvaluationContext() {
17598 ExprCleanupObjects.erase(
17599 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17600 ExprCleanupObjects.end());
17601 Cleanup.reset();
17602 MaybeODRUseExprs.clear();
17603}
17604
17605ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
17606 ExprResult Result = CheckPlaceholderExpr(E);
17607 if (Result.isInvalid())
17608 return ExprError();
17609 E = Result.get();
17610 if (!E->getType()->isVariablyModifiedType())
17611 return E;
17612 return TransformToPotentiallyEvaluated(E);
17613}
17614
17615/// Are we in a context that is potentially constant evaluated per C++20
17616/// [expr.const]p12?
17617static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
17618 /// C++2a [expr.const]p12:
17619 // An expression or conversion is potentially constant evaluated if it is
17620 switch (SemaRef.ExprEvalContexts.back().Context) {
17621 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17622 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17623
17624 // -- a manifestly constant-evaluated expression,
17625 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17626 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17627 case Sema::ExpressionEvaluationContext::DiscardedStatement:
17628 // -- a potentially-evaluated expression,
17629 case Sema::ExpressionEvaluationContext::UnevaluatedList:
17630 // -- an immediate subexpression of a braced-init-list,
17631
17632 // -- [FIXME] an expression of the form & cast-expression that occurs
17633 // within a templated entity
17634 // -- a subexpression of one of the above that is not a subexpression of
17635 // a nested unevaluated operand.
17636 return true;
17637
17638 case Sema::ExpressionEvaluationContext::Unevaluated:
17639 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17640 // Expressions in this context are never evaluated.
17641 return false;
17642 }
17643 llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "clang/lib/Sema/SemaExpr.cpp"
, 17643)
;
17644}
17645
17646/// Return true if this function has a calling convention that requires mangling
17647/// in the size of the parameter pack.
17648static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17649 // These manglings don't do anything on non-Windows or non-x86 platforms, so
17650 // we don't need parameter type sizes.
17651 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17652 if (!TT.isOSWindows() || !TT.isX86())
17653 return false;
17654
17655 // If this is C++ and this isn't an extern "C" function, parameters do not
17656 // need to be complete. In this case, C++ mangling will apply, which doesn't
17657 // use the size of the parameters.
17658 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17659 return false;
17660
17661 // Stdcall, fastcall, and vectorcall need this special treatment.
17662 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17663 switch (CC) {
17664 case CC_X86StdCall:
17665 case CC_X86FastCall:
17666 case CC_X86VectorCall:
17667 return true;
17668 default:
17669 break;
17670 }
17671 return false;
17672}
17673
17674/// Require that all of the parameter types of function be complete. Normally,
17675/// parameter types are only required to be complete when a function is called
17676/// or defined, but to mangle functions with certain calling conventions, the
17677/// mangler needs to know the size of the parameter list. In this situation,
17678/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17679/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17680/// result in a linker error. Clang doesn't implement this behavior, and instead
17681/// attempts to error at compile time.
17682static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17683 SourceLocation Loc) {
17684 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17685 FunctionDecl *FD;
17686 ParmVarDecl *Param;
17687
17688 public:
17689 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17690 : FD(FD), Param(Param) {}
17691
17692 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17693 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17694 StringRef CCName;
17695 switch (CC) {
17696 case CC_X86StdCall:
17697 CCName = "stdcall";
17698 break;
17699 case CC_X86FastCall:
17700 CCName = "fastcall";
17701 break;
17702 case CC_X86VectorCall:
17703 CCName = "vectorcall";
17704 break;
17705 default:
17706 llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling"
, "clang/lib/Sema/SemaExpr.cpp", 17706)
;
17707 }
17708
17709 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17710 << Param->getDeclName() << FD->getDeclName() << CCName;
17711 }
17712 };
17713
17714 for (ParmVarDecl *Param : FD->parameters()) {
17715 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17716 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17717 }
17718}
17719
17720namespace {
17721enum class OdrUseContext {
17722 /// Declarations in this context are not odr-used.
17723 None,
17724 /// Declarations in this context are formally odr-used, but this is a
17725 /// dependent context.
17726 Dependent,
17727 /// Declarations in this context are odr-used but not actually used (yet).
17728 FormallyOdrUsed,
17729 /// Declarations in this context are used.
17730 Used
17731};
17732}
17733
17734/// Are we within a context in which references to resolved functions or to
17735/// variables result in odr-use?
17736static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17737 OdrUseContext Result;
17738
17739 switch (SemaRef.ExprEvalContexts.back().Context) {
17740 case Sema::ExpressionEvaluationContext::Unevaluated:
17741 case Sema::ExpressionEvaluationContext::UnevaluatedList:
17742 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17743 return OdrUseContext::None;
17744
17745 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17746 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17747 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17748 Result = OdrUseContext::Used;
17749 break;
17750
17751 case Sema::ExpressionEvaluationContext::DiscardedStatement:
17752 Result = OdrUseContext::FormallyOdrUsed;
17753 break;
17754
17755 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17756 // A default argument formally results in odr-use, but doesn't actually
17757 // result in a use in any real sense until it itself is used.
17758 Result = OdrUseContext::FormallyOdrUsed;
17759 break;
17760 }
17761
17762 if (SemaRef.CurContext->isDependentContext())
17763 return OdrUseContext::Dependent;
17764
17765 return Result;
17766}
17767
17768static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17769 if (!Func->isConstexpr())
17770 return false;
17771
17772 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17773 return true;
17774 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17775 return CCD && CCD->getInheritedConstructor();
17776}
17777
17778/// Mark a function referenced, and check whether it is odr-used
17779/// (C++ [basic.def.odr]p2, C99 6.9p3)
17780void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17781 bool MightBeOdrUse) {
17782 assert(Func && "No function?")(static_cast <bool> (Func && "No function?") ? void
(0) : __assert_fail ("Func && \"No function?\"", "clang/lib/Sema/SemaExpr.cpp"
, 17782, __extension__ __PRETTY_FUNCTION__))
;
17783
17784 Func->setReferenced();
17785
17786 // Recursive functions aren't really used until they're used from some other
17787 // context.
17788 bool IsRecursiveCall = CurContext == Func;
17789
17790 // C++11 [basic.def.odr]p3:
17791 // A function whose name appears as a potentially-evaluated expression is
17792 // odr-used if it is the unique lookup result or the selected member of a
17793 // set of overloaded functions [...].
17794 //
17795 // We (incorrectly) mark overload resolution as an unevaluated context, so we
17796 // can just check that here.
17797 OdrUseContext OdrUse =
17798 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17799 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17800 OdrUse = OdrUseContext::FormallyOdrUsed;
17801
17802 // Trivial default constructors and destructors are never actually used.
17803 // FIXME: What about other special members?
17804 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17805 OdrUse == OdrUseContext::Used) {
17806 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17807 if (Constructor->isDefaultConstructor())
17808 OdrUse = OdrUseContext::FormallyOdrUsed;
17809 if (isa<CXXDestructorDecl>(Func))
17810 OdrUse = OdrUseContext::FormallyOdrUsed;
17811 }
17812
17813 // C++20 [expr.const]p12:
17814 // A function [...] is needed for constant evaluation if it is [...] a
17815 // constexpr function that is named by an expression that is potentially
17816 // constant evaluated
17817 bool NeededForConstantEvaluation =
17818 isPotentiallyConstantEvaluatedContext(*this) &&
17819 isImplicitlyDefinableConstexprFunction(Func);
17820
17821 // Determine whether we require a function definition to exist, per
17822 // C++11 [temp.inst]p3:
17823 // Unless a function template specialization has been explicitly
17824 // instantiated or explicitly specialized, the function template
17825 // specialization is implicitly instantiated when the specialization is
17826 // referenced in a context that requires a function definition to exist.
17827 // C++20 [temp.inst]p7:
17828 // The existence of a definition of a [...] function is considered to
17829 // affect the semantics of the program if the [...] function is needed for
17830 // constant evaluation by an expression
17831 // C++20 [basic.def.odr]p10:
17832 // Every program shall contain exactly one definition of every non-inline
17833 // function or variable that is odr-used in that program outside of a
17834 // discarded statement
17835 // C++20 [special]p1:
17836 // The implementation will implicitly define [defaulted special members]
17837 // if they are odr-used or needed for constant evaluation.
17838 //
17839 // Note that we skip the implicit instantiation of templates that are only
17840 // used in unused default arguments or by recursive calls to themselves.
17841 // This is formally non-conforming, but seems reasonable in practice.
17842 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17843 NeededForConstantEvaluation);
17844
17845 // C++14 [temp.expl.spec]p6:
17846 // If a template [...] is explicitly specialized then that specialization
17847 // shall be declared before the first use of that specialization that would
17848 // cause an implicit instantiation to take place, in every translation unit
17849 // in which such a use occurs
17850 if (NeedDefinition &&
17851 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17852 Func->getMemberSpecializationInfo()))
17853 checkSpecializationVisibility(Loc, Func);
17854
17855 if (getLangOpts().CUDA)
17856 CheckCUDACall(Loc, Func);
17857
17858 if (getLangOpts().SYCLIsDevice)
17859 checkSYCLDeviceFunction(Loc, Func);
17860
17861 // If we need a definition, try to create one.
17862 if (NeedDefinition && !Func->getBody()) {
17863 runWithSufficientStackSpace(Loc, [&] {
17864 if (CXXConstructorDecl *Constructor =
17865 dyn_cast<CXXConstructorDecl>(Func)) {
17866 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17867 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17868 if (Constructor->isDefaultConstructor()) {
17869 if (Constructor->isTrivial() &&
17870 !Constructor->hasAttr<DLLExportAttr>())
17871 return;
17872 DefineImplicitDefaultConstructor(Loc, Constructor);
17873 } else if (Constructor->isCopyConstructor()) {
17874 DefineImplicitCopyConstructor(Loc, Constructor);
17875 } else if (Constructor->isMoveConstructor()) {
17876 DefineImplicitMoveConstructor(Loc, Constructor);
17877 }
17878 } else if (Constructor->getInheritedConstructor()) {
17879 DefineInheritingConstructor(Loc, Constructor);
17880 }
17881 } else if (CXXDestructorDecl *Destructor =
17882 dyn_cast<CXXDestructorDecl>(Func)) {
17883 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17884 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17885 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17886 return;
17887 DefineImplicitDestructor(Loc, Destructor);
17888 }
17889 if (Destructor->isVirtual() && getLangOpts().AppleKext)
17890 MarkVTableUsed(Loc, Destructor->getParent());
17891 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17892 if (MethodDecl->isOverloadedOperator() &&
17893 MethodDecl->getOverloadedOperator() == OO_Equal) {
17894 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17895 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17896 if (MethodDecl->isCopyAssignmentOperator())
17897 DefineImplicitCopyAssignment(Loc, MethodDecl);
17898 else if (MethodDecl->isMoveAssignmentOperator())
17899 DefineImplicitMoveAssignment(Loc, MethodDecl);
17900 }
17901 } else if (isa<CXXConversionDecl>(MethodDecl) &&
17902 MethodDecl->getParent()->isLambda()) {
17903 CXXConversionDecl *Conversion =
17904 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17905 if (Conversion->isLambdaToBlockPointerConversion())
17906 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17907 else
17908 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17909 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17910 MarkVTableUsed(Loc, MethodDecl->getParent());
17911 }
17912
17913 if (Func->isDefaulted() && !Func->isDeleted()) {
17914 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17915 if (DCK != DefaultedComparisonKind::None)
17916 DefineDefaultedComparison(Loc, Func, DCK);
17917 }
17918
17919 // Implicit instantiation of function templates and member functions of
17920 // class templates.
17921 if (Func->isImplicitlyInstantiable()) {
17922 TemplateSpecializationKind TSK =
17923 Func->getTemplateSpecializationKindForInstantiation();
17924 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17925 bool FirstInstantiation = PointOfInstantiation.isInvalid();
17926 if (FirstInstantiation) {
17927 PointOfInstantiation = Loc;
17928 if (auto *MSI = Func->getMemberSpecializationInfo())
17929 MSI->setPointOfInstantiation(Loc);
17930 // FIXME: Notify listener.
17931 else
17932 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17933 } else if (TSK != TSK_ImplicitInstantiation) {
17934 // Use the point of use as the point of instantiation, instead of the
17935 // point of explicit instantiation (which we track as the actual point
17936 // of instantiation). This gives better backtraces in diagnostics.
17937 PointOfInstantiation = Loc;
17938 }
17939
17940 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17941 Func->isConstexpr()) {
17942 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17943 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17944 CodeSynthesisContexts.size())
17945 PendingLocalImplicitInstantiations.push_back(
17946 std::make_pair(Func, PointOfInstantiation));
17947 else if (Func->isConstexpr())
17948 // Do not defer instantiations of constexpr functions, to avoid the
17949 // expression evaluator needing to call back into Sema if it sees a
17950 // call to such a function.
17951 InstantiateFunctionDefinition(PointOfInstantiation, Func);
17952 else {
17953 Func->setInstantiationIsPending(true);
17954 PendingInstantiations.push_back(
17955 std::make_pair(Func, PointOfInstantiation));
17956 // Notify the consumer that a function was implicitly instantiated.
17957 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17958 }
17959 }
17960 } else {
17961 // Walk redefinitions, as some of them may be instantiable.
17962 for (auto i : Func->redecls()) {
17963 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17964 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17965 }
17966 }
17967 });
17968 }
17969
17970 // C++14 [except.spec]p17:
17971 // An exception-specification is considered to be needed when:
17972 // - the function is odr-used or, if it appears in an unevaluated operand,
17973 // would be odr-used if the expression were potentially-evaluated;
17974 //
17975 // Note, we do this even if MightBeOdrUse is false. That indicates that the
17976 // function is a pure virtual function we're calling, and in that case the
17977 // function was selected by overload resolution and we need to resolve its
17978 // exception specification for a different reason.
17979 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17980 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17981 ResolveExceptionSpec(Loc, FPT);
17982
17983 // If this is the first "real" use, act on that.
17984 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17985 // Keep track of used but undefined functions.
17986 if (!Func->isDefined()) {
17987 if (mightHaveNonExternalLinkage(Func))
17988 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17989 else if (Func->getMostRecentDecl()->isInlined() &&
17990 !LangOpts.GNUInline &&
17991 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17992 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17993 else if (isExternalWithNoLinkageType(Func))
17994 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17995 }
17996
17997 // Some x86 Windows calling conventions mangle the size of the parameter
17998 // pack into the name. Computing the size of the parameters requires the
17999 // parameter types to be complete. Check that now.
18000 if (funcHasParameterSizeMangling(*this, Func))
18001 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18002
18003 // In the MS C++ ABI, the compiler emits destructor variants where they are
18004 // used. If the destructor is used here but defined elsewhere, mark the
18005 // virtual base destructors referenced. If those virtual base destructors
18006 // are inline, this will ensure they are defined when emitting the complete
18007 // destructor variant. This checking may be redundant if the destructor is
18008 // provided later in this TU.
18009 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18010 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18011 CXXRecordDecl *Parent = Dtor->getParent();
18012 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18013 CheckCompleteDestructorVariant(Loc, Dtor);
18014 }
18015 }
18016
18017 Func->markUsed(Context);
18018 }
18019}
18020
18021/// Directly mark a variable odr-used. Given a choice, prefer to use
18022/// MarkVariableReferenced since it does additional checks and then
18023/// calls MarkVarDeclODRUsed.
18024/// If the variable must be captured:
18025/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18026/// - else capture it in the DeclContext that maps to the
18027/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18028static void
18029MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
18030 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18031 // Keep track of used but undefined variables.
18032 // FIXME: We shouldn't suppress this warning for static data members.
18033 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18034 (!Var->isExternallyVisible() || Var->isInline() ||
18035 SemaRef.isExternalWithNoLinkageType(Var)) &&
18036 !(Var->isStaticDataMember() && Var->hasInit())) {
18037 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18038 if (old.isInvalid())
18039 old = Loc;
18040 }
18041 QualType CaptureType, DeclRefType;
18042 if (SemaRef.LangOpts.OpenMP)
18043 SemaRef.tryCaptureOpenMPLambdas(Var);
18044 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
18045 /*EllipsisLoc*/ SourceLocation(),
18046 /*BuildAndDiagnose*/ true,
18047 CaptureType, DeclRefType,
18048 FunctionScopeIndexToStopAt);
18049
18050 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18051 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18052 auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
18053 auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
18054 if (VarTarget == Sema::CVT_Host &&
18055 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
18056 UserTarget == Sema::CFT_Global)) {
18057 // Diagnose ODR-use of host global variables in device functions.
18058 // Reference of device global variables in host functions is allowed
18059 // through shadow variables therefore it is not diagnosed.
18060 if (SemaRef.LangOpts.CUDAIsDevice) {
18061 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18062 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18063 SemaRef.targetDiag(Var->getLocation(),
18064 Var->getType().isConstQualified()
18065 ? diag::note_cuda_const_var_unpromoted
18066 : diag::note_cuda_host_var);
18067 }
18068 } else if (VarTarget == Sema::CVT_Device &&
18069 (UserTarget == Sema::CFT_Host ||
18070 UserTarget == Sema::CFT_HostDevice)) {
18071 // Record a CUDA/HIP device side variable if it is ODR-used
18072 // by host code. This is done conservatively, when the variable is
18073 // referenced in any of the following contexts:
18074 // - a non-function context
18075 // - a host function
18076 // - a host device function
18077 // This makes the ODR-use of the device side variable by host code to
18078 // be visible in the device compilation for the compiler to be able to
18079 // emit template variables instantiated by host code only and to
18080 // externalize the static device side variable ODR-used by host code.
18081 if (!Var->hasExternalStorage())
18082 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18083 else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
18084 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18085 }
18086 }
18087
18088 Var->markUsed(SemaRef.Context);
18089}
18090
18091void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
18092 SourceLocation Loc,
18093 unsigned CapturingScopeIndex) {
18094 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18095}
18096
18097static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
18098 ValueDecl *var) {
18099 DeclContext *VarDC = var->getDeclContext();
18100
18101 // If the parameter still belongs to the translation unit, then
18102 // we're actually just using one parameter in the declaration of
18103 // the next.
18104 if (isa<ParmVarDecl>(var) &&
18105 isa<TranslationUnitDecl>(VarDC))
18106 return;
18107
18108 // For C code, don't diagnose about capture if we're not actually in code
18109 // right now; it's impossible to write a non-constant expression outside of
18110 // function context, so we'll get other (more useful) diagnostics later.
18111 //
18112 // For C++, things get a bit more nasty... it would be nice to suppress this
18113 // diagnostic for certain cases like using a local variable in an array bound
18114 // for a member of a local class, but the correct predicate is not obvious.
18115 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18116 return;
18117
18118 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18119 unsigned ContextKind = 3; // unknown
18120 if (isa<CXXMethodDecl>(VarDC) &&
18121 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18122 ContextKind = 2;
18123 } else if (isa<FunctionDecl>(VarDC)) {
18124 ContextKind = 0;
18125 } else if (isa<BlockDecl>(VarDC)) {
18126 ContextKind = 1;
18127 }
18128
18129 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18130 << var << ValueKind << ContextKind << VarDC;
18131 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18132 << var;
18133
18134 // FIXME: Add additional diagnostic info about class etc. which prevents
18135 // capture.
18136}
18137
18138
18139static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
18140 bool &SubCapturesAreNested,
18141 QualType &CaptureType,
18142 QualType &DeclRefType) {
18143 // Check whether we've already captured it.
18144 if (CSI->CaptureMap.count(Var)) {
18145 // If we found a capture, any subcaptures are nested.
18146 SubCapturesAreNested = true;
18147
18148 // Retrieve the capture type for this variable.
18149 CaptureType = CSI->getCapture(Var).getCaptureType();
18150
18151 // Compute the type of an expression that refers to this variable.
18152 DeclRefType = CaptureType.getNonReferenceType();
18153
18154 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18155 // are mutable in the sense that user can change their value - they are
18156 // private instances of the captured declarations.
18157 const Capture &Cap = CSI->getCapture(Var);
18158 if (Cap.isCopyCapture() &&
18159 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
18160 !(isa<CapturedRegionScopeInfo>(CSI) &&
18161 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18162 DeclRefType.addConst();
18163 return true;
18164 }
18165 return false;
18166}
18167
18168// Only block literals, captured statements, and lambda expressions can
18169// capture; other scopes don't work.
18170static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
18171 SourceLocation Loc,
18172 const bool Diagnose, Sema &S) {
18173 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18174 return getLambdaAwareParentOfDeclContext(DC);
18175 else if (Var->hasLocalStorage()) {
18176 if (Diagnose)
18177 diagnoseUncapturableValueReference(S, Loc, Var);
18178 }
18179 return nullptr;
18180}
18181
18182// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18183// certain types of variables (unnamed, variably modified types etc.)
18184// so check for eligibility.
18185static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
18186 SourceLocation Loc,
18187 const bool Diagnose, Sema &S) {
18188
18189 bool IsBlock = isa<BlockScopeInfo>(CSI);
18190 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18191
18192 // Lambdas are not allowed to capture unnamed variables
18193 // (e.g. anonymous unions).
18194 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18195 // assuming that's the intent.
18196 if (IsLambda && !Var->getDeclName()) {
18197 if (Diagnose) {
18198 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18199 S.Diag(Var->getLocation(), diag::note_declared_at);
18200 }
18201 return false;
18202 }
18203
18204 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18205 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18206 if (Diagnose) {
18207 S.Diag(Loc, diag::err_ref_vm_type);
18208 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18209 }
18210 return false;
18211 }
18212 // Prohibit structs with flexible array members too.
18213 // We cannot capture what is in the tail end of the struct.
18214 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18215 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18216 if (Diagnose) {
18217 if (IsBlock)
18218 S.Diag(Loc, diag::err_ref_flexarray_type);
18219 else
18220 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18221 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18222 }
18223 return false;
18224 }
18225 }
18226 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18227 // Lambdas and captured statements are not allowed to capture __block
18228 // variables; they don't support the expected semantics.
18229 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18230 if (Diagnose) {
18231 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18232 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18233 }
18234 return false;
18235 }
18236 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18237 if (S.getLangOpts().OpenCL && IsBlock &&
18238 Var->getType()->isBlockPointerType()) {
18239 if (Diagnose)
18240 S.Diag(Loc, diag::err_opencl_block_ref_block);
18241 return false;
18242 }
18243
18244 return true;
18245}
18246
18247// Returns true if the capture by block was successful.
18248static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
18249 SourceLocation Loc,
18250 const bool BuildAndDiagnose,
18251 QualType &CaptureType,
18252 QualType &DeclRefType,
18253 const bool Nested,
18254 Sema &S, bool Invalid) {
18255 bool ByRef = false;
18256
18257 // Blocks are not allowed to capture arrays, excepting OpenCL.
18258 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18259 // (decayed to pointers).
18260 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18261 if (BuildAndDiagnose) {
18262 S.Diag(Loc, diag::err_ref_array_type);
18263 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18264 Invalid = true;
18265 } else {
18266 return false;
18267 }
18268 }
18269
18270 // Forbid the block-capture of autoreleasing variables.
18271 if (!Invalid &&
18272 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18273 if (BuildAndDiagnose) {
18274 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18275 << /*block*/ 0;
18276 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18277 Invalid = true;
18278 } else {
18279 return false;
18280 }
18281 }
18282
18283 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18284 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18285 QualType PointeeTy = PT->getPointeeType();
18286
18287 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18288 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
18289 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18290 if (BuildAndDiagnose) {
18291 SourceLocation VarLoc = Var->getLocation();
18292 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18293 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18294 }
18295 }
18296 }
18297
18298 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18299 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18300 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
18301 // Block capture by reference does not change the capture or
18302 // declaration reference types.
18303 ByRef = true;
18304 } else {
18305 // Block capture by copy introduces 'const'.
18306 CaptureType = CaptureType.getNonReferenceType().withConst();
18307 DeclRefType = CaptureType;
18308 }
18309
18310 // Actually capture the variable.
18311 if (BuildAndDiagnose)
18312 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18313 CaptureType, Invalid);
18314
18315 return !Invalid;
18316}
18317
18318
18319/// Capture the given variable in the captured region.
18320static bool captureInCapturedRegion(
18321 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
18322 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18323 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18324 bool IsTopScope, Sema &S, bool Invalid) {
18325 // By default, capture variables by reference.
18326 bool ByRef = true;
18327 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18328 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18329 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18330 // Using an LValue reference type is consistent with Lambdas (see below).
18331 if (S.isOpenMPCapturedDecl(Var)) {
18332 bool HasConst = DeclRefType.isConstQualified();
18333 DeclRefType = DeclRefType.getUnqualifiedType();
18334 // Don't lose diagnostics about assignments to const.
18335 if (HasConst)
18336 DeclRefType.addConst();
18337 }
18338 // Do not capture firstprivates in tasks.
18339 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
18340 OMPC_unknown)
18341 return true;
18342 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18343 RSI->OpenMPCaptureLevel);
18344 }
18345
18346 if (ByRef)
18347 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18348 else
18349 CaptureType = DeclRefType;
18350
18351 // Actually capture the variable.
18352 if (BuildAndDiagnose)
18353 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18354 Loc, SourceLocation(), CaptureType, Invalid);
18355
18356 return !Invalid;
18357}
18358
18359/// Capture the given variable in the lambda.
18360static bool captureInLambda(LambdaScopeInfo *LSI,
18361 VarDecl *Var,
18362 SourceLocation Loc,
18363 const bool BuildAndDiagnose,
18364 QualType &CaptureType,
18365 QualType &DeclRefType,
18366 const bool RefersToCapturedVariable,
18367 const Sema::TryCaptureKind Kind,
18368 SourceLocation EllipsisLoc,
18369 const bool IsTopScope,
18370 Sema &S, bool Invalid) {
18371 // Determine whether we are capturing by reference or by value.
18372 bool ByRef = false;
18373 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18374 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18375 } else {
18376 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18377 }
18378
18379 // Compute the type of the field that will capture this variable.
18380 if (ByRef) {
18381 // C++11 [expr.prim.lambda]p15:
18382 // An entity is captured by reference if it is implicitly or
18383 // explicitly captured but not captured by copy. It is
18384 // unspecified whether additional unnamed non-static data
18385 // members are declared in the closure type for entities
18386 // captured by reference.
18387 //
18388 // FIXME: It is not clear whether we want to build an lvalue reference
18389 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18390 // to do the former, while EDG does the latter. Core issue 1249 will
18391 // clarify, but for now we follow GCC because it's a more permissive and
18392 // easily defensible position.
18393 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18394 } else {
18395 // C++11 [expr.prim.lambda]p14:
18396 // For each entity captured by copy, an unnamed non-static
18397 // data member is declared in the closure type. The
18398 // declaration order of these members is unspecified. The type
18399 // of such a data member is the type of the corresponding
18400 // captured entity if the entity is not a reference to an
18401 // object, or the referenced type otherwise. [Note: If the
18402 // captured entity is a reference to a function, the
18403 // corresponding data member is also a reference to a
18404 // function. - end note ]
18405 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18406 if (!RefType->getPointeeType()->isFunctionType())
18407 CaptureType = RefType->getPointeeType();
18408 }
18409
18410 // Forbid the lambda copy-capture of autoreleasing variables.
18411 if (!Invalid &&
18412 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18413 if (BuildAndDiagnose) {
18414 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18415 S.Diag(Var->getLocation(), diag::note_previous_decl)
18416 << Var->getDeclName();
18417 Invalid = true;
18418 } else {
18419 return false;
18420 }
18421 }
18422
18423 // Make sure that by-copy captures are of a complete and non-abstract type.
18424 if (!Invalid && BuildAndDiagnose) {
18425 if (!CaptureType->isDependentType() &&
18426 S.RequireCompleteSizedType(
18427 Loc, CaptureType,
18428 diag::err_capture_of_incomplete_or_sizeless_type,
18429 Var->getDeclName()))
18430 Invalid = true;
18431 else if (S.RequireNonAbstractType(Loc, CaptureType,
18432 diag::err_capture_of_abstract_type))
18433 Invalid = true;
18434 }
18435 }
18436
18437 // Compute the type of a reference to this captured variable.
18438 if (ByRef)
18439 DeclRefType = CaptureType.getNonReferenceType();
18440 else {
18441 // C++ [expr.prim.lambda]p5:
18442 // The closure type for a lambda-expression has a public inline
18443 // function call operator [...]. This function call operator is
18444 // declared const (9.3.1) if and only if the lambda-expression's
18445 // parameter-declaration-clause is not followed by mutable.
18446 DeclRefType = CaptureType.getNonReferenceType();
18447 if (!LSI->Mutable && !CaptureType->isReferenceType())
18448 DeclRefType.addConst();
18449 }
18450
18451 // Add the capture.
18452 if (BuildAndDiagnose)
18453 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18454 Loc, EllipsisLoc, CaptureType, Invalid);
18455
18456 return !Invalid;
18457}
18458
18459static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
18460 // Offer a Copy fix even if the type is dependent.
18461 if (Var->getType()->isDependentType())
18462 return true;
18463 QualType T = Var->getType().getNonReferenceType();
18464 if (T.isTriviallyCopyableType(Context))
18465 return true;
18466 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18467
18468 if (!(RD = RD->getDefinition()))
18469 return false;
18470 if (RD->hasSimpleCopyConstructor())
18471 return true;
18472 if (RD->hasUserDeclaredCopyConstructor())
18473 for (CXXConstructorDecl *Ctor : RD->ctors())
18474 if (Ctor->isCopyConstructor())
18475 return !Ctor->isDeleted();
18476 }
18477 return false;
18478}
18479
18480/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18481/// default capture. Fixes may be omitted if they aren't allowed by the
18482/// standard, for example we can't emit a default copy capture fix-it if we
18483/// already explicitly copy capture capture another variable.
18484static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
18485 VarDecl *Var) {
18486 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", 18486, __extension__ __PRETTY_FUNCTION__
))
;
18487 // Don't offer Capture by copy of default capture by copy fixes if Var is
18488 // known not to be copy constructible.
18489 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18490
18491 SmallString<32> FixBuffer;
18492 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18493 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18494 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18495 if (ShouldOfferCopyFix) {
18496 // Offer fixes to insert an explicit capture for the variable.
18497 // [] -> [VarName]
18498 // [OtherCapture] -> [OtherCapture, VarName]
18499 FixBuffer.assign({Separator, Var->getName()});
18500 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18501 << Var << /*value*/ 0
18502 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18503 }
18504 // As above but capture by reference.
18505 FixBuffer.assign({Separator, "&", Var->getName()});
18506 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18507 << Var << /*reference*/ 1
18508 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18509 }
18510
18511 // Only try to offer default capture if there are no captures excluding this
18512 // and init captures.
18513 // [this]: OK.
18514 // [X = Y]: OK.
18515 // [&A, &B]: Don't offer.
18516 // [A, B]: Don't offer.
18517 if (llvm::any_of(LSI->Captures, [](Capture &C) {
18518 return !C.isThisCapture() && !C.isInitCapture();
18519 }))
18520 return;
18521
18522 // The default capture specifiers, '=' or '&', must appear first in the
18523 // capture body.
18524 SourceLocation DefaultInsertLoc =
18525 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
18526
18527 if (ShouldOfferCopyFix) {
18528 bool CanDefaultCopyCapture = true;
18529 // [=, *this] OK since c++17
18530 // [=, this] OK since c++20
18531 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18532 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18533 ? LSI->getCXXThisCapture().isCopyCapture()
18534 : false;
18535 // We can't use default capture by copy if any captures already specified
18536 // capture by copy.
18537 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18538 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18539 })) {
18540 FixBuffer.assign({"=", Separator});
18541 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18542 << /*value*/ 0
18543 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18544 }
18545 }
18546
18547 // We can't use default capture by reference if any captures already specified
18548 // capture by reference.
18549 if (llvm::none_of(LSI->Captures, [](Capture &C) {
18550 return !C.isInitCapture() && C.isReferenceCapture() &&
18551 !C.isThisCapture();
18552 })) {
18553 FixBuffer.assign({"&", Separator});
18554 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18555 << /*reference*/ 1
18556 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18557 }
18558}
18559
18560static bool CheckCaptureUseBeforeLambdaQualifiers(Sema &S, VarDecl *Var,
18561 SourceLocation ExprLoc,
18562 LambdaScopeInfo *LSI) {
18563
18564 // Allow `[a = 1](decltype(a)) {}` as per CWG2569.
18565 if (S.InMutableAgnosticContext)
18566 return true;
18567
18568 if (Var->isInvalidDecl())
18569 return false;
18570
18571 bool ByCopy = LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval;
18572 SourceLocation Loc = LSI->IntroducerRange.getBegin();
18573 bool Explicitly = false;
18574 for (auto &&C : LSI->DelayedCaptures) {
18575 VarDecl *CV = C.second.Var;
18576 if (Var != CV)
18577 continue;
18578 ByCopy = C.second.Kind == LambdaCaptureKind::LCK_ByCopy;
18579 Loc = C.second.Loc;
18580 Explicitly = true;
18581 break;
18582 }
18583 if (ByCopy && LSI->BeforeLambdaQualifiersScope) {
18584 // This can only occur in a non-ODR context, so we need to diagnose eagerly,
18585 // even when BuildAndDiagnose is false
18586 S.Diag(ExprLoc, diag::err_lambda_used_before_capture) << Var;
18587 S.Diag(Loc, diag::note_var_explicitly_captured_here) << Var << Explicitly;
18588 if (!Var->isInitCapture())
18589 S.Diag(Var->getBeginLoc(), diag::note_entity_declared_at) << Var;
18590 Var->setInvalidDecl();
18591 return false;
18592 }
18593 return true;
18594}
18595
18596bool Sema::tryCaptureVariable(
18597 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18598 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18599 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18600 // An init-capture is notionally from the context surrounding its
18601 // declaration, but its parent DC is the lambda class.
18602 DeclContext *VarDC = Var->getDeclContext();
18603 if (Var->isInitCapture())
18604 VarDC = VarDC->getParent();
18605
18606 DeclContext *DC = CurContext;
18607 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18608 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18609 // We need to sync up the Declaration Context with the
18610 // FunctionScopeIndexToStopAt
18611 if (FunctionScopeIndexToStopAt) {
18612 unsigned FSIndex = FunctionScopes.size() - 1;
18613 while (FSIndex != MaxFunctionScopesIndex) {
18614 DC = getLambdaAwareParentOfDeclContext(DC);
18615 --FSIndex;
18616 }
18617 }
18618
18619 // Capture global variables if it is required to use private copy of this
18620 // variable.
18621 bool IsGlobal = !Var->hasLocalStorage();
18622 if (IsGlobal &&
18623 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18624 MaxFunctionScopesIndex)))
18625 return true;
18626 Var = Var->getCanonicalDecl();
18627
18628 // Walk up the stack to determine whether we can capture the variable,
18629 // performing the "simple" checks that don't depend on type. We stop when
18630 // we've either hit the declared scope of the variable or find an existing
18631 // capture of that variable. We start from the innermost capturing-entity
18632 // (the DC) and ensure that all intervening capturing-entities
18633 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18634 // declcontext can either capture the variable or have already captured
18635 // the variable.
18636 CaptureType = Var->getType();
18637 DeclRefType = CaptureType.getNonReferenceType();
18638 bool Nested = false;
18639 bool Explicit = (Kind != TryCapture_Implicit);
18640 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18641 bool IsInLambdaBeforeQualifiers;
18642 do {
18643 IsInLambdaBeforeQualifiers = false;
18644
18645 LambdaScopeInfo *LSI = nullptr;
18646 if (!FunctionScopes.empty())
18647 LSI = dyn_cast_or_null<LambdaScopeInfo>(
18648 FunctionScopes[FunctionScopesIndex]);
18649 if (LSI && LSI->BeforeLambdaQualifiersScope) {
18650 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
18651 return true;
18652 IsInLambdaBeforeQualifiers = true;
18653 if (!CheckCaptureUseBeforeLambdaQualifiers(*this, Var, ExprLoc, LSI)) {
18654 break;
18655 }
18656 }
18657
18658 // If the variable is declared in the current context, there is no need to
18659 // capture it.
18660 if (!IsInLambdaBeforeQualifiers &&
18661 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
18662 return true;
18663
18664 // Only block literals, captured statements, and lambda expressions can
18665 // capture; other scopes don't work.
18666 DeclContext *ParentDC =
18667 IsInLambdaBeforeQualifiers
18668 ? DC->getParent()
18669 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
18670 BuildAndDiagnose, *this);
18671 // We need to check for the parent *first* because, if we *have*
18672 // private-captured a global variable, we need to recursively capture it in
18673 // intermediate blocks, lambdas, etc.
18674 if (!ParentDC) {
18675 if (IsGlobal) {
18676 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18677 break;
18678 }
18679 return true;
18680 }
18681
18682 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
18683 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18684
18685 // Check whether we've already captured it.
18686 if (!IsInLambdaBeforeQualifiers &&
18687 isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18688 DeclRefType)) {
18689 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18690 break;
18691 }
18692 // If we are instantiating a generic lambda call operator body,
18693 // we do not want to capture new variables. What was captured
18694 // during either a lambdas transformation or initial parsing
18695 // should be used.
18696 if (!IsInLambdaBeforeQualifiers &&
18697 isGenericLambdaCallOperatorSpecialization(DC)) {
18698 if (BuildAndDiagnose) {
18699 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18700 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18701 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18702 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18703 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18704 buildLambdaCaptureFixit(*this, LSI, Var);
18705 } else
18706 diagnoseUncapturableValueReference(*this, ExprLoc, Var);
18707 }
18708 return true;
18709 }
18710
18711 // Try to capture variable-length arrays types.
18712 if (!IsInLambdaBeforeQualifiers &&
18713 Var->getType()->isVariablyModifiedType()) {
18714 // We're going to walk down into the type and look for VLA
18715 // expressions.
18716 QualType QTy = Var->getType();
18717 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18718 QTy = PVD->getOriginalType();
18719 captureVariablyModifiedType(Context, QTy, CSI);
18720 }
18721
18722 if (!IsInLambdaBeforeQualifiers && getLangOpts().OpenMP) {
18723 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18724 // OpenMP private variables should not be captured in outer scope, so
18725 // just break here. Similarly, global variables that are captured in a
18726 // target region should not be captured outside the scope of the region.
18727 if (RSI->CapRegionKind == CR_OpenMP) {
18728 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
18729 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18730 // If the variable is private (i.e. not captured) and has variably
18731 // modified type, we still need to capture the type for correct
18732 // codegen in all regions, associated with the construct. Currently,
18733 // it is captured in the innermost captured region only.
18734 if (IsOpenMPPrivateDecl != OMPC_unknown &&
18735 Var->getType()->isVariablyModifiedType()) {
18736 QualType QTy = Var->getType();
18737 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18738 QTy = PVD->getOriginalType();
18739 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
18740 I < E; ++I) {
18741 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18742 FunctionScopes[FunctionScopesIndex - I]);
18743 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", 18745, __extension__ __PRETTY_FUNCTION__
))
18744 "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", 18745, __extension__ __PRETTY_FUNCTION__
))
18745 "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", 18745, __extension__ __PRETTY_FUNCTION__
))
;
18746 captureVariablyModifiedType(Context, QTy, OuterRSI);
18747 }
18748 }
18749 bool IsTargetCap =
18750 IsOpenMPPrivateDecl != OMPC_private &&
18751 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18752 RSI->OpenMPCaptureLevel);
18753 // Do not capture global if it is not privatized in outer regions.
18754 bool IsGlobalCap =
18755 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18756 RSI->OpenMPCaptureLevel);
18757
18758 // When we detect target captures we are looking from inside the
18759 // target region, therefore we need to propagate the capture from the
18760 // enclosing region. Therefore, the capture is not initially nested.
18761 if (IsTargetCap)
18762 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18763
18764 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18765 (IsGlobal && !IsGlobalCap)) {
18766 Nested = !IsTargetCap;
18767 bool HasConst = DeclRefType.isConstQualified();
18768 DeclRefType = DeclRefType.getUnqualifiedType();
18769 // Don't lose diagnostics about assignments to const.
18770 if (HasConst)
18771 DeclRefType.addConst();
18772 CaptureType = Context.getLValueReferenceType(DeclRefType);
18773 break;
18774 }
18775 }
18776 }
18777 }
18778 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18779 // No capture-default, and this is not an explicit capture
18780 // so cannot capture this variable.
18781 if (BuildAndDiagnose) {
18782 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18783 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18784 auto *LSI = cast<LambdaScopeInfo>(CSI);
18785 if (LSI->Lambda) {
18786 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18787 buildLambdaCaptureFixit(*this, LSI, Var);
18788 }
18789 // FIXME: If we error out because an outer lambda can not implicitly
18790 // capture a variable that an inner lambda explicitly captures, we
18791 // should have the inner lambda do the explicit capture - because
18792 // it makes for cleaner diagnostics later. This would purely be done
18793 // so that the diagnostic does not misleadingly claim that a variable
18794 // can not be captured by a lambda implicitly even though it is captured
18795 // explicitly. Suggestion:
18796 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18797 // at the function head
18798 // - cache the StartingDeclContext - this must be a lambda
18799 // - captureInLambda in the innermost lambda the variable.
18800 }
18801 return true;
18802 }
18803 Explicit = false;
18804 FunctionScopesIndex--;
18805 if (!IsInLambdaBeforeQualifiers)
18806 DC = ParentDC;
18807 } while (IsInLambdaBeforeQualifiers || !VarDC->Equals(DC));
18808
18809 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18810 // computing the type of the capture at each step, checking type-specific
18811 // requirements, and adding captures if requested.
18812 // If the variable had already been captured previously, we start capturing
18813 // at the lambda nested within that one.
18814 bool Invalid = false;
18815 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18816 ++I) {
18817 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18818
18819 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18820 // certain types of variables (unnamed, variably modified types etc.)
18821 // so check for eligibility.
18822 if (!Invalid)
18823 Invalid =
18824 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18825
18826 // After encountering an error, if we're actually supposed to capture, keep
18827 // capturing in nested contexts to suppress any follow-on diagnostics.
18828 if (Invalid && !BuildAndDiagnose)
18829 return true;
18830
18831 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18832 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18833 DeclRefType, Nested, *this, Invalid);
18834 Nested = true;
18835 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18836 Invalid = !captureInCapturedRegion(
18837 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18838 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18839 Nested = true;
18840 } else {
18841 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18842 if (!CheckCaptureUseBeforeLambdaQualifiers(*this, Var, ExprLoc, LSI)) {
18843 return true;
18844 }
18845 Invalid =
18846 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18847 DeclRefType, Nested, Kind, EllipsisLoc,
18848 /*IsTopScope*/ I == N - 1, *this, Invalid);
18849 Nested = true;
18850 }
18851
18852 if (Invalid && !BuildAndDiagnose)
18853 return true;
18854 }
18855 return Invalid;
18856}
18857
18858bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18859 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18860 QualType CaptureType;
18861 QualType DeclRefType;
18862 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18863 /*BuildAndDiagnose=*/true, CaptureType,
18864 DeclRefType, nullptr);
18865}
18866
18867bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18868 QualType CaptureType;
18869 QualType DeclRefType;
18870 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18871 /*BuildAndDiagnose=*/false, CaptureType,
18872 DeclRefType, nullptr);
18873}
18874
18875QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18876 QualType CaptureType;
18877 QualType DeclRefType;
18878
18879 // Determine whether we can capture this variable.
18880 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18881 /*BuildAndDiagnose=*/false, CaptureType,
18882 DeclRefType, nullptr))
18883 return QualType();
18884
18885 return DeclRefType;
18886}
18887
18888namespace {
18889// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18890// The produced TemplateArgumentListInfo* points to data stored within this
18891// object, so should only be used in contexts where the pointer will not be
18892// used after the CopiedTemplateArgs object is destroyed.
18893class CopiedTemplateArgs {
18894 bool HasArgs;
18895 TemplateArgumentListInfo TemplateArgStorage;
18896public:
18897 template<typename RefExpr>
18898 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18899 if (HasArgs)
18900 E->copyTemplateArgumentsInto(TemplateArgStorage);
18901 }
18902 operator TemplateArgumentListInfo*()
18903#ifdef __has_cpp_attribute
18904#if0 __has_cpp_attribute(clang::lifetimebound)1
18905 [[clang::lifetimebound]]
18906#endif
18907#endif
18908 {
18909 return HasArgs ? &TemplateArgStorage : nullptr;
18910 }
18911};
18912}
18913
18914/// Walk the set of potential results of an expression and mark them all as
18915/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18916///
18917/// \return A new expression if we found any potential results, ExprEmpty() if
18918/// not, and ExprError() if we diagnosed an error.
18919static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18920 NonOdrUseReason NOUR) {
18921 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18922 // an object that satisfies the requirements for appearing in a
18923 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18924 // is immediately applied." This function handles the lvalue-to-rvalue
18925 // conversion part.
18926 //
18927 // If we encounter a node that claims to be an odr-use but shouldn't be, we
18928 // transform it into the relevant kind of non-odr-use node and rebuild the
18929 // tree of nodes leading to it.
18930 //
18931 // This is a mini-TreeTransform that only transforms a restricted subset of
18932 // nodes (and only certain operands of them).
18933
18934 // Rebuild a subexpression.
18935 auto Rebuild = [&](Expr *Sub) {
18936 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18937 };
18938
18939 // Check whether a potential result satisfies the requirements of NOUR.
18940 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18941 // Any entity other than a VarDecl is always odr-used whenever it's named
18942 // in a potentially-evaluated expression.
18943 auto *VD = dyn_cast<VarDecl>(D);
18944 if (!VD)
18945 return true;
18946
18947 // C++2a [basic.def.odr]p4:
18948 // A variable x whose name appears as a potentially-evalauted expression
18949 // e is odr-used by e unless
18950 // -- x is a reference that is usable in constant expressions, or
18951 // -- x is a variable of non-reference type that is usable in constant
18952 // expressions and has no mutable subobjects, and e is an element of
18953 // the set of potential results of an expression of
18954 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
18955 // conversion is applied, or
18956 // -- x is a variable of non-reference type, and e is an element of the
18957 // set of potential results of a discarded-value expression to which
18958 // the lvalue-to-rvalue conversion is not applied
18959 //
18960 // We check the first bullet and the "potentially-evaluated" condition in
18961 // BuildDeclRefExpr. We check the type requirements in the second bullet
18962 // in CheckLValueToRValueConversionOperand below.
18963 switch (NOUR) {
18964 case NOUR_None:
18965 case NOUR_Unevaluated:
18966 llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason"
, "clang/lib/Sema/SemaExpr.cpp", 18966)
;
18967
18968 case NOUR_Constant:
18969 // Constant references were handled when they were built.
18970 if (VD->getType()->isReferenceType())
18971 return true;
18972 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18973 if (RD->hasMutableFields())
18974 return true;
18975 if (!VD->isUsableInConstantExpressions(S.Context))
18976 return true;
18977 break;
18978
18979 case NOUR_Discarded:
18980 if (VD->getType()->isReferenceType())
18981 return true;
18982 break;
18983 }
18984 return false;
18985 };
18986
18987 // Mark that this expression does not constitute an odr-use.
18988 auto MarkNotOdrUsed = [&] {
18989 S.MaybeODRUseExprs.remove(E);
18990 if (LambdaScopeInfo *LSI = S.getCurLambda())
18991 LSI->markVariableExprAsNonODRUsed(E);
18992 };
18993
18994 // C++2a [basic.def.odr]p2:
18995 // The set of potential results of an expression e is defined as follows:
18996 switch (E->getStmtClass()) {
18997 // -- If e is an id-expression, ...
18998 case Expr::DeclRefExprClass: {
18999 auto *DRE = cast<DeclRefExpr>(E);
19000 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19001 break;
19002
19003 // Rebuild as a non-odr-use DeclRefExpr.
19004 MarkNotOdrUsed();
19005 return DeclRefExpr::Create(
19006 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19007 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19008 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19009 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19010 }
19011
19012 case Expr::FunctionParmPackExprClass: {
19013 auto *FPPE = cast<FunctionParmPackExpr>(E);
19014 // If any of the declarations in the pack is odr-used, then the expression
19015 // as a whole constitutes an odr-use.
19016 for (VarDecl *D : *FPPE)
19017 if (IsPotentialResultOdrUsed(D))
19018 return ExprEmpty();
19019
19020 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19021 // nothing cares about whether we marked this as an odr-use, but it might
19022 // be useful for non-compiler tools.
19023 MarkNotOdrUsed();
19024 break;
19025 }
19026
19027 // -- If e is a subscripting operation with an array operand...
19028 case Expr::ArraySubscriptExprClass: {
19029 auto *ASE = cast<ArraySubscriptExpr>(E);
19030 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19031 if (!OldBase->getType()->isArrayType())
19032 break;
19033 ExprResult Base = Rebuild(OldBase);
19034 if (!Base.isUsable())
19035 return Base;
19036 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19037 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19038 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19039 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19040 ASE->getRBracketLoc());
19041 }
19042
19043 case Expr::MemberExprClass: {
19044 auto *ME = cast<MemberExpr>(E);
19045 // -- If e is a class member access expression [...] naming a non-static
19046 // data member...
19047 if (isa<FieldDecl>(ME->getMemberDecl())) {
19048 ExprResult Base = Rebuild(ME->getBase());
19049 if (!Base.isUsable())
19050 return Base;
19051 return MemberExpr::Create(
19052 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19053 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19054 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19055 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19056 ME->getObjectKind(), ME->isNonOdrUse());
19057 }
19058
19059 if (ME->getMemberDecl()->isCXXInstanceMember())
19060 break;
19061
19062 // -- If e is a class member access expression naming a static data member,
19063 // ...
19064 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19065 break;
19066
19067 // Rebuild as a non-odr-use MemberExpr.
19068 MarkNotOdrUsed();
19069 return MemberExpr::Create(
19070 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19071 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19072 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19073 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19074 }
19075
19076 case Expr::BinaryOperatorClass: {
19077 auto *BO = cast<BinaryOperator>(E);
19078 Expr *LHS = BO->getLHS();
19079 Expr *RHS = BO->getRHS();
19080 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19081 if (BO->getOpcode() == BO_PtrMemD) {
19082 ExprResult Sub = Rebuild(LHS);
19083 if (!Sub.isUsable())
19084 return Sub;
19085 LHS = Sub.get();
19086 // -- If e is a comma expression, ...
19087 } else if (BO->getOpcode() == BO_Comma) {
19088 ExprResult Sub = Rebuild(RHS);
19089 if (!Sub.isUsable())
19090 return Sub;
19091 RHS = Sub.get();
19092 } else {
19093 break;
19094 }
19095 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
19096 LHS, RHS);
19097 }
19098
19099 // -- If e has the form (e1)...
19100 case Expr::ParenExprClass: {
19101 auto *PE = cast<ParenExpr>(E);
19102 ExprResult Sub = Rebuild(PE->getSubExpr());
19103 if (!Sub.isUsable())
19104 return Sub;
19105 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19106 }
19107
19108 // -- If e is a glvalue conditional expression, ...
19109 // We don't apply this to a binary conditional operator. FIXME: Should we?
19110 case Expr::ConditionalOperatorClass: {
19111 auto *CO = cast<ConditionalOperator>(E);
19112 ExprResult LHS = Rebuild(CO->getLHS());
19113 if (LHS.isInvalid())
19114 return ExprError();
19115 ExprResult RHS = Rebuild(CO->getRHS());
19116 if (RHS.isInvalid())
19117 return ExprError();
19118 if (!LHS.isUsable() && !RHS.isUsable())
19119 return ExprEmpty();
19120 if (!LHS.isUsable())
19121 LHS = CO->getLHS();
19122 if (!RHS.isUsable())
19123 RHS = CO->getRHS();
19124 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19125 CO->getCond(), LHS.get(), RHS.get());
19126 }
19127
19128 // [Clang extension]
19129 // -- If e has the form __extension__ e1...
19130 case Expr::UnaryOperatorClass: {
19131 auto *UO = cast<UnaryOperator>(E);
19132 if (UO->getOpcode() != UO_Extension)
19133 break;
19134 ExprResult Sub = Rebuild(UO->getSubExpr());
19135 if (!Sub.isUsable())
19136 return Sub;
19137 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19138 Sub.get());
19139 }
19140
19141 // [Clang extension]
19142 // -- If e has the form _Generic(...), the set of potential results is the
19143 // union of the sets of potential results of the associated expressions.
19144 case Expr::GenericSelectionExprClass: {
19145 auto *GSE = cast<GenericSelectionExpr>(E);
19146
19147 SmallVector<Expr *, 4> AssocExprs;
19148 bool AnyChanged = false;
19149 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19150 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19151 if (AssocExpr.isInvalid())
19152 return ExprError();
19153 if (AssocExpr.isUsable()) {
19154 AssocExprs.push_back(AssocExpr.get());
19155 AnyChanged = true;
19156 } else {
19157 AssocExprs.push_back(OrigAssocExpr);
19158 }
19159 }
19160
19161 return AnyChanged ? S.CreateGenericSelectionExpr(
19162 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19163 GSE->getRParenLoc(), GSE->getControllingExpr(),
19164 GSE->getAssocTypeSourceInfos(), AssocExprs)
19165 : ExprEmpty();
19166 }
19167
19168 // [Clang extension]
19169 // -- If e has the form __builtin_choose_expr(...), the set of potential
19170 // results is the union of the sets of potential results of the
19171 // second and third subexpressions.
19172 case Expr::ChooseExprClass: {
19173 auto *CE = cast<ChooseExpr>(E);
19174
19175 ExprResult LHS = Rebuild(CE->getLHS());
19176 if (LHS.isInvalid())
19177 return ExprError();
19178
19179 ExprResult RHS = Rebuild(CE->getLHS());
19180 if (RHS.isInvalid())
19181 return ExprError();
19182
19183 if (!LHS.get() && !RHS.get())
19184 return ExprEmpty();
19185 if (!LHS.isUsable())
19186 LHS = CE->getLHS();
19187 if (!RHS.isUsable())
19188 RHS = CE->getRHS();
19189
19190 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19191 RHS.get(), CE->getRParenLoc());
19192 }
19193
19194 // Step through non-syntactic nodes.
19195 case Expr::ConstantExprClass: {
19196 auto *CE = cast<ConstantExpr>(E);
19197 ExprResult Sub = Rebuild(CE->getSubExpr());
19198 if (!Sub.isUsable())
19199 return Sub;
19200 return ConstantExpr::Create(S.Context, Sub.get());
19201 }
19202
19203 // We could mostly rely on the recursive rebuilding to rebuild implicit
19204 // casts, but not at the top level, so rebuild them here.
19205 case Expr::ImplicitCastExprClass: {
19206 auto *ICE = cast<ImplicitCastExpr>(E);
19207 // Only step through the narrow set of cast kinds we expect to encounter.
19208 // Anything else suggests we've left the region in which potential results
19209 // can be found.
19210 switch (ICE->getCastKind()) {
19211 case CK_NoOp:
19212 case CK_DerivedToBase:
19213 case CK_UncheckedDerivedToBase: {
19214 ExprResult Sub = Rebuild(ICE->getSubExpr());
19215 if (!Sub.isUsable())
19216 return Sub;
19217 CXXCastPath Path(ICE->path());
19218 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19219 ICE->getValueKind(), &Path);
19220 }
19221
19222 default:
19223 break;
19224 }
19225 break;
19226 }
19227
19228 default:
19229 break;
19230 }
19231
19232 // Can't traverse through this node. Nothing to do.
19233 return ExprEmpty();
19234}
19235
19236ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
19237 // Check whether the operand is or contains an object of non-trivial C union
19238 // type.
19239 if (E->getType().isVolatileQualified() &&
19240 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19241 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19242 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
19243 Sema::NTCUC_LValueToRValueVolatile,
19244 NTCUK_Destruct|NTCUK_Copy);
19245
19246 // C++2a [basic.def.odr]p4:
19247 // [...] an expression of non-volatile-qualified non-class type to which
19248 // the lvalue-to-rvalue conversion is applied [...]
19249 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19250 return E;
19251
19252 ExprResult Result =
19253 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
19254 if (Result.isInvalid())
19255 return ExprError();
19256 return Result.get() ? Result : E;
19257}
19258
19259ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
19260 Res = CorrectDelayedTyposInExpr(Res);
19261
19262 if (!Res.isUsable())
19263 return Res;
19264
19265 // If a constant-expression is a reference to a variable where we delay
19266 // deciding whether it is an odr-use, just assume we will apply the
19267 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19268 // (a non-type template argument), we have special handling anyway.
19269 return CheckLValueToRValueConversionOperand(Res.get());
19270}
19271
19272void Sema::CleanupVarDeclMarking() {
19273 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19274 // call.
19275 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19276 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19277
19278 for (Expr *E : LocalMaybeODRUseExprs) {
19279 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19280 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19281 DRE->getLocation(), *this);
19282 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19283 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19284 *this);
19285 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19286 for (VarDecl *VD : *FP)
19287 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19288 } else {
19289 llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "clang/lib/Sema/SemaExpr.cpp"
, 19289)
;
19290 }
19291 }
19292
19293 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", 19294, __extension__ __PRETTY_FUNCTION__
))
19294 "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", 19294, __extension__ __PRETTY_FUNCTION__
))
;
19295}
19296
19297static void DoMarkVarDeclReferenced(
19298 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19299 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19300 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", 19302, __extension__ __PRETTY_FUNCTION__
))
19301 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", 19302, __extension__ __PRETTY_FUNCTION__
))
19302 "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", 19302, __extension__ __PRETTY_FUNCTION__
))
;
19303 Var->setReferenced();
19304
19305 if (Var->isInvalidDecl())
19306 return;
19307
19308 auto *MSI = Var->getMemberSpecializationInfo();
19309 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
19310 : Var->getTemplateSpecializationKind();
19311
19312 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19313 bool UsableInConstantExpr =
19314 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
19315
19316 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19317 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19318 }
19319
19320 // C++20 [expr.const]p12:
19321 // A variable [...] is needed for constant evaluation if it is [...] a
19322 // variable whose name appears as a potentially constant evaluated
19323 // expression that is either a contexpr variable or is of non-volatile
19324 // const-qualified integral type or of reference type
19325 bool NeededForConstantEvaluation =
19326 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19327
19328 bool NeedDefinition =
19329 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19330
19331 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", 19332, __extension__ __PRETTY_FUNCTION__
))
19332 "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", 19332, __extension__ __PRETTY_FUNCTION__
))
;
19333
19334 // If this might be a member specialization of a static data member, check
19335 // the specialization is visible. We already did the checks for variable
19336 // template specializations when we created them.
19337 if (NeedDefinition && TSK != TSK_Undeclared &&
19338 !isa<VarTemplateSpecializationDecl>(Var))
19339 SemaRef.checkSpecializationVisibility(Loc, Var);
19340
19341 // Perform implicit instantiation of static data members, static data member
19342 // templates of class templates, and variable template specializations. Delay
19343 // instantiations of variable templates, except for those that could be used
19344 // in a constant expression.
19345 if (NeedDefinition && isTemplateInstantiation(TSK)) {
19346 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19347 // instantiation declaration if a variable is usable in a constant
19348 // expression (among other cases).
19349 bool TryInstantiating =
19350 TSK == TSK_ImplicitInstantiation ||
19351 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19352
19353 if (TryInstantiating) {
19354 SourceLocation PointOfInstantiation =
19355 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19356 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19357 if (FirstInstantiation) {
19358 PointOfInstantiation = Loc;
19359 if (MSI)
19360 MSI->setPointOfInstantiation(PointOfInstantiation);
19361 // FIXME: Notify listener.
19362 else
19363 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19364 }
19365
19366 if (UsableInConstantExpr) {
19367 // Do not defer instantiations of variables that could be used in a
19368 // constant expression.
19369 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19370 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19371 });
19372
19373 // Re-set the member to trigger a recomputation of the dependence bits
19374 // for the expression.
19375 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19376 DRE->setDecl(DRE->getDecl());
19377 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19378 ME->setMemberDecl(ME->getMemberDecl());
19379 } else if (FirstInstantiation ||
19380 isa<VarTemplateSpecializationDecl>(Var)) {
19381 // FIXME: For a specialization of a variable template, we don't
19382 // distinguish between "declaration and type implicitly instantiated"
19383 // and "implicit instantiation of definition requested", so we have
19384 // no direct way to avoid enqueueing the pending instantiation
19385 // multiple times.
19386 SemaRef.PendingInstantiations
19387 .push_back(std::make_pair(Var, PointOfInstantiation));
19388 }
19389 }
19390 }
19391
19392 // C++2a [basic.def.odr]p4:
19393 // A variable x whose name appears as a potentially-evaluated expression e
19394 // is odr-used by e unless
19395 // -- x is a reference that is usable in constant expressions
19396 // -- x is a variable of non-reference type that is usable in constant
19397 // expressions and has no mutable subobjects [FIXME], and e is an
19398 // element of the set of potential results of an expression of
19399 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19400 // conversion is applied
19401 // -- x is a variable of non-reference type, and e is an element of the set
19402 // of potential results of a discarded-value expression to which the
19403 // lvalue-to-rvalue conversion is not applied [FIXME]
19404 //
19405 // We check the first part of the second bullet here, and
19406 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19407 // FIXME: To get the third bullet right, we need to delay this even for
19408 // variables that are not usable in constant expressions.
19409
19410 // If we already know this isn't an odr-use, there's nothing more to do.
19411 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19412 if (DRE->isNonOdrUse())
19413 return;
19414 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19415 if (ME->isNonOdrUse())
19416 return;
19417
19418 switch (OdrUse) {
19419 case OdrUseContext::None:
19420 assert((!E || isa<FunctionParmPackExpr>(E)) &&(static_cast <bool> ((!E || isa<FunctionParmPackExpr
>(E)) && "missing non-odr-use marking for unevaluated decl ref"
) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\""
, "clang/lib/Sema/SemaExpr.cpp", 19421, __extension__ __PRETTY_FUNCTION__
))
19421 "missing non-odr-use marking for unevaluated decl ref")(static_cast <bool> ((!E || isa<FunctionParmPackExpr
>(E)) && "missing non-odr-use marking for unevaluated decl ref"
) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\""
, "clang/lib/Sema/SemaExpr.cpp", 19421, __extension__ __PRETTY_FUNCTION__
))
;
19422 break;
19423
19424 case OdrUseContext::FormallyOdrUsed:
19425 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19426 // behavior.
19427 break;
19428
19429 case OdrUseContext::Used:
19430 // If we might later find that this expression isn't actually an odr-use,
19431 // delay the marking.
19432 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19433 SemaRef.MaybeODRUseExprs.insert(E);
19434 else
19435 MarkVarDeclODRUsed(Var, Loc, SemaRef);
19436 break;
19437
19438 case OdrUseContext::Dependent:
19439 // If this is a dependent context, we don't need to mark variables as
19440 // odr-used, but we may still need to track them for lambda capture.
19441 // FIXME: Do we also need to do this inside dependent typeid expressions
19442 // (which are modeled as unevaluated at this point)?
19443 const bool RefersToEnclosingScope =
19444 (SemaRef.CurContext != Var->getDeclContext() &&
19445 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
19446 if (RefersToEnclosingScope) {
19447 LambdaScopeInfo *const LSI =
19448 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19449 if (LSI && (!LSI->CallOperator ||
19450 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19451 // If a variable could potentially be odr-used, defer marking it so
19452 // until we finish analyzing the full expression for any
19453 // lvalue-to-rvalue
19454 // or discarded value conversions that would obviate odr-use.
19455 // Add it to the list of potential captures that will be analyzed
19456 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19457 // unless the variable is a reference that was initialized by a constant
19458 // expression (this will never need to be captured or odr-used).
19459 //
19460 // FIXME: We can simplify this a lot after implementing P0588R1.
19461 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", 19461, __extension__ __PRETTY_FUNCTION__
))
;
19462 if (!Var->getType()->isReferenceType() ||
19463 !Var->isUsableInConstantExpressions(SemaRef.Context))
19464 LSI->addPotentialCapture(E->IgnoreParens());
19465 }
19466 }
19467 break;
19468 }
19469}
19470
19471/// Mark a variable referenced, and check whether it is odr-used
19472/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
19473/// used directly for normal expressions referring to VarDecl.
19474void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
19475 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19476}
19477
19478static void
19479MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
19480 bool MightBeOdrUse,
19481 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19482 if (SemaRef.isInOpenMPDeclareTargetContext())
19483 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
19484
19485 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19486 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
19487 return;
19488 }
19489
19490 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19491
19492 // If this is a call to a method via a cast, also mark the method in the
19493 // derived class used in case codegen can devirtualize the call.
19494 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19495 if (!ME)
19496 return;
19497 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19498 if (!MD)
19499 return;
19500 // Only attempt to devirtualize if this is truly a virtual call.
19501 bool IsVirtualCall = MD->isVirtual() &&
19502 ME->performsVirtualDispatch(SemaRef.getLangOpts());
19503 if (!IsVirtualCall)
19504 return;
19505
19506 // If it's possible to devirtualize the call, mark the called function
19507 // referenced.
19508 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
19509 ME->getBase(), SemaRef.getLangOpts().AppleKext);
19510 if (DM)
19511 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19512}
19513
19514/// Perform reference-marking and odr-use handling for a DeclRefExpr.
19515///
19516/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19517/// handled with care if the DeclRefExpr is not newly-created.
19518void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
19519 // TODO: update this with DR# once a defect report is filed.
19520 // C++11 defect. The address of a pure member should not be an ODR use, even
19521 // if it's a qualified reference.
19522 bool OdrUse = true;
19523 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19524 if (Method->isVirtual() &&
19525 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19526 OdrUse = false;
19527
19528 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
19529 if (!isUnevaluatedContext() && !isConstantEvaluated() &&
19530 FD->isConsteval() && !RebuildingImmediateInvocation)
19531 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19532 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19533 RefsMinusAssignments);
19534}
19535
19536/// Perform reference-marking and odr-use handling for a MemberExpr.
19537void Sema::MarkMemberReferenced(MemberExpr *E) {
19538 // C++11 [basic.def.odr]p2:
19539 // A non-overloaded function whose name appears as a potentially-evaluated
19540 // expression or a member of a set of candidate functions, if selected by
19541 // overload resolution when referred to from a potentially-evaluated
19542 // expression, is odr-used, unless it is a pure virtual function and its
19543 // name is not explicitly qualified.
19544 bool MightBeOdrUse = true;
19545 if (E->performsVirtualDispatch(getLangOpts())) {
19546 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19547 if (Method->isPure())
19548 MightBeOdrUse = false;
19549 }
19550 SourceLocation Loc =
19551 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19552 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19553 RefsMinusAssignments);
19554}
19555
19556/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
19557void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
19558 for (VarDecl *VD : *E)
19559 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19560 RefsMinusAssignments);
19561}
19562
19563/// Perform marking for a reference to an arbitrary declaration. It
19564/// marks the declaration referenced, and performs odr-use checking for
19565/// functions and variables. This method should not be used when building a
19566/// normal expression which refers to a variable.
19567void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
19568 bool MightBeOdrUse) {
19569 if (MightBeOdrUse) {
19570 if (auto *VD = dyn_cast<VarDecl>(D)) {
19571 MarkVariableReferenced(Loc, VD);
19572 return;
19573 }
19574 }
19575 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19576 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19577 return;
19578 }
19579 D->setReferenced();
19580}
19581
19582namespace {
19583 // Mark all of the declarations used by a type as referenced.
19584 // FIXME: Not fully implemented yet! We need to have a better understanding
19585 // of when we're entering a context we should not recurse into.
19586 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19587 // TreeTransforms rebuilding the type in a new context. Rather than
19588 // duplicating the TreeTransform logic, we should consider reusing it here.
19589 // Currently that causes problems when rebuilding LambdaExprs.
19590 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19591 Sema &S;
19592 SourceLocation Loc;
19593
19594 public:
19595 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
19596
19597 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19598
19599 bool TraverseTemplateArgument(const TemplateArgument &Arg);
19600 };
19601}
19602
19603bool MarkReferencedDecls::TraverseTemplateArgument(
19604 const TemplateArgument &Arg) {
19605 {
19606 // A non-type template argument is a constant-evaluated context.
19607 EnterExpressionEvaluationContext Evaluated(
19608 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
19609 if (Arg.getKind() == TemplateArgument::Declaration) {
19610 if (Decl *D = Arg.getAsDecl())
19611 S.MarkAnyDeclReferenced(Loc, D, true);
19612 } else if (Arg.getKind() == TemplateArgument::Expression) {
19613 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
19614 }
19615 }
19616
19617 return Inherited::TraverseTemplateArgument(Arg);
19618}
19619
19620void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
19621 MarkReferencedDecls Marker(*this, Loc);
19622 Marker.TraverseType(T);
19623}
19624
19625namespace {
19626/// Helper class that marks all of the declarations referenced by
19627/// potentially-evaluated subexpressions as "referenced".
19628class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19629public:
19630 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19631 bool SkipLocalVariables;
19632 ArrayRef<const Expr *> StopAt;
19633
19634 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19635 ArrayRef<const Expr *> StopAt)
19636 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19637
19638 void visitUsedDecl(SourceLocation Loc, Decl *D) {
19639 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19640 }
19641
19642 void Visit(Expr *E) {
19643 if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end())
19644 return;
19645 Inherited::Visit(E);
19646 }
19647
19648 void VisitDeclRefExpr(DeclRefExpr *E) {
19649 // If we were asked not to visit local variables, don't.
19650 if (SkipLocalVariables) {
19651 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19652 if (VD->hasLocalStorage())
19653 return;
19654 }
19655
19656 // FIXME: This can trigger the instantiation of the initializer of a
19657 // variable, which can cause the expression to become value-dependent
19658 // or error-dependent. Do we need to propagate the new dependence bits?
19659 S.MarkDeclRefReferenced(E);
19660 }
19661
19662 void VisitMemberExpr(MemberExpr *E) {
19663 S.MarkMemberReferenced(E);
19664 Visit(E->getBase());
19665 }
19666};
19667} // namespace
19668
19669/// Mark any declarations that appear within this expression or any
19670/// potentially-evaluated subexpressions as "referenced".
19671///
19672/// \param SkipLocalVariables If true, don't mark local variables as
19673/// 'referenced'.
19674/// \param StopAt Subexpressions that we shouldn't recurse into.
19675void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
19676 bool SkipLocalVariables,
19677 ArrayRef<const Expr*> StopAt) {
19678 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19679}
19680
19681/// Emit a diagnostic when statements are reachable.
19682/// FIXME: check for reachability even in expressions for which we don't build a
19683/// CFG (eg, in the initializer of a global or in a constant expression).
19684/// For example,
19685/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19686bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
19687 const PartialDiagnostic &PD) {
19688 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19689 if (!FunctionScopes.empty())
19690 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19691 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
19692 return true;
19693 }
19694
19695 // The initializer of a constexpr variable or of the first declaration of a
19696 // static data member is not syntactically a constant evaluated constant,
19697 // but nonetheless is always required to be a constant expression, so we
19698 // can skip diagnosing.
19699 // FIXME: Using the mangling context here is a hack.
19700 if (auto *VD = dyn_cast_or_null<VarDecl>(
19701 ExprEvalContexts.back().ManglingContextDecl)) {
19702 if (VD->isConstexpr() ||
19703 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19704 return false;
19705 // FIXME: For any other kind of variable, we should build a CFG for its
19706 // initializer and check whether the context in question is reachable.
19707 }
19708
19709 Diag(Loc, PD);
19710 return true;
19711}
19712
19713/// Emit a diagnostic that describes an effect on the run-time behavior
19714/// of the program being compiled.
19715///
19716/// This routine emits the given diagnostic when the code currently being
19717/// type-checked is "potentially evaluated", meaning that there is a
19718/// possibility that the code will actually be executable. Code in sizeof()
19719/// expressions, code used only during overload resolution, etc., are not
19720/// potentially evaluated. This routine will suppress such diagnostics or,
19721/// in the absolutely nutty case of potentially potentially evaluated
19722/// expressions (C++ typeid), queue the diagnostic to potentially emit it
19723/// later.
19724///
19725/// This routine should be used for all diagnostics that describe the run-time
19726/// behavior of a program, such as passing a non-POD value through an ellipsis.
19727/// Failure to do so will likely result in spurious diagnostics or failures
19728/// during overload resolution or within sizeof/alignof/typeof/typeid.
19729bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19730 const PartialDiagnostic &PD) {
19731
19732 if (ExprEvalContexts.back().isDiscardedStatementContext())
19733 return false;
19734
19735 switch (ExprEvalContexts.back().Context) {
19736 case ExpressionEvaluationContext::Unevaluated:
19737 case ExpressionEvaluationContext::UnevaluatedList:
19738 case ExpressionEvaluationContext::UnevaluatedAbstract:
19739 case ExpressionEvaluationContext::DiscardedStatement:
19740 // The argument will never be evaluated, so don't complain.
19741 break;
19742
19743 case ExpressionEvaluationContext::ConstantEvaluated:
19744 case ExpressionEvaluationContext::ImmediateFunctionContext:
19745 // Relevant diagnostics should be produced by constant evaluation.
19746 break;
19747
19748 case ExpressionEvaluationContext::PotentiallyEvaluated:
19749 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19750 return DiagIfReachable(Loc, Stmts, PD);
19751 }
19752
19753 return false;
19754}
19755
19756bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19757 const PartialDiagnostic &PD) {
19758 return DiagRuntimeBehavior(
19759 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
19760}
19761
19762bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19763 CallExpr *CE, FunctionDecl *FD) {
19764 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19765 return false;
19766
19767 // If we're inside a decltype's expression, don't check for a valid return
19768 // type or construct temporaries until we know whether this is the last call.
19769 if (ExprEvalContexts.back().ExprContext ==
19770 ExpressionEvaluationContextRecord::EK_Decltype) {
19771 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19772 return false;
19773 }
19774
19775 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19776 FunctionDecl *FD;
19777 CallExpr *CE;
19778
19779 public:
19780 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19781 : FD(FD), CE(CE) { }
19782
19783 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19784 if (!FD) {
19785 S.Diag(Loc, diag::err_call_incomplete_return)
19786 << T << CE->getSourceRange();
19787 return;
19788 }
19789
19790 S.Diag(Loc, diag::err_call_function_incomplete_return)
19791 << CE->getSourceRange() << FD << T;
19792 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19793 << FD->getDeclName();
19794 }
19795 } Diagnoser(FD, CE);
19796
19797 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19798 return true;
19799
19800 return false;
19801}
19802
19803// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19804// will prevent this condition from triggering, which is what we want.
19805void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19806 SourceLocation Loc;
19807
19808 unsigned diagnostic = diag::warn_condition_is_assignment;
19809 bool IsOrAssign = false;
19810
19811 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19812 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19813 return;
19814
19815 IsOrAssign = Op->getOpcode() == BO_OrAssign;
19816
19817 // Greylist some idioms by putting them into a warning subcategory.
19818 if (ObjCMessageExpr *ME
19819 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19820 Selector Sel = ME->getSelector();
19821
19822 // self = [<foo> init...]
19823 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19824 diagnostic = diag::warn_condition_is_idiomatic_assignment;
19825
19826 // <foo> = [<bar> nextObject]
19827 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19828 diagnostic = diag::warn_condition_is_idiomatic_assignment;
19829 }
19830
19831 Loc = Op->getOperatorLoc();
19832 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19833 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19834 return;
19835
19836 IsOrAssign = Op->getOperator() == OO_PipeEqual;
19837 Loc = Op->getOperatorLoc();
19838 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19839 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19840 else {
19841 // Not an assignment.
19842 return;
19843 }
19844
19845 Diag(Loc, diagnostic) << E->getSourceRange();
19846
19847 SourceLocation Open = E->getBeginLoc();
19848 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19849 Diag(Loc, diag::note_condition_assign_silence)
19850 << FixItHint::CreateInsertion(Open, "(")
19851 << FixItHint::CreateInsertion(Close, ")");
19852
19853 if (IsOrAssign)
19854 Diag(Loc, diag::note_condition_or_assign_to_comparison)
19855 << FixItHint::CreateReplacement(Loc, "!=");
19856 else
19857 Diag(Loc, diag::note_condition_assign_to_comparison)
19858 << FixItHint::CreateReplacement(Loc, "==");
19859}
19860
19861/// Redundant parentheses over an equality comparison can indicate
19862/// that the user intended an assignment used as condition.
19863void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19864 // Don't warn if the parens came from a macro.
19865 SourceLocation parenLoc = ParenE->getBeginLoc();
19866 if (parenLoc.isInvalid() || parenLoc.isMacroID())
19867 return;
19868 // Don't warn for dependent expressions.
19869 if (ParenE->isTypeDependent())
19870 return;
19871
19872 Expr *E = ParenE->IgnoreParens();
19873
19874 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19875 if (opE->getOpcode() == BO_EQ &&
19876 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19877 == Expr::MLV_Valid) {
19878 SourceLocation Loc = opE->getOperatorLoc();
19879
19880 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19881 SourceRange ParenERange = ParenE->getSourceRange();
19882 Diag(Loc, diag::note_equality_comparison_silence)
19883 << FixItHint::CreateRemoval(ParenERange.getBegin())
19884 << FixItHint::CreateRemoval(ParenERange.getEnd());
19885 Diag(Loc, diag::note_equality_comparison_to_assign)
19886 << FixItHint::CreateReplacement(Loc, "=");
19887 }
19888}
19889
19890ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19891 bool IsConstexpr) {
19892 DiagnoseAssignmentAsCondition(E);
19893 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19894 DiagnoseEqualityWithExtraParens(parenE);
19895
19896 ExprResult result = CheckPlaceholderExpr(E);
19897 if (result.isInvalid()) return ExprError();
19898 E = result.get();
19899
19900 if (!E->isTypeDependent()) {
19901 if (getLangOpts().CPlusPlus)
19902 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19903
19904 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19905 if (ERes.isInvalid())
19906 return ExprError();
19907 E = ERes.get();
19908
19909 QualType T = E->getType();
19910 if (!T->isScalarType()) { // C99 6.8.4.1p1
19911 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19912 << T << E->getSourceRange();
19913 return ExprError();
19914 }
19915 CheckBoolLikeConversion(E, Loc);
19916 }
19917
19918 return E;
19919}
19920
19921Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19922 Expr *SubExpr, ConditionKind CK,
19923 bool MissingOK) {
19924 // MissingOK indicates whether having no condition expression is valid
19925 // (for loop) or invalid (e.g. while loop).
19926 if (!SubExpr)
19927 return MissingOK ? ConditionResult() : ConditionError();
19928
19929 ExprResult Cond;
19930 switch (CK) {
19931 case ConditionKind::Boolean:
19932 Cond = CheckBooleanCondition(Loc, SubExpr);
19933 break;
19934
19935 case ConditionKind::ConstexprIf:
19936 Cond = CheckBooleanCondition(Loc, SubExpr, true);
19937 break;
19938
19939 case ConditionKind::Switch:
19940 Cond = CheckSwitchCondition(Loc, SubExpr);
19941 break;
19942 }
19943 if (Cond.isInvalid()) {
19944 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19945 {SubExpr}, PreferredConditionType(CK));
19946 if (!Cond.get())
19947 return ConditionError();
19948 }
19949 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19950 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19951 if (!FullExpr.get())
19952 return ConditionError();
19953
19954 return ConditionResult(*this, nullptr, FullExpr,
19955 CK == ConditionKind::ConstexprIf);
19956}
19957
19958namespace {
19959 /// A visitor for rebuilding a call to an __unknown_any expression
19960 /// to have an appropriate type.
19961 struct RebuildUnknownAnyFunction
19962 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19963
19964 Sema &S;
19965
19966 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19967
19968 ExprResult VisitStmt(Stmt *S) {
19969 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp"
, 19969)
;
19970 }
19971
19972 ExprResult VisitExpr(Expr *E) {
19973 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19974 << E->getSourceRange();
19975 return ExprError();
19976 }
19977
19978 /// Rebuild an expression which simply semantically wraps another
19979 /// expression which it shares the type and value kind of.
19980 template <class T> ExprResult rebuildSugarExpr(T *E) {
19981 ExprResult SubResult = Visit(E->getSubExpr());
19982 if (SubResult.isInvalid()) return ExprError();
19983
19984 Expr *SubExpr = SubResult.get();
19985 E->setSubExpr(SubExpr);
19986 E->setType(SubExpr->getType());
19987 E->setValueKind(SubExpr->getValueKind());
19988 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", 19988, __extension__ __PRETTY_FUNCTION__
))
;
19989 return E;
19990 }
19991
19992 ExprResult VisitParenExpr(ParenExpr *E) {
19993 return rebuildSugarExpr(E);
19994 }
19995
19996 ExprResult VisitUnaryExtension(UnaryOperator *E) {
19997 return rebuildSugarExpr(E);
19998 }
19999
20000 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20001 ExprResult SubResult = Visit(E->getSubExpr());
20002 if (SubResult.isInvalid()) return ExprError();
20003
20004 Expr *SubExpr = SubResult.get();
20005 E->setSubExpr(SubExpr);
20006 E->setType(S.Context.getPointerType(SubExpr->getType()));
20007 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20007, __extension__
__PRETTY_FUNCTION__))
;
20008 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", 20008, __extension__ __PRETTY_FUNCTION__
))
;
20009 return E;
20010 }
20011
20012 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20013 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20014
20015 E->setType(VD->getType());
20016
20017 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20017, __extension__
__PRETTY_FUNCTION__))
;
20018 if (S.getLangOpts().CPlusPlus &&
20019 !(isa<CXXMethodDecl>(VD) &&
20020 cast<CXXMethodDecl>(VD)->isInstance()))
20021 E->setValueKind(VK_LValue);
20022
20023 return E;
20024 }
20025
20026 ExprResult VisitMemberExpr(MemberExpr *E) {
20027 return resolveDecl(E, E->getMemberDecl());
20028 }
20029
20030 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20031 return resolveDecl(E, E->getDecl());
20032 }
20033 };
20034}
20035
20036/// Given a function expression of unknown-any type, try to rebuild it
20037/// to have a function type.
20038static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
20039 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20040 if (Result.isInvalid()) return ExprError();
20041 return S.DefaultFunctionArrayConversion(Result.get());
20042}
20043
20044namespace {
20045 /// A visitor for rebuilding an expression of type __unknown_anytype
20046 /// into one which resolves the type directly on the referring
20047 /// expression. Strict preservation of the original source
20048 /// structure is not a goal.
20049 struct RebuildUnknownAnyExpr
20050 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20051
20052 Sema &S;
20053
20054 /// The current destination type.
20055 QualType DestType;
20056
20057 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20058 : S(S), DestType(CastType) {}
20059
20060 ExprResult VisitStmt(Stmt *S) {
20061 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp"
, 20061)
;
20062 }
20063
20064 ExprResult VisitExpr(Expr *E) {
20065 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20066 << E->getSourceRange();
20067 return ExprError();
20068 }
20069
20070 ExprResult VisitCallExpr(CallExpr *E);
20071 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20072
20073 /// Rebuild an expression which simply semantically wraps another
20074 /// expression which it shares the type and value kind of.
20075 template <class T> ExprResult rebuildSugarExpr(T *E) {
20076 ExprResult SubResult = Visit(E->getSubExpr());
20077 if (SubResult.isInvalid()) return ExprError();
20078 Expr *SubExpr = SubResult.get();
20079 E->setSubExpr(SubExpr);
20080 E->setType(SubExpr->getType());
20081 E->setValueKind(SubExpr->getValueKind());
20082 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", 20082, __extension__ __PRETTY_FUNCTION__
))
;
20083 return E;
20084 }
20085
20086 ExprResult VisitParenExpr(ParenExpr *E) {
20087 return rebuildSugarExpr(E);
20088 }
20089
20090 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20091 return rebuildSugarExpr(E);
20092 }
20093
20094 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20095 const PointerType *Ptr = DestType->getAs<PointerType>();
20096 if (!Ptr) {
20097 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20098 << E->getSourceRange();
20099 return ExprError();
20100 }
20101
20102 if (isa<CallExpr>(E->getSubExpr())) {
20103 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20104 << E->getSourceRange();
20105 return ExprError();
20106 }
20107
20108 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20108, __extension__
__PRETTY_FUNCTION__))
;
20109 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", 20109, __extension__ __PRETTY_FUNCTION__
))
;
20110 E->setType(DestType);
20111
20112 // Build the sub-expression as if it were an object of the pointee type.
20113 DestType = Ptr->getPointeeType();
20114 ExprResult SubResult = Visit(E->getSubExpr());
20115 if (SubResult.isInvalid()) return ExprError();
20116 E->setSubExpr(SubResult.get());
20117 return E;
20118 }
20119
20120 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20121
20122 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20123
20124 ExprResult VisitMemberExpr(MemberExpr *E) {
20125 return resolveDecl(E, E->getMemberDecl());
20126 }
20127
20128 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20129 return resolveDecl(E, E->getDecl());
20130 }
20131 };
20132}
20133
20134/// Rebuilds a call expression which yielded __unknown_anytype.
20135ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20136 Expr *CalleeExpr = E->getCallee();
20137
20138 enum FnKind {
20139 FK_MemberFunction,
20140 FK_FunctionPointer,
20141 FK_BlockPointer
20142 };
20143
20144 FnKind Kind;
20145 QualType CalleeType = CalleeExpr->getType();
20146 if (CalleeType == S.Context.BoundMemberTy) {
20147 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", 20147, __extension__ __PRETTY_FUNCTION__
))
;
20148 Kind = FK_MemberFunction;
20149 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20150 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20151 CalleeType = Ptr->getPointeeType();
20152 Kind = FK_FunctionPointer;
20153 } else {
20154 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20155 Kind = FK_BlockPointer;
20156 }
20157 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20158
20159 // Verify that this is a legal result type of a function.
20160 if (DestType->isArrayType() || DestType->isFunctionType()) {
20161 unsigned diagID = diag::err_func_returning_array_function;
20162 if (Kind == FK_BlockPointer)
20163 diagID = diag::err_block_returning_array_function;
20164
20165 S.Diag(E->getExprLoc(), diagID)
20166 << DestType->isFunctionType() << DestType;
20167 return ExprError();
20168 }
20169
20170 // Otherwise, go ahead and set DestType as the call's result.
20171 E->setType(DestType.getNonLValueExprType(S.Context));
20172 E->setValueKind(Expr::getValueKindForType(DestType));
20173 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", 20173, __extension__ __PRETTY_FUNCTION__
))
;
20174
20175 // Rebuild the function type, replacing the result type with DestType.
20176 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20177 if (Proto) {
20178 // __unknown_anytype(...) is a special case used by the debugger when
20179 // it has no idea what a function's signature is.
20180 //
20181 // We want to build this call essentially under the K&R
20182 // unprototyped rules, but making a FunctionNoProtoType in C++
20183 // would foul up all sorts of assumptions. However, we cannot
20184 // simply pass all arguments as variadic arguments, nor can we
20185 // portably just call the function under a non-variadic type; see
20186 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20187 // However, it turns out that in practice it is generally safe to
20188 // call a function declared as "A foo(B,C,D);" under the prototype
20189 // "A foo(B,C,D,...);". The only known exception is with the
20190 // Windows ABI, where any variadic function is implicitly cdecl
20191 // regardless of its normal CC. Therefore we change the parameter
20192 // types to match the types of the arguments.
20193 //
20194 // This is a hack, but it is far superior to moving the
20195 // corresponding target-specific code from IR-gen to Sema/AST.
20196
20197 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20198 SmallVector<QualType, 8> ArgTypes;
20199 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20200 ArgTypes.reserve(E->getNumArgs());
20201 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20202 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20203 }
20204 ParamTypes = ArgTypes;
20205 }
20206 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20207 Proto->getExtProtoInfo());
20208 } else {
20209 DestType = S.Context.getFunctionNoProtoType(DestType,
20210 FnType->getExtInfo());
20211 }
20212
20213 // Rebuild the appropriate pointer-to-function type.
20214 switch (Kind) {
20215 case FK_MemberFunction:
20216 // Nothing to do.
20217 break;
20218
20219 case FK_FunctionPointer:
20220 DestType = S.Context.getPointerType(DestType);
20221 break;
20222
20223 case FK_BlockPointer:
20224 DestType = S.Context.getBlockPointerType(DestType);
20225 break;
20226 }
20227
20228 // Finally, we can recurse.
20229 ExprResult CalleeResult = Visit(CalleeExpr);
20230 if (!CalleeResult.isUsable()) return ExprError();
20231 E->setCallee(CalleeResult.get());
20232
20233 // Bind a temporary if necessary.
20234 return S.MaybeBindToTemporary(E);
20235}
20236
20237ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20238 // Verify that this is a legal result type of a call.
20239 if (DestType->isArrayType() || DestType->isFunctionType()) {
20240 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20241 << DestType->isFunctionType() << DestType;
20242 return ExprError();
20243 }
20244
20245 // Rewrite the method result type if available.
20246 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20247 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", 20247, __extension__ __PRETTY_FUNCTION__
))
;
20248 Method->setReturnType(DestType);
20249 }
20250
20251 // Change the type of the message.
20252 E->setType(DestType.getNonReferenceType());
20253 E->setValueKind(Expr::getValueKindForType(DestType));
20254
20255 return S.MaybeBindToTemporary(E);
20256}
20257
20258ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20259 // The only case we should ever see here is a function-to-pointer decay.
20260 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20261 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20261, __extension__
__PRETTY_FUNCTION__))
;
20262 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", 20262, __extension__ __PRETTY_FUNCTION__
))
;
20263
20264 E->setType(DestType);
20265
20266 // Rebuild the sub-expression as the pointee (function) type.
20267 DestType = DestType->castAs<PointerType>()->getPointeeType();
20268
20269 ExprResult Result = Visit(E->getSubExpr());
20270 if (!Result.isUsable()) return ExprError();
20271
20272 E->setSubExpr(Result.get());
20273 return E;
20274 } else if (E->getCastKind() == CK_LValueToRValue) {
20275 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20275, __extension__
__PRETTY_FUNCTION__))
;
20276 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", 20276, __extension__ __PRETTY_FUNCTION__
))
;
20277
20278 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", 20278, __extension__ __PRETTY_FUNCTION__
))
;
20279
20280 E->setType(DestType);
20281
20282 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20283 DestType = S.Context.getLValueReferenceType(DestType);
20284
20285 ExprResult Result = Visit(E->getSubExpr());
20286 if (!Result.isUsable()) return ExprError();
20287
20288 E->setSubExpr(Result.get());
20289 return E;
20290 } else {
20291 llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "clang/lib/Sema/SemaExpr.cpp"
, 20291)
;
20292 }
20293}
20294
20295ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20296 ExprValueKind ValueKind = VK_LValue;
20297 QualType Type = DestType;
20298
20299 // We know how to make this work for certain kinds of decls:
20300
20301 // - functions
20302 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20303 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20304 DestType = Ptr->getPointeeType();
20305 ExprResult Result = resolveDecl(E, VD);
20306 if (Result.isInvalid()) return ExprError();
20307 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20308 VK_PRValue);
20309 }
20310
20311 if (!Type->isFunctionType()) {
20312 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20313 << VD << E->getSourceRange();
20314 return ExprError();
20315 }
20316 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20317 // We must match the FunctionDecl's type to the hack introduced in
20318 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20319 // type. See the lengthy commentary in that routine.
20320 QualType FDT = FD->getType();
20321 const FunctionType *FnType = FDT->castAs<FunctionType>();
20322 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20323 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20324 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20325 SourceLocation Loc = FD->getLocation();
20326 FunctionDecl *NewFD = FunctionDecl::Create(
20327 S.Context, FD->getDeclContext(), Loc, Loc,
20328 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20329 SC_None, S.getCurFPFeatures().isFPConstrained(),
20330 false /*isInlineSpecified*/, FD->hasPrototype(),
20331 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20332
20333 if (FD->getQualifier())
20334 NewFD->setQualifierInfo(FD->getQualifierLoc());
20335
20336 SmallVector<ParmVarDecl*, 16> Params;
20337 for (const auto &AI : FT->param_types()) {
20338 ParmVarDecl *Param =
20339 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
20340 Param->setScopeInfo(0, Params.size());
20341 Params.push_back(Param);
20342 }
20343 NewFD->setParams(Params);
20344 DRE->setDecl(NewFD);
20345 VD = DRE->getDecl();
20346 }
20347 }
20348
20349 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20350 if (MD->isInstance()) {
20351 ValueKind = VK_PRValue;
20352 Type = S.Context.BoundMemberTy;
20353 }
20354
20355 // Function references aren't l-values in C.
20356 if (!S.getLangOpts().CPlusPlus)
20357 ValueKind = VK_PRValue;
20358
20359 // - variables
20360 } else if (isa<VarDecl>(VD)) {
20361 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20362 Type = RefTy->getPointeeType();
20363 } else if (Type->isFunctionType()) {
20364 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20365 << VD << E->getSourceRange();
20366 return ExprError();
20367 }
20368
20369 // - nothing else
20370 } else {
20371 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20372 << VD << E->getSourceRange();
20373 return ExprError();
20374 }
20375
20376 // Modifying the declaration like this is friendly to IR-gen but
20377 // also really dangerous.
20378 VD->setType(DestType);
20379 E->setType(Type);
20380 E->setValueKind(ValueKind);
20381 return E;
20382}
20383
20384/// Check a cast of an unknown-any type. We intentionally only
20385/// trigger this for C-style casts.
20386ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
20387 Expr *CastExpr, CastKind &CastKind,
20388 ExprValueKind &VK, CXXCastPath &Path) {
20389 // The type we're casting to must be either void or complete.
20390 if (!CastType->isVoidType() &&
20391 RequireCompleteType(TypeRange.getBegin(), CastType,
20392 diag::err_typecheck_cast_to_incomplete))
20393 return ExprError();
20394
20395 // Rewrite the casted expression from scratch.
20396 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20397 if (!result.isUsable()) return ExprError();
20398
20399 CastExpr = result.get();
20400 VK = CastExpr->getValueKind();
20401 CastKind = CK_NoOp;
20402
20403 return CastExpr;
20404}
20405
20406ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
20407 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20408}
20409
20410ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
20411 Expr *arg, QualType &paramType) {
20412 // If the syntactic form of the argument is not an explicit cast of
20413 // any sort, just do default argument promotion.
20414 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20415 if (!castArg) {
20416 ExprResult result = DefaultArgumentPromotion(arg);
20417 if (result.isInvalid()) return ExprError();
20418 paramType = result.get()->getType();
20419 return result;
20420 }
20421
20422 // Otherwise, use the type that was written in the explicit cast.
20423 assert(!arg->hasPlaceholderType())(static_cast <bool> (!arg->hasPlaceholderType()) ? void
(0) : __assert_fail ("!arg->hasPlaceholderType()", "clang/lib/Sema/SemaExpr.cpp"
, 20423, __extension__ __PRETTY_FUNCTION__))
;
20424 paramType = castArg->getTypeAsWritten();
20425
20426 // Copy-initialize a parameter of that type.
20427 InitializedEntity entity =
20428 InitializedEntity::InitializeParameter(Context, paramType,
20429 /*consumed*/ false);
20430 return PerformCopyInitialization(entity, callLoc, arg);
20431}
20432
20433static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
20434 Expr *orig = E;
20435 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20436 while (true) {
20437 E = E->IgnoreParenImpCasts();
20438 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20439 E = call->getCallee();
20440 diagID = diag::err_uncasted_call_of_unknown_any;
20441 } else {
20442 break;
20443 }
20444 }
20445
20446 SourceLocation loc;
20447 NamedDecl *d;
20448 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20449 loc = ref->getLocation();
20450 d = ref->getDecl();
20451 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20452 loc = mem->getMemberLoc();
20453 d = mem->getMemberDecl();
20454 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20455 diagID = diag::err_uncasted_call_of_unknown_any;
20456 loc = msg->getSelectorStartLoc();
20457 d = msg->getMethodDecl();
20458 if (!d) {
20459 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20460 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20461 << orig->getSourceRange();
20462 return ExprError();
20463 }
20464 } else {
20465 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20466 << E->getSourceRange();
20467 return ExprError();
20468 }
20469
20470 S.Diag(loc, diagID) << d << orig->getSourceRange();
20471
20472 // Never recoverable.
20473 return ExprError();
20474}
20475
20476/// Check for operands with placeholder types and complain if found.
20477/// Returns ExprError() if there was an error and no recovery was possible.
20478ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
20479 if (!Context.isDependenceAllowed()) {
20480 // C cannot handle TypoExpr nodes on either side of a binop because it
20481 // doesn't handle dependent types properly, so make sure any TypoExprs have
20482 // been dealt with before checking the operands.
20483 ExprResult Result = CorrectDelayedTyposInExpr(E);
20484 if (!Result.isUsable()) return ExprError();
20485 E = Result.get();
20486 }
20487
20488 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20489 if (!placeholderType) return E;
20490
20491 switch (placeholderType->getKind()) {
20492
20493 // Overloaded expressions.
20494 case BuiltinType::Overload: {
20495 // Try to resolve a single function template specialization.
20496 // This is obligatory.
20497 ExprResult Result = E;
20498 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
20499 return Result;
20500
20501 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20502 // leaves Result unchanged on failure.
20503 Result = E;
20504 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
20505 return Result;
20506
20507 // If that failed, try to recover with a call.
20508 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20509 /*complain*/ true);
20510 return Result;
20511 }
20512
20513 // Bound member functions.
20514 case BuiltinType::BoundMember: {
20515 ExprResult result = E;
20516 const Expr *BME = E->IgnoreParens();
20517 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20518 // Try to give a nicer diagnostic if it is a bound member that we recognize.
20519 if (isa<CXXPseudoDestructorExpr>(BME)) {
20520 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20521 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20522 if (ME->getMemberNameInfo().getName().getNameKind() ==
20523 DeclarationName::CXXDestructorName)
20524 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20525 }
20526 tryToRecoverWithCall(result, PD,
20527 /*complain*/ true);
20528 return result;
20529 }
20530
20531 // ARC unbridged casts.
20532 case BuiltinType::ARCUnbridgedCast: {
20533 Expr *realCast = stripARCUnbridgedCast(E);
20534 diagnoseARCUnbridgedCast(realCast);
20535 return realCast;
20536 }
20537
20538 // Expressions of unknown type.
20539 case BuiltinType::UnknownAny:
20540 return diagnoseUnknownAnyExpr(*this, E);
20541
20542 // Pseudo-objects.
20543 case BuiltinType::PseudoObject:
20544 return checkPseudoObjectRValue(E);
20545
20546 case BuiltinType::BuiltinFn: {
20547 // Accept __noop without parens by implicitly converting it to a call expr.
20548 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20549 if (DRE) {
20550 auto *FD = cast<FunctionDecl>(DRE->getDecl());
20551 unsigned BuiltinID = FD->getBuiltinID();
20552 if (BuiltinID == Builtin::BI__noop) {
20553 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20554 CK_BuiltinFnToFnPtr)
20555 .get();
20556 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20557 VK_PRValue, SourceLocation(),
20558 FPOptionsOverride());
20559 }
20560
20561 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
20562 // Any use of these other than a direct call is ill-formed as of C++20,
20563 // because they are not addressable functions. In earlier language
20564 // modes, warn and force an instantiation of the real body.
20565 Diag(E->getBeginLoc(),
20566 getLangOpts().CPlusPlus20
20567 ? diag::err_use_of_unaddressable_function
20568 : diag::warn_cxx20_compat_use_of_unaddressable_function);
20569 if (FD->isImplicitlyInstantiable()) {
20570 // Require a definition here because a normal attempt at
20571 // instantiation for a builtin will be ignored, and we won't try
20572 // again later. We assume that the definition of the template
20573 // precedes this use.
20574 InstantiateFunctionDefinition(E->getBeginLoc(), FD,
20575 /*Recursive=*/false,
20576 /*DefinitionRequired=*/true,
20577 /*AtEndOfTU=*/false);
20578 }
20579 // Produce a properly-typed reference to the function.
20580 CXXScopeSpec SS;
20581 SS.Adopt(DRE->getQualifierLoc());
20582 TemplateArgumentListInfo TemplateArgs;
20583 DRE->copyTemplateArgumentsInto(TemplateArgs);
20584 return BuildDeclRefExpr(
20585 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
20586 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
20587 DRE->getTemplateKeywordLoc(),
20588 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
20589 }
20590 }
20591
20592 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20593 return ExprError();
20594 }
20595
20596 case BuiltinType::IncompleteMatrixIdx:
20597 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20598 ->getRowIdx()
20599 ->getBeginLoc(),
20600 diag::err_matrix_incomplete_index);
20601 return ExprError();
20602
20603 // Expressions of unknown type.
20604 case BuiltinType::OMPArraySection:
20605 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
20606 return ExprError();
20607
20608 // Expressions of unknown type.
20609 case BuiltinType::OMPArrayShaping:
20610 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20611
20612 case BuiltinType::OMPIterator:
20613 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20614
20615 // Everything else should be impossible.
20616#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20617 case BuiltinType::Id:
20618#include "clang/Basic/OpenCLImageTypes.def"
20619#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20620 case BuiltinType::Id:
20621#include "clang/Basic/OpenCLExtensionTypes.def"
20622#define SVE_TYPE(Name, Id, SingletonId) \
20623 case BuiltinType::Id:
20624#include "clang/Basic/AArch64SVEACLETypes.def"
20625#define PPC_VECTOR_TYPE(Name, Id, Size) \
20626 case BuiltinType::Id:
20627#include "clang/Basic/PPCTypes.def"
20628#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20629#include "clang/Basic/RISCVVTypes.def"
20630#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20631#define PLACEHOLDER_TYPE(Id, SingletonId)
20632#include "clang/AST/BuiltinTypes.def"
20633 break;
20634 }
20635
20636 llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!"
, "clang/lib/Sema/SemaExpr.cpp", 20636)
;
20637}
20638
20639bool Sema::CheckCaseExpression(Expr *E) {
20640 if (E->isTypeDependent())
20641 return true;
20642 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
20643 return E->getType()->isIntegralOrEnumerationType();
20644 return false;
20645}
20646
20647/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
20648ExprResult
20649Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
20650 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", 20651, __extension__ __PRETTY_FUNCTION__
))
20651 "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", 20651, __extension__ __PRETTY_FUNCTION__
))
;
20652 QualType BoolT = Context.ObjCBuiltinBoolTy;
20653 if (!Context.getBOOLDecl()) {
20654 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
20655 Sema::LookupOrdinaryName);
20656 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
20657 NamedDecl *ND = Result.getFoundDecl();
20658 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
20659 Context.setBOOLDecl(TD);
20660 }
20661 }
20662 if (Context.getBOOLDecl())
20663 BoolT = Context.getBOOLType();
20664 return new (Context)
20665 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
20666}
20667
20668ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
20669 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
20670 SourceLocation RParen) {
20671 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
20672 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20673 return Spec.getPlatform() == Platform;
20674 });
20675 // Transcribe the "ios" availability check to "maccatalyst" when compiling
20676 // for "maccatalyst" if "maccatalyst" is not specified.
20677 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
20678 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20679 return Spec.getPlatform() == "ios";
20680 });
20681 }
20682 if (Spec == AvailSpecs.end())
20683 return None;
20684 return Spec->getVersion();
20685 };
20686
20687 VersionTuple Version;
20688 if (auto MaybeVersion =
20689 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
20690 Version = *MaybeVersion;
20691
20692 // The use of `@available` in the enclosing context should be analyzed to
20693 // warn when it's used inappropriately (i.e. not if(@available)).
20694 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
20695 Context->HasPotentialAvailabilityViolations = true;
20696
20697 return new (Context)
20698 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
20699}
20700
20701ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
20702 ArrayRef<Expr *> SubExprs, QualType T) {
20703 if (!Context.getLangOpts().RecoveryAST)
20704 return ExprError();
20705
20706 if (isSFINAEContext())
20707 return ExprError();
20708
20709 if (T.isNull() || T->isUndeducedType() ||
20710 !Context.getLangOpts().RecoveryASTType)
20711 // We don't know the concrete type, fallback to dependent type.
20712 T = Context.DependentTy;
20713
20714 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20715}

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/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/ExprConcepts.h"
23#include "clang/AST/ExprCXX.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/Lookup.h"
35#include "clang/Sema/Ownership.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "clang/Sema/SemaDiagnostic.h"
39#include "clang/Sema/SemaInternal.h"
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/Support/ErrorHandling.h"
42#include <algorithm>
43
44using namespace llvm::omp;
45
46namespace clang {
47using namespace sema;
48
49/// A semantic tree transformation that allows one to transform one
50/// abstract syntax tree into another.
51///
52/// A new tree transformation is defined by creating a new subclass \c X of
53/// \c TreeTransform<X> and then overriding certain operations to provide
54/// behavior specific to that transformation. For example, template
55/// instantiation is implemented as a tree transformation where the
56/// transformation of TemplateTypeParmType nodes involves substituting the
57/// template arguments for their corresponding template parameters; a similar
58/// transformation is performed for non-type template parameters and
59/// template template parameters.
60///
61/// This tree-transformation template uses static polymorphism to allow
62/// subclasses to customize any of its operations. Thus, a subclass can
63/// override any of the transformation or rebuild operators by providing an
64/// operation with the same signature as the default implementation. The
65/// overriding function should not be virtual.
66///
67/// Semantic tree transformations are split into two stages, either of which
68/// can be replaced by a subclass. The "transform" step transforms an AST node
69/// or the parts of an AST node using the various transformation functions,
70/// then passes the pieces on to the "rebuild" step, which constructs a new AST
71/// node of the appropriate kind from the pieces. The default transformation
72/// routines recursively transform the operands to composite AST nodes (e.g.,
73/// the pointee type of a PointerType node) and, if any of those operand nodes
74/// were changed by the transformation, invokes the rebuild operation to create
75/// a new AST node.
76///
77/// Subclasses can customize the transformation at various levels. The
78/// most coarse-grained transformations involve replacing TransformType(),
79/// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
80/// TransformTemplateName(), or TransformTemplateArgument() with entirely
81/// new implementations.
82///
83/// For more fine-grained transformations, subclasses can replace any of the
84/// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
85/// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
86/// replacing TransformTemplateTypeParmType() allows template instantiation
87/// to substitute template arguments for their corresponding template
88/// parameters. Additionally, subclasses can override the \c RebuildXXX
89/// functions to control how AST nodes are rebuilt when their operands change.
90/// By default, \c TreeTransform will invoke semantic analysis to rebuild
91/// AST nodes. However, certain other tree transformations (e.g, cloning) may
92/// be able to use more efficient rebuild steps.
93///
94/// There are a handful of other functions that can be overridden, allowing one
95/// to avoid traversing nodes that don't need any transformation
96/// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
97/// operands have not changed (\c AlwaysRebuild()), and customize the
98/// default locations and entity names used for type-checking
99/// (\c getBaseLocation(), \c getBaseEntity()).
100template<typename Derived>
101class TreeTransform {
102 /// Private RAII object that helps us forget and then re-remember
103 /// the template argument corresponding to a partially-substituted parameter
104 /// pack.
105 class ForgetPartiallySubstitutedPackRAII {
106 Derived &Self;
107 TemplateArgument Old;
108
109 public:
110 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
111 Old = Self.ForgetPartiallySubstitutedPack();
112 }
113
114 ~ForgetPartiallySubstitutedPackRAII() {
115 Self.RememberPartiallySubstitutedPack(Old);
116 }
117 };
118
119protected:
120 Sema &SemaRef;
121
122 /// The set of local declarations that have been transformed, for
123 /// cases where we are forced to build new declarations within the transformer
124 /// rather than in the subclass (e.g., lambda closure types).
125 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
126
127public:
128 /// Initializes a new tree transformer.
129 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
130
131 /// Retrieves a reference to the derived class.
132 Derived &getDerived() { return static_cast<Derived&>(*this); }
133
134 /// Retrieves a reference to the derived class.
135 const Derived &getDerived() const {
136 return static_cast<const Derived&>(*this);
137 }
138
139 static inline ExprResult Owned(Expr *E) { return E; }
140 static inline StmtResult Owned(Stmt *S) { return S; }
141
142 /// Retrieves a reference to the semantic analysis object used for
143 /// this tree transform.
144 Sema &getSema() const { return SemaRef; }
145
146 /// Whether the transformation should always rebuild AST nodes, even
147 /// if none of the children have changed.
148 ///
149 /// Subclasses may override this function to specify when the transformation
150 /// should rebuild all AST nodes.
151 ///
152 /// We must always rebuild all AST nodes when performing variadic template
153 /// pack expansion, in order to avoid violating the AST invariant that each
154 /// statement node appears at most once in its containing declaration.
155 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
156
157 /// Whether the transformation is forming an expression or statement that
158 /// replaces the original. In this case, we'll reuse mangling numbers from
159 /// existing lambdas.
160 bool ReplacingOriginal() { return false; }
161
162 /// Wether CXXConstructExpr can be skipped when they are implicit.
163 /// They will be reconstructed when used if needed.
164 /// This is useful when the user that cause rebuilding of the
165 /// CXXConstructExpr is outside of the expression at which the TreeTransform
166 /// started.
167 bool AllowSkippingCXXConstructExpr() { return true; }
168
169 /// Returns the location of the entity being transformed, if that
170 /// information was not available elsewhere in the AST.
171 ///
172 /// By default, returns no source-location information. Subclasses can
173 /// provide an alternative implementation that provides better location
174 /// information.
175 SourceLocation getBaseLocation() { return SourceLocation(); }
176
177 /// Returns the name of the entity being transformed, if that
178 /// information was not available elsewhere in the AST.
179 ///
180 /// By default, returns an empty name. Subclasses can provide an alternative
181 /// implementation with a more precise name.
182 DeclarationName getBaseEntity() { return DeclarationName(); }
183
184 /// Sets the "base" location and entity when that
185 /// information is known based on another transformation.
186 ///
187 /// By default, the source location and entity are ignored. Subclasses can
188 /// override this function to provide a customized implementation.
189 void setBase(SourceLocation Loc, DeclarationName Entity) { }
190
191 /// RAII object that temporarily sets the base location and entity
192 /// used for reporting diagnostics in types.
193 class TemporaryBase {
194 TreeTransform &Self;
195 SourceLocation OldLocation;
196 DeclarationName OldEntity;
197
198 public:
199 TemporaryBase(TreeTransform &Self, SourceLocation Location,
200 DeclarationName Entity) : Self(Self) {
201 OldLocation = Self.getDerived().getBaseLocation();
202 OldEntity = Self.getDerived().getBaseEntity();
203
204 if (Location.isValid())
205 Self.getDerived().setBase(Location, Entity);
206 }
207
208 ~TemporaryBase() {
209 Self.getDerived().setBase(OldLocation, OldEntity);
210 }
211 };
212
213 /// Determine whether the given type \p T has already been
214 /// transformed.
215 ///
216 /// Subclasses can provide an alternative implementation of this routine
217 /// to short-circuit evaluation when it is known that a given type will
218 /// not change. For example, template instantiation need not traverse
219 /// non-dependent types.
220 bool AlreadyTransformed(QualType T) {
221 return T.isNull();
222 }
223
224 /// Transform a template parameter depth level.
225 ///
226 /// During a transformation that transforms template parameters, this maps
227 /// an old template parameter depth to a new depth.
228 unsigned TransformTemplateDepth(unsigned Depth) {
229 return Depth;
230 }
231
232 /// Determine whether the given call argument should be dropped, e.g.,
233 /// because it is a default argument.
234 ///
235 /// Subclasses can provide an alternative implementation of this routine to
236 /// determine which kinds of call arguments get dropped. By default,
237 /// CXXDefaultArgument nodes are dropped (prior to transformation).
238 bool DropCallArgument(Expr *E) {
239 return E->isDefaultArgument();
240 }
241
242 /// Determine whether we should expand a pack expansion with the
243 /// given set of parameter packs into separate arguments by repeatedly
244 /// transforming the pattern.
245 ///
246 /// By default, the transformer never tries to expand pack expansions.
247 /// Subclasses can override this routine to provide different behavior.
248 ///
249 /// \param EllipsisLoc The location of the ellipsis that identifies the
250 /// pack expansion.
251 ///
252 /// \param PatternRange The source range that covers the entire pattern of
253 /// the pack expansion.
254 ///
255 /// \param Unexpanded The set of unexpanded parameter packs within the
256 /// pattern.
257 ///
258 /// \param ShouldExpand Will be set to \c true if the transformer should
259 /// expand the corresponding pack expansions into separate arguments. When
260 /// set, \c NumExpansions must also be set.
261 ///
262 /// \param RetainExpansion Whether the caller should add an unexpanded
263 /// pack expansion after all of the expanded arguments. This is used
264 /// when extending explicitly-specified template argument packs per
265 /// C++0x [temp.arg.explicit]p9.
266 ///
267 /// \param NumExpansions The number of separate arguments that will be in
268 /// the expanded form of the corresponding pack expansion. This is both an
269 /// input and an output parameter, which can be set by the caller if the
270 /// number of expansions is known a priori (e.g., due to a prior substitution)
271 /// and will be set by the callee when the number of expansions is known.
272 /// The callee must set this value when \c ShouldExpand is \c true; it may
273 /// set this value in other cases.
274 ///
275 /// \returns true if an error occurred (e.g., because the parameter packs
276 /// are to be instantiated with arguments of different lengths), false
277 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
278 /// must be set.
279 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
280 SourceRange PatternRange,
281 ArrayRef<UnexpandedParameterPack> Unexpanded,
282 bool &ShouldExpand,
283 bool &RetainExpansion,
284 Optional<unsigned> &NumExpansions) {
285 ShouldExpand = false;
286 return false;
287 }
288
289 /// "Forget" about the partially-substituted pack template argument,
290 /// when performing an instantiation that must preserve the parameter pack
291 /// use.
292 ///
293 /// This routine is meant to be overridden by the template instantiator.
294 TemplateArgument ForgetPartiallySubstitutedPack() {
295 return TemplateArgument();
296 }
297
298 /// "Remember" the partially-substituted pack template argument
299 /// after performing an instantiation that must preserve the parameter pack
300 /// use.
301 ///
302 /// This routine is meant to be overridden by the template instantiator.
303 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
304
305 /// Note to the derived class when a function parameter pack is
306 /// being expanded.
307 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
308
309 /// Transforms the given type into another type.
310 ///
311 /// By default, this routine transforms a type by creating a
312 /// TypeSourceInfo for it and delegating to the appropriate
313 /// function. This is expensive, but we don't mind, because
314 /// this method is deprecated anyway; all users should be
315 /// switched to storing TypeSourceInfos.
316 ///
317 /// \returns the transformed type.
318 QualType TransformType(QualType T);
319
320 /// Transforms the given type-with-location into a new
321 /// type-with-location.
322 ///
323 /// By default, this routine transforms a type by delegating to the
324 /// appropriate TransformXXXType to build a new type. Subclasses
325 /// may override this function (to take over all type
326 /// transformations) or some set of the TransformXXXType functions
327 /// to alter the transformation.
328 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
329
330 /// Transform the given type-with-location into a new
331 /// type, collecting location information in the given builder
332 /// as necessary.
333 ///
334 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
335
336 /// Transform a type that is permitted to produce a
337 /// DeducedTemplateSpecializationType.
338 ///
339 /// This is used in the (relatively rare) contexts where it is acceptable
340 /// for transformation to produce a class template type with deduced
341 /// template arguments.
342 /// @{
343 QualType TransformTypeWithDeducedTST(QualType T);
344 TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
345 /// @}
346
347 /// The reason why the value of a statement is not discarded, if any.
348 enum StmtDiscardKind {
349 SDK_Discarded,
350 SDK_NotDiscarded,
351 SDK_StmtExprResult,
352 };
353
354 /// Transform the given statement.
355 ///
356 /// By default, this routine transforms a statement by delegating to the
357 /// appropriate TransformXXXStmt function to transform a specific kind of
358 /// statement or the TransformExpr() function to transform an expression.
359 /// Subclasses may override this function to transform statements using some
360 /// other mechanism.
361 ///
362 /// \returns the transformed statement.
363 StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
364
365 /// Transform the given statement.
366 ///
367 /// By default, this routine transforms a statement by delegating to the
368 /// appropriate TransformOMPXXXClause function to transform a specific kind
369 /// of clause. Subclasses may override this function to transform statements
370 /// using some other mechanism.
371 ///
372 /// \returns the transformed OpenMP clause.
373 OMPClause *TransformOMPClause(OMPClause *S);
374
375 /// Transform the given attribute.
376 ///
377 /// By default, this routine transforms a statement by delegating to the
378 /// appropriate TransformXXXAttr function to transform a specific kind
379 /// of attribute. Subclasses may override this function to transform
380 /// attributed statements using some other mechanism.
381 ///
382 /// \returns the transformed attribute
383 const Attr *TransformAttr(const Attr *S);
384
385/// Transform the specified attribute.
386///
387/// Subclasses should override the transformation of attributes with a pragma
388/// spelling to transform expressions stored within the attribute.
389///
390/// \returns the transformed attribute.
391#define ATTR(X)
392#define PRAGMA_SPELLING_ATTR(X) \
393 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
394#include "clang/Basic/AttrList.inc"
395
396 /// Transform the given expression.
397 ///
398 /// By default, this routine transforms an expression by delegating to the
399 /// appropriate TransformXXXExpr function to build a new expression.
400 /// Subclasses may override this function to transform expressions using some
401 /// other mechanism.
402 ///
403 /// \returns the transformed expression.
404 ExprResult TransformExpr(Expr *E);
405
406 /// Transform the given initializer.
407 ///
408 /// By default, this routine transforms an initializer by stripping off the
409 /// semantic nodes added by initialization, then passing the result to
410 /// TransformExpr or TransformExprs.
411 ///
412 /// \returns the transformed initializer.
413 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
414
415 /// Transform the given list of expressions.
416 ///
417 /// This routine transforms a list of expressions by invoking
418 /// \c TransformExpr() for each subexpression. However, it also provides
419 /// support for variadic templates by expanding any pack expansions (if the
420 /// derived class permits such expansion) along the way. When pack expansions
421 /// are present, the number of outputs may not equal the number of inputs.
422 ///
423 /// \param Inputs The set of expressions to be transformed.
424 ///
425 /// \param NumInputs The number of expressions in \c Inputs.
426 ///
427 /// \param IsCall If \c true, then this transform is being performed on
428 /// function-call arguments, and any arguments that should be dropped, will
429 /// be.
430 ///
431 /// \param Outputs The transformed input expressions will be added to this
432 /// vector.
433 ///
434 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
435 /// due to transformation.
436 ///
437 /// \returns true if an error occurred, false otherwise.
438 bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
439 SmallVectorImpl<Expr *> &Outputs,
440 bool *ArgChanged = nullptr);
441
442 /// Transform the given declaration, which is referenced from a type
443 /// or expression.
444 ///
445 /// By default, acts as the identity function on declarations, unless the
446 /// transformer has had to transform the declaration itself. Subclasses
447 /// may override this function to provide alternate behavior.
448 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
449 llvm::DenseMap<Decl *, Decl *>::iterator Known
450 = TransformedLocalDecls.find(D);
451 if (Known != TransformedLocalDecls.end())
452 return Known->second;
453
454 return D;
455 }
456
457 /// Transform the specified condition.
458 ///
459 /// By default, this transforms the variable and expression and rebuilds
460 /// the condition.
461 Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
462 Expr *Expr,
463 Sema::ConditionKind Kind);
464
465 /// Transform the attributes associated with the given declaration and
466 /// place them on the new declaration.
467 ///
468 /// By default, this operation does nothing. Subclasses may override this
469 /// behavior to transform attributes.
470 void transformAttrs(Decl *Old, Decl *New) { }
471
472 /// Note that a local declaration has been transformed by this
473 /// transformer.
474 ///
475 /// Local declarations are typically transformed via a call to
476 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
477 /// the transformer itself has to transform the declarations. This routine
478 /// can be overridden by a subclass that keeps track of such mappings.
479 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
480 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", 481, __extension__ __PRETTY_FUNCTION__
))
481 "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", 481, __extension__ __PRETTY_FUNCTION__
))
;
482 TransformedLocalDecls[Old] = New.front();
483 }
484
485 /// Transform the definition of the given declaration.
486 ///
487 /// By default, invokes TransformDecl() to transform the declaration.
488 /// Subclasses may override this function to provide alternate behavior.
489 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
490 return getDerived().TransformDecl(Loc, D);
491 }
492
493 /// Transform the given declaration, which was the first part of a
494 /// nested-name-specifier in a member access expression.
495 ///
496 /// This specific declaration transformation only applies to the first
497 /// identifier in a nested-name-specifier of a member access expression, e.g.,
498 /// the \c T in \c x->T::member
499 ///
500 /// By default, invokes TransformDecl() to transform the declaration.
501 /// Subclasses may override this function to provide alternate behavior.
502 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
503 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
504 }
505
506 /// Transform the set of declarations in an OverloadExpr.
507 bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
508 LookupResult &R);
509
510 /// Transform the given nested-name-specifier with source-location
511 /// information.
512 ///
513 /// By default, transforms all of the types and declarations within the
514 /// nested-name-specifier. Subclasses may override this function to provide
515 /// alternate behavior.
516 NestedNameSpecifierLoc
517 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
518 QualType ObjectType = QualType(),
519 NamedDecl *FirstQualifierInScope = nullptr);
520
521 /// Transform the given declaration name.
522 ///
523 /// By default, transforms the types of conversion function, constructor,
524 /// and destructor names and then (if needed) rebuilds the declaration name.
525 /// Identifiers and selectors are returned unmodified. Subclasses may
526 /// override this function to provide alternate behavior.
527 DeclarationNameInfo
528 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
529
530 bool TransformRequiresExprRequirements(ArrayRef<concepts::Requirement *> Reqs,
531 llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
532 concepts::TypeRequirement *
533 TransformTypeRequirement(concepts::TypeRequirement *Req);
534 concepts::ExprRequirement *
535 TransformExprRequirement(concepts::ExprRequirement *Req);
536 concepts::NestedRequirement *
537 TransformNestedRequirement(concepts::NestedRequirement *Req);
538
539 /// Transform the given template name.
540 ///
541 /// \param SS The nested-name-specifier that qualifies the template
542 /// name. This nested-name-specifier must already have been transformed.
543 ///
544 /// \param Name The template name to transform.
545 ///
546 /// \param NameLoc The source location of the template name.
547 ///
548 /// \param ObjectType If we're translating a template name within a member
549 /// access expression, this is the type of the object whose member template
550 /// is being referenced.
551 ///
552 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
553 /// also refers to a name within the current (lexical) scope, this is the
554 /// declaration it refers to.
555 ///
556 /// By default, transforms the template name by transforming the declarations
557 /// and nested-name-specifiers that occur within the template name.
558 /// Subclasses may override this function to provide alternate behavior.
559 TemplateName
560 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
561 SourceLocation NameLoc,
562 QualType ObjectType = QualType(),
563 NamedDecl *FirstQualifierInScope = nullptr,
564 bool AllowInjectedClassName = false);
565
566 /// Transform the given template argument.
567 ///
568 /// By default, this operation transforms the type, expression, or
569 /// declaration stored within the template argument and constructs a
570 /// new template argument from the transformed result. Subclasses may
571 /// override this function to provide alternate behavior.
572 ///
573 /// Returns true if there was an error.
574 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
575 TemplateArgumentLoc &Output,
576 bool Uneval = false);
577
578 /// Transform the given set of template arguments.
579 ///
580 /// By default, this operation transforms all of the template arguments
581 /// in the input set using \c TransformTemplateArgument(), and appends
582 /// the transformed arguments to the output list.
583 ///
584 /// Note that this overload of \c TransformTemplateArguments() is merely
585 /// a convenience function. Subclasses that wish to override this behavior
586 /// should override the iterator-based member template version.
587 ///
588 /// \param Inputs The set of template arguments to be transformed.
589 ///
590 /// \param NumInputs The number of template arguments in \p Inputs.
591 ///
592 /// \param Outputs The set of transformed template arguments output by this
593 /// routine.
594 ///
595 /// Returns true if an error occurred.
596 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
597 unsigned NumInputs,
598 TemplateArgumentListInfo &Outputs,
599 bool Uneval = false) {
600 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
601 Uneval);
602 }
603
604 /// Transform the given set of template arguments.
605 ///
606 /// By default, this operation transforms all of the template arguments
607 /// in the input set using \c TransformTemplateArgument(), and appends
608 /// the transformed arguments to the output list.
609 ///
610 /// \param First An iterator to the first template argument.
611 ///
612 /// \param Last An iterator one step past the last template argument.
613 ///
614 /// \param Outputs The set of transformed template arguments output by this
615 /// routine.
616 ///
617 /// Returns true if an error occurred.
618 template<typename InputIterator>
619 bool TransformTemplateArguments(InputIterator First,
620 InputIterator Last,
621 TemplateArgumentListInfo &Outputs,
622 bool Uneval = false);
623
624 /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
625 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
626 TemplateArgumentLoc &ArgLoc);
627
628 /// Fakes up a TypeSourceInfo for a type.
629 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
630 return SemaRef.Context.getTrivialTypeSourceInfo(T,
631 getDerived().getBaseLocation());
632 }
633
634#define ABSTRACT_TYPELOC(CLASS, PARENT)
635#define TYPELOC(CLASS, PARENT) \
636 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
637#include "clang/AST/TypeLocNodes.def"
638
639 template<typename Fn>
640 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
641 FunctionProtoTypeLoc TL,
642 CXXRecordDecl *ThisContext,
643 Qualifiers ThisTypeQuals,
644 Fn TransformExceptionSpec);
645
646 bool TransformExceptionSpec(SourceLocation Loc,
647 FunctionProtoType::ExceptionSpecInfo &ESI,
648 SmallVectorImpl<QualType> &Exceptions,
649 bool &Changed);
650
651 StmtResult TransformSEHHandler(Stmt *Handler);
652
653 QualType
654 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
655 TemplateSpecializationTypeLoc TL,
656 TemplateName Template);
657
658 QualType
659 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
660 DependentTemplateSpecializationTypeLoc TL,
661 TemplateName Template,
662 CXXScopeSpec &SS);
663
664 QualType TransformDependentTemplateSpecializationType(
665 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
666 NestedNameSpecifierLoc QualifierLoc);
667
668 /// Transforms the parameters of a function type into the
669 /// given vectors.
670 ///
671 /// The result vectors should be kept in sync; null entries in the
672 /// variables vector are acceptable.
673 ///
674 /// Return true on error.
675 bool TransformFunctionTypeParams(
676 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
677 const QualType *ParamTypes,
678 const FunctionProtoType::ExtParameterInfo *ParamInfos,
679 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
680 Sema::ExtParameterInfoBuilder &PInfos);
681
682 /// Transforms a single function-type parameter. Return null
683 /// on error.
684 ///
685 /// \param indexAdjustment - A number to add to the parameter's
686 /// scope index; can be negative
687 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
688 int indexAdjustment,
689 Optional<unsigned> NumExpansions,
690 bool ExpectParameterPack);
691
692 /// Transform the body of a lambda-expression.
693 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
694 /// Alternative implementation of TransformLambdaBody that skips transforming
695 /// the body.
696 StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
697
698 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
699
700 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
701 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
702
703 TemplateParameterList *TransformTemplateParameterList(
704 TemplateParameterList *TPL) {
705 return TPL;
706 }
707
708 ExprResult TransformAddressOfOperand(Expr *E);
709
710 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
711 bool IsAddressOfOperand,
712 TypeSourceInfo **RecoveryTSI);
713
714 ExprResult TransformParenDependentScopeDeclRefExpr(
715 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
716 TypeSourceInfo **RecoveryTSI);
717
718 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
719
720// FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
721// amount of stack usage with clang.
722#define STMT(Node, Parent) \
723 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
724 StmtResult Transform##Node(Node *S);
725#define VALUESTMT(Node, Parent) \
726 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
727 StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
728#define EXPR(Node, Parent) \
729 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
730 ExprResult Transform##Node(Node *E);
731#define ABSTRACT_STMT(Stmt)
732#include "clang/AST/StmtNodes.inc"
733
734#define GEN_CLANG_CLAUSE_CLASS
735#define CLAUSE_CLASS(Enum, Str, Class) \
736 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
737 OMPClause *Transform##Class(Class *S);
738#include "llvm/Frontend/OpenMP/OMP.inc"
739
740 /// Build a new qualified type given its unqualified type and type location.
741 ///
742 /// By default, this routine adds type qualifiers only to types that can
743 /// have qualifiers, and silently suppresses those qualifiers that are not
744 /// permitted. Subclasses may override this routine to provide different
745 /// behavior.
746 QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
747
748 /// Build a new pointer type given its pointee type.
749 ///
750 /// By default, performs semantic analysis when building the pointer type.
751 /// Subclasses may override this routine to provide different behavior.
752 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
753
754 /// Build a new block pointer type given its pointee type.
755 ///
756 /// By default, performs semantic analysis when building the block pointer
757 /// type. Subclasses may override this routine to provide different behavior.
758 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
759
760 /// Build a new reference type given the type it references.
761 ///
762 /// By default, performs semantic analysis when building the
763 /// reference type. Subclasses may override this routine to provide
764 /// different behavior.
765 ///
766 /// \param LValue whether the type was written with an lvalue sigil
767 /// or an rvalue sigil.
768 QualType RebuildReferenceType(QualType ReferentType,
769 bool LValue,
770 SourceLocation Sigil);
771
772 /// Build a new member pointer type given the pointee type and the
773 /// class type it refers into.
774 ///
775 /// By default, performs semantic analysis when building the member pointer
776 /// type. Subclasses may override this routine to provide different behavior.
777 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
778 SourceLocation Sigil);
779
780 QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
781 SourceLocation ProtocolLAngleLoc,
782 ArrayRef<ObjCProtocolDecl *> Protocols,
783 ArrayRef<SourceLocation> ProtocolLocs,
784 SourceLocation ProtocolRAngleLoc);
785
786 /// Build an Objective-C object type.
787 ///
788 /// By default, performs semantic analysis when building the object type.
789 /// Subclasses may override this routine to provide different behavior.
790 QualType RebuildObjCObjectType(QualType BaseType,
791 SourceLocation Loc,
792 SourceLocation TypeArgsLAngleLoc,
793 ArrayRef<TypeSourceInfo *> TypeArgs,
794 SourceLocation TypeArgsRAngleLoc,
795 SourceLocation ProtocolLAngleLoc,
796 ArrayRef<ObjCProtocolDecl *> Protocols,
797 ArrayRef<SourceLocation> ProtocolLocs,
798 SourceLocation ProtocolRAngleLoc);
799
800 /// Build a new Objective-C object pointer type given the pointee type.
801 ///
802 /// By default, directly builds the pointer type, with no additional semantic
803 /// analysis.
804 QualType RebuildObjCObjectPointerType(QualType PointeeType,
805 SourceLocation Star);
806
807 /// Build a new array type given the element type, size
808 /// modifier, size of the array (if known), size expression, and index type
809 /// qualifiers.
810 ///
811 /// By default, performs semantic analysis when building the array type.
812 /// Subclasses may override this routine to provide different behavior.
813 /// Also by default, all of the other Rebuild*Array
814 QualType RebuildArrayType(QualType ElementType,
815 ArrayType::ArraySizeModifier SizeMod,
816 const llvm::APInt *Size,
817 Expr *SizeExpr,
818 unsigned IndexTypeQuals,
819 SourceRange BracketsRange);
820
821 /// Build a new constant array type given the element type, size
822 /// modifier, (known) size of the array, and index type qualifiers.
823 ///
824 /// By default, performs semantic analysis when building the array type.
825 /// Subclasses may override this routine to provide different behavior.
826 QualType RebuildConstantArrayType(QualType ElementType,
827 ArrayType::ArraySizeModifier SizeMod,
828 const llvm::APInt &Size,
829 Expr *SizeExpr,
830 unsigned IndexTypeQuals,
831 SourceRange BracketsRange);
832
833 /// Build a new incomplete array type given the element type, size
834 /// modifier, and index type qualifiers.
835 ///
836 /// By default, performs semantic analysis when building the array type.
837 /// Subclasses may override this routine to provide different behavior.
838 QualType RebuildIncompleteArrayType(QualType ElementType,
839 ArrayType::ArraySizeModifier SizeMod,
840 unsigned IndexTypeQuals,
841 SourceRange BracketsRange);
842
843 /// Build a new variable-length array type given the element type,
844 /// size modifier, size expression, and index type qualifiers.
845 ///
846 /// By default, performs semantic analysis when building the array type.
847 /// Subclasses may override this routine to provide different behavior.
848 QualType RebuildVariableArrayType(QualType ElementType,
849 ArrayType::ArraySizeModifier SizeMod,
850 Expr *SizeExpr,
851 unsigned IndexTypeQuals,
852 SourceRange BracketsRange);
853
854 /// Build a new dependent-sized array type given the element type,
855 /// size modifier, size expression, and index type qualifiers.
856 ///
857 /// By default, performs semantic analysis when building the array type.
858 /// Subclasses may override this routine to provide different behavior.
859 QualType RebuildDependentSizedArrayType(QualType ElementType,
860 ArrayType::ArraySizeModifier SizeMod,
861 Expr *SizeExpr,
862 unsigned IndexTypeQuals,
863 SourceRange BracketsRange);
864
865 /// Build a new vector type given the element type and
866 /// number of elements.
867 ///
868 /// By default, performs semantic analysis when building the vector type.
869 /// Subclasses may override this routine to provide different behavior.
870 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
871 VectorType::VectorKind VecKind);
872
873 /// Build a new potentially dependently-sized extended vector type
874 /// given the element type and number of elements.
875 ///
876 /// By default, performs semantic analysis when building the vector type.
877 /// Subclasses may override this routine to provide different behavior.
878 QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
879 SourceLocation AttributeLoc,
880 VectorType::VectorKind);
881
882 /// Build a new extended vector type given the element type and
883 /// number of elements.
884 ///
885 /// By default, performs semantic analysis when building the vector type.
886 /// Subclasses may override this routine to provide different behavior.
887 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
888 SourceLocation AttributeLoc);
889
890 /// Build a new potentially dependently-sized extended vector type
891 /// given the element type and number of elements.
892 ///
893 /// By default, performs semantic analysis when building the vector type.
894 /// Subclasses may override this routine to provide different behavior.
895 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
896 Expr *SizeExpr,
897 SourceLocation AttributeLoc);
898
899 /// Build a new matrix type given the element type and dimensions.
900 QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
901 unsigned NumColumns);
902
903 /// Build a new matrix type given the type and dependently-defined
904 /// dimensions.
905 QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
906 Expr *ColumnExpr,
907 SourceLocation AttributeLoc);
908
909 /// Build a new DependentAddressSpaceType or return the pointee
910 /// type variable with the correct address space (retrieved from
911 /// AddrSpaceExpr) applied to it. The former will be returned in cases
912 /// where the address space remains dependent.
913 ///
914 /// By default, performs semantic analysis when building the type with address
915 /// space applied. Subclasses may override this routine to provide different
916 /// behavior.
917 QualType RebuildDependentAddressSpaceType(QualType PointeeType,
918 Expr *AddrSpaceExpr,
919 SourceLocation AttributeLoc);
920
921 /// Build a new function type.
922 ///
923 /// By default, performs semantic analysis when building the function type.
924 /// Subclasses may override this routine to provide different behavior.
925 QualType RebuildFunctionProtoType(QualType T,
926 MutableArrayRef<QualType> ParamTypes,
927 const FunctionProtoType::ExtProtoInfo &EPI);
928
929 /// Build a new unprototyped function type.
930 QualType RebuildFunctionNoProtoType(QualType ResultType);
931
932 /// Rebuild an unresolved typename type, given the decl that
933 /// the UnresolvedUsingTypenameDecl was transformed to.
934 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
935
936 /// Build a new type found via an alias.
937 QualType RebuildUsingType(UsingShadowDecl *Found, QualType Underlying) {
938 return SemaRef.Context.getUsingType(Found, Underlying);
939 }
940
941 /// Build a new typedef type.
942 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
943 return SemaRef.Context.getTypeDeclType(Typedef);
944 }
945
946 /// Build a new MacroDefined type.
947 QualType RebuildMacroQualifiedType(QualType T,
948 const IdentifierInfo *MacroII) {
949 return SemaRef.Context.getMacroQualifiedType(T, MacroII);
950 }
951
952 /// Build a new class/struct/union type.
953 QualType RebuildRecordType(RecordDecl *Record) {
954 return SemaRef.Context.getTypeDeclType(Record);
955 }
956
957 /// Build a new Enum type.
958 QualType RebuildEnumType(EnumDecl *Enum) {
959 return SemaRef.Context.getTypeDeclType(Enum);
960 }
961
962 /// Build a new typeof(expr) type.
963 ///
964 /// By default, performs semantic analysis when building the typeof type.
965 /// Subclasses may override this routine to provide different behavior.
966 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
967
968 /// Build a new typeof(type) type.
969 ///
970 /// By default, builds a new TypeOfType with the given underlying type.
971 QualType RebuildTypeOfType(QualType Underlying);
972
973 /// Build a new unary transform type.
974 QualType RebuildUnaryTransformType(QualType BaseType,
975 UnaryTransformType::UTTKind UKind,
976 SourceLocation Loc);
977
978 /// Build a new C++11 decltype type.
979 ///
980 /// By default, performs semantic analysis when building the decltype type.
981 /// Subclasses may override this routine to provide different behavior.
982 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
983
984 /// Build a new C++11 auto type.
985 ///
986 /// By default, builds a new AutoType with the given deduced type.
987 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
988 ConceptDecl *TypeConstraintConcept,
989 ArrayRef<TemplateArgument> TypeConstraintArgs) {
990 // Note, IsDependent is always false here: we implicitly convert an 'auto'
991 // which has been deduced to a dependent type into an undeduced 'auto', so
992 // that we'll retry deduction after the transformation.
993 return SemaRef.Context.getAutoType(Deduced, Keyword,
994 /*IsDependent*/ false, /*IsPack=*/false,
995 TypeConstraintConcept,
996 TypeConstraintArgs);
997 }
998
999 /// By default, builds a new DeducedTemplateSpecializationType with the given
1000 /// deduced type.
1001 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
1002 QualType Deduced) {
1003 return SemaRef.Context.getDeducedTemplateSpecializationType(
1004 Template, Deduced, /*IsDependent*/ false);
1005 }
1006
1007 /// Build a new template specialization type.
1008 ///
1009 /// By default, performs semantic analysis when building the template
1010 /// specialization type. Subclasses may override this routine to provide
1011 /// different behavior.
1012 QualType RebuildTemplateSpecializationType(TemplateName Template,
1013 SourceLocation TemplateLoc,
1014 TemplateArgumentListInfo &Args);
1015
1016 /// Build a new parenthesized type.
1017 ///
1018 /// By default, builds a new ParenType type from the inner type.
1019 /// Subclasses may override this routine to provide different behavior.
1020 QualType RebuildParenType(QualType InnerType) {
1021 return SemaRef.BuildParenType(InnerType);
1022 }
1023
1024 /// Build a new qualified name type.
1025 ///
1026 /// By default, builds a new ElaboratedType type from the keyword,
1027 /// the nested-name-specifier and the named type.
1028 /// Subclasses may override this routine to provide different behavior.
1029 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1030 ElaboratedTypeKeyword Keyword,
1031 NestedNameSpecifierLoc QualifierLoc,
1032 QualType Named) {
1033 return SemaRef.Context.getElaboratedType(Keyword,
1034 QualifierLoc.getNestedNameSpecifier(),
1035 Named);
1036 }
1037
1038 /// Build a new typename type that refers to a template-id.
1039 ///
1040 /// By default, builds a new DependentNameType type from the
1041 /// nested-name-specifier and the given type. Subclasses may override
1042 /// this routine to provide different behavior.
1043 QualType RebuildDependentTemplateSpecializationType(
1044 ElaboratedTypeKeyword Keyword,
1045 NestedNameSpecifierLoc QualifierLoc,
1046 SourceLocation TemplateKWLoc,
1047 const IdentifierInfo *Name,
1048 SourceLocation NameLoc,
1049 TemplateArgumentListInfo &Args,
1050 bool AllowInjectedClassName) {
1051 // Rebuild the template name.
1052 // TODO: avoid TemplateName abstraction
1053 CXXScopeSpec SS;
1054 SS.Adopt(QualifierLoc);
1055 TemplateName InstName = getDerived().RebuildTemplateName(
1056 SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1057 AllowInjectedClassName);
1058
1059 if (InstName.isNull())
1060 return QualType();
1061
1062 // If it's still dependent, make a dependent specialization.
1063 if (InstName.getAsDependentTemplateName())
1064 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1065 QualifierLoc.getNestedNameSpecifier(),
1066 Name,
1067 Args);
1068
1069 // Otherwise, make an elaborated type wrapping a non-dependent
1070 // specialization.
1071 QualType T =
1072 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1073 if (T.isNull()) return QualType();
1074
1075 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1076 return T;
1077
1078 return SemaRef.Context.getElaboratedType(Keyword,
1079 QualifierLoc.getNestedNameSpecifier(),
1080 T);
1081 }
1082
1083 /// Build a new typename type that refers to an identifier.
1084 ///
1085 /// By default, performs semantic analysis when building the typename type
1086 /// (or elaborated type). Subclasses may override this routine to provide
1087 /// different behavior.
1088 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1089 SourceLocation KeywordLoc,
1090 NestedNameSpecifierLoc QualifierLoc,
1091 const IdentifierInfo *Id,
1092 SourceLocation IdLoc,
1093 bool DeducedTSTContext) {
1094 CXXScopeSpec SS;
1095 SS.Adopt(QualifierLoc);
1096
1097 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1098 // If the name is still dependent, just build a new dependent name type.
1099 if (!SemaRef.computeDeclContext(SS))
1100 return SemaRef.Context.getDependentNameType(Keyword,
1101 QualifierLoc.getNestedNameSpecifier(),
1102 Id);
1103 }
1104
1105 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1106 return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1107 *Id, IdLoc, DeducedTSTContext);
1108 }
1109
1110 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1111
1112 // We had a dependent elaborated-type-specifier that has been transformed
1113 // into a non-dependent elaborated-type-specifier. Find the tag we're
1114 // referring to.
1115 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1116 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1117 if (!DC)
1118 return QualType();
1119
1120 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1121 return QualType();
1122
1123 TagDecl *Tag = nullptr;
1124 SemaRef.LookupQualifiedName(Result, DC);
1125 switch (Result.getResultKind()) {
1126 case LookupResult::NotFound:
1127 case LookupResult::NotFoundInCurrentInstantiation:
1128 break;
1129
1130 case LookupResult::Found:
1131 Tag = Result.getAsSingle<TagDecl>();
1132 break;
1133
1134 case LookupResult::FoundOverloaded:
1135 case LookupResult::FoundUnresolvedValue:
1136 llvm_unreachable("Tag lookup cannot find non-tags")::llvm::llvm_unreachable_internal("Tag lookup cannot find non-tags"
, "clang/lib/Sema/TreeTransform.h", 1136)
;
1137
1138 case LookupResult::Ambiguous:
1139 // Let the LookupResult structure handle ambiguities.
1140 return QualType();
1141 }
1142
1143 if (!Tag) {
1144 // Check where the name exists but isn't a tag type and use that to emit
1145 // better diagnostics.
1146 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1147 SemaRef.LookupQualifiedName(Result, DC);
1148 switch (Result.getResultKind()) {
1149 case LookupResult::Found:
1150 case LookupResult::FoundOverloaded:
1151 case LookupResult::FoundUnresolvedValue: {
1152 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1153 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1154 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1155 << NTK << Kind;
1156 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1157 break;
1158 }
1159 default:
1160 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1161 << Kind << Id << DC << QualifierLoc.getSourceRange();
1162 break;
1163 }
1164 return QualType();
1165 }
1166
1167 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1168 IdLoc, Id)) {
1169 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1170 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1171 return QualType();
1172 }
1173
1174 // Build the elaborated-type-specifier type.
1175 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1176 return SemaRef.Context.getElaboratedType(Keyword,
1177 QualifierLoc.getNestedNameSpecifier(),
1178 T);
1179 }
1180
1181 /// Build a new pack expansion type.
1182 ///
1183 /// By default, builds a new PackExpansionType type from the given pattern.
1184 /// Subclasses may override this routine to provide different behavior.
1185 QualType RebuildPackExpansionType(QualType Pattern,
1186 SourceRange PatternRange,
1187 SourceLocation EllipsisLoc,
1188 Optional<unsigned> NumExpansions) {
1189 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1190 NumExpansions);
1191 }
1192
1193 /// Build a new atomic type given its value type.
1194 ///
1195 /// By default, performs semantic analysis when building the atomic type.
1196 /// Subclasses may override this routine to provide different behavior.
1197 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1198
1199 /// Build a new pipe type given its value type.
1200 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1201 bool isReadPipe);
1202
1203 /// Build a bit-precise int given its value type.
1204 QualType RebuildBitIntType(bool IsUnsigned, unsigned NumBits,
1205 SourceLocation Loc);
1206
1207 /// Build a dependent bit-precise int given its value type.
1208 QualType RebuildDependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr,
1209 SourceLocation Loc);
1210
1211 /// Build a new template name given a nested name specifier, a flag
1212 /// indicating whether the "template" keyword was provided, and the template
1213 /// that the template name refers to.
1214 ///
1215 /// By default, builds the new template name directly. Subclasses may override
1216 /// this routine to provide different behavior.
1217 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1218 bool TemplateKW,
1219 TemplateDecl *Template);
1220
1221 /// Build a new template name given a nested name specifier and the
1222 /// name that is referred to as a template.
1223 ///
1224 /// By default, performs semantic analysis to determine whether the name can
1225 /// be resolved to a specific template, then builds the appropriate kind of
1226 /// template name. Subclasses may override this routine to provide different
1227 /// behavior.
1228 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1229 SourceLocation TemplateKWLoc,
1230 const IdentifierInfo &Name,
1231 SourceLocation NameLoc, QualType ObjectType,
1232 NamedDecl *FirstQualifierInScope,
1233 bool AllowInjectedClassName);
1234
1235 /// Build a new template name given a nested name specifier and the
1236 /// overloaded operator name that is referred to as a template.
1237 ///
1238 /// By default, performs semantic analysis to determine whether the name can
1239 /// be resolved to a specific template, then builds the appropriate kind of
1240 /// template name. Subclasses may override this routine to provide different
1241 /// behavior.
1242 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1243 SourceLocation TemplateKWLoc,
1244 OverloadedOperatorKind Operator,
1245 SourceLocation NameLoc, QualType ObjectType,
1246 bool AllowInjectedClassName);
1247
1248 /// Build a new template name given a template template parameter pack
1249 /// and the
1250 ///
1251 /// By default, performs semantic analysis to determine whether the name can
1252 /// be resolved to a specific template, then builds the appropriate kind of
1253 /// template name. Subclasses may override this routine to provide different
1254 /// behavior.
1255 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1256 const TemplateArgument &ArgPack) {
1257 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1258 }
1259
1260 /// Build a new compound statement.
1261 ///
1262 /// By default, performs semantic analysis to build the new statement.
1263 /// Subclasses may override this routine to provide different behavior.
1264 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1265 MultiStmtArg Statements,
1266 SourceLocation RBraceLoc,
1267 bool IsStmtExpr) {
1268 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1269 IsStmtExpr);
1270 }
1271
1272 /// Build a new case statement.
1273 ///
1274 /// By default, performs semantic analysis to build the new statement.
1275 /// Subclasses may override this routine to provide different behavior.
1276 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1277 Expr *LHS,
1278 SourceLocation EllipsisLoc,
1279 Expr *RHS,
1280 SourceLocation ColonLoc) {
1281 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1282 ColonLoc);
1283 }
1284
1285 /// Attach the body to a new case statement.
1286 ///
1287 /// By default, performs semantic analysis to build the new statement.
1288 /// Subclasses may override this routine to provide different behavior.
1289 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1290 getSema().ActOnCaseStmtBody(S, Body);
1291 return S;
1292 }
1293
1294 /// Build a new default statement.
1295 ///
1296 /// By default, performs semantic analysis to build the new statement.
1297 /// Subclasses may override this routine to provide different behavior.
1298 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1299 SourceLocation ColonLoc,
1300 Stmt *SubStmt) {
1301 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1302 /*CurScope=*/nullptr);
1303 }
1304
1305 /// Build a new label statement.
1306 ///
1307 /// By default, performs semantic analysis to build the new statement.
1308 /// Subclasses may override this routine to provide different behavior.
1309 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1310 SourceLocation ColonLoc, Stmt *SubStmt) {
1311 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1312 }
1313
1314 /// Build a new attributed statement.
1315 ///
1316 /// By default, performs semantic analysis to build the new statement.
1317 /// Subclasses may override this routine to provide different behavior.
1318 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1319 ArrayRef<const Attr *> Attrs,
1320 Stmt *SubStmt) {
1321 return SemaRef.BuildAttributedStmt(AttrLoc, Attrs, SubStmt);
1322 }
1323
1324 /// Build a new "if" statement.
1325 ///
1326 /// By default, performs semantic analysis to build the new statement.
1327 /// Subclasses may override this routine to provide different behavior.
1328 StmtResult RebuildIfStmt(SourceLocation IfLoc, IfStatementKind Kind,
1329 SourceLocation LParenLoc, Sema::ConditionResult Cond,
1330 SourceLocation RParenLoc, Stmt *Init, Stmt *Then,
1331 SourceLocation ElseLoc, Stmt *Else) {
1332 return getSema().ActOnIfStmt(IfLoc, Kind, LParenLoc, Init, Cond, RParenLoc,
1333 Then, ElseLoc, Else);
1334 }
1335
1336 /// Start building a new switch statement.
1337 ///
1338 /// By default, performs semantic analysis to build the new statement.
1339 /// Subclasses may override this routine to provide different behavior.
1340 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1341 SourceLocation LParenLoc, Stmt *Init,
1342 Sema::ConditionResult Cond,
1343 SourceLocation RParenLoc) {
1344 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, LParenLoc, Init, Cond,
1345 RParenLoc);
1346 }
1347
1348 /// Attach the body to the switch 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 RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1353 Stmt *Switch, Stmt *Body) {
1354 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1355 }
1356
1357 /// Build a new while 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 RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1362 Sema::ConditionResult Cond,
1363 SourceLocation RParenLoc, Stmt *Body) {
1364 return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1365 }
1366
1367 /// Build a new do-while statement.
1368 ///
1369 /// By default, performs semantic analysis to build the new statement.
1370 /// Subclasses may override this routine to provide different behavior.
1371 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1372 SourceLocation WhileLoc, SourceLocation LParenLoc,
1373 Expr *Cond, SourceLocation RParenLoc) {
1374 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1375 Cond, RParenLoc);
1376 }
1377
1378 /// Build a new for statement.
1379 ///
1380 /// By default, performs semantic analysis to build the new statement.
1381 /// Subclasses may override this routine to provide different behavior.
1382 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1383 Stmt *Init, Sema::ConditionResult Cond,
1384 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1385 Stmt *Body) {
1386 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1387 Inc, RParenLoc, Body);
1388 }
1389
1390 /// Build a new goto statement.
1391 ///
1392 /// By default, performs semantic analysis to build the new statement.
1393 /// Subclasses may override this routine to provide different behavior.
1394 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1395 LabelDecl *Label) {
1396 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1397 }
1398
1399 /// Build a new indirect goto 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 RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1404 SourceLocation StarLoc,
1405 Expr *Target) {
1406 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1407 }
1408
1409 /// Build a new return statement.
1410 ///
1411 /// By default, performs semantic analysis to build the new statement.
1412 /// Subclasses may override this routine to provide different behavior.
1413 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1414 return getSema().BuildReturnStmt(ReturnLoc, Result);
1415 }
1416
1417 /// Build a new declaration statement.
1418 ///
1419 /// By default, performs semantic analysis to build the new statement.
1420 /// Subclasses may override this routine to provide different behavior.
1421 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1422 SourceLocation StartLoc, SourceLocation EndLoc) {
1423 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1424 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1425 }
1426
1427 /// Build a new inline asm statement.
1428 ///
1429 /// By default, performs semantic analysis to build the new statement.
1430 /// Subclasses may override this routine to provide different behavior.
1431 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1432 bool IsVolatile, unsigned NumOutputs,
1433 unsigned NumInputs, IdentifierInfo **Names,
1434 MultiExprArg Constraints, MultiExprArg Exprs,
1435 Expr *AsmString, MultiExprArg Clobbers,
1436 unsigned NumLabels,
1437 SourceLocation RParenLoc) {
1438 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1439 NumInputs, Names, Constraints, Exprs,
1440 AsmString, Clobbers, NumLabels, RParenLoc);
1441 }
1442
1443 /// Build a new MS style inline asm statement.
1444 ///
1445 /// By default, performs semantic analysis to build the new statement.
1446 /// Subclasses may override this routine to provide different behavior.
1447 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1448 ArrayRef<Token> AsmToks,
1449 StringRef AsmString,
1450 unsigned NumOutputs, unsigned NumInputs,
1451 ArrayRef<StringRef> Constraints,
1452 ArrayRef<StringRef> Clobbers,
1453 ArrayRef<Expr*> Exprs,
1454 SourceLocation EndLoc) {
1455 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1456 NumOutputs, NumInputs,
1457 Constraints, Clobbers, Exprs, EndLoc);
1458 }
1459
1460 /// Build a new co_return statement.
1461 ///
1462 /// By default, performs semantic analysis to build the new statement.
1463 /// Subclasses may override this routine to provide different behavior.
1464 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1465 bool IsImplicit) {
1466 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1467 }
1468
1469 /// Build a new co_await expression.
1470 ///
1471 /// By default, performs semantic analysis to build the new expression.
1472 /// Subclasses may override this routine to provide different behavior.
1473 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1474 bool IsImplicit) {
1475 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1476 }
1477
1478 /// Build a new co_await expression.
1479 ///
1480 /// By default, performs semantic analysis to build the new expression.
1481 /// Subclasses may override this routine to provide different behavior.
1482 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1483 Expr *Result,
1484 UnresolvedLookupExpr *Lookup) {
1485 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1486 }
1487
1488 /// Build a new co_yield expression.
1489 ///
1490 /// By default, performs semantic analysis to build the new expression.
1491 /// Subclasses may override this routine to provide different behavior.
1492 ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1493 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1494 }
1495
1496 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1497 return getSema().BuildCoroutineBodyStmt(Args);
1498 }
1499
1500 /// Build a new Objective-C \@try statement.
1501 ///
1502 /// By default, performs semantic analysis to build the new statement.
1503 /// Subclasses may override this routine to provide different behavior.
1504 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1505 Stmt *TryBody,
1506 MultiStmtArg CatchStmts,
1507 Stmt *Finally) {
1508 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1509 Finally);
1510 }
1511
1512 /// Rebuild an Objective-C exception declaration.
1513 ///
1514 /// By default, performs semantic analysis to build the new declaration.
1515 /// Subclasses may override this routine to provide different behavior.
1516 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1517 TypeSourceInfo *TInfo, QualType T) {
1518 return getSema().BuildObjCExceptionDecl(TInfo, T,
1519 ExceptionDecl->getInnerLocStart(),
1520 ExceptionDecl->getLocation(),
1521 ExceptionDecl->getIdentifier());
1522 }
1523
1524 /// Build a new Objective-C \@catch statement.
1525 ///
1526 /// By default, performs semantic analysis to build the new statement.
1527 /// Subclasses may override this routine to provide different behavior.
1528 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1529 SourceLocation RParenLoc,
1530 VarDecl *Var,
1531 Stmt *Body) {
1532 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1533 Var, Body);
1534 }
1535
1536 /// Build a new Objective-C \@finally statement.
1537 ///
1538 /// By default, performs semantic analysis to build the new statement.
1539 /// Subclasses may override this routine to provide different behavior.
1540 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1541 Stmt *Body) {
1542 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1543 }
1544
1545 /// Build a new Objective-C \@throw statement.
1546 ///
1547 /// By default, performs semantic analysis to build the new statement.
1548 /// Subclasses may override this routine to provide different behavior.
1549 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1550 Expr *Operand) {
1551 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1552 }
1553
1554 /// Build a new OpenMP Canonical loop.
1555 ///
1556 /// Ensures that the outermost loop in @p LoopStmt is wrapped by a
1557 /// OMPCanonicalLoop.
1558 StmtResult RebuildOMPCanonicalLoop(Stmt *LoopStmt) {
1559 return getSema().ActOnOpenMPCanonicalLoop(LoopStmt);
1560 }
1561
1562 /// Build a new OpenMP executable directive.
1563 ///
1564 /// By default, performs semantic analysis to build the new statement.
1565 /// Subclasses may override this routine to provide different behavior.
1566 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1567 DeclarationNameInfo DirName,
1568 OpenMPDirectiveKind CancelRegion,
1569 ArrayRef<OMPClause *> Clauses,
1570 Stmt *AStmt, SourceLocation StartLoc,
1571 SourceLocation EndLoc) {
1572 return getSema().ActOnOpenMPExecutableDirective(
1573 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1574 }
1575
1576 /// Build a new OpenMP 'if' clause.
1577 ///
1578 /// By default, performs semantic analysis to build the new OpenMP clause.
1579 /// Subclasses may override this routine to provide different behavior.
1580 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1581 Expr *Condition, SourceLocation StartLoc,
1582 SourceLocation LParenLoc,
1583 SourceLocation NameModifierLoc,
1584 SourceLocation ColonLoc,
1585 SourceLocation EndLoc) {
1586 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1587 LParenLoc, NameModifierLoc, ColonLoc,
1588 EndLoc);
1589 }
1590
1591 /// Build a new OpenMP 'final' clause.
1592 ///
1593 /// By default, performs semantic analysis to build the new OpenMP clause.
1594 /// Subclasses may override this routine to provide different behavior.
1595 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1596 SourceLocation LParenLoc,
1597 SourceLocation EndLoc) {
1598 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1599 EndLoc);
1600 }
1601
1602 /// Build a new OpenMP 'num_threads' clause.
1603 ///
1604 /// By default, performs semantic analysis to build the new OpenMP clause.
1605 /// Subclasses may override this routine to provide different behavior.
1606 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1607 SourceLocation StartLoc,
1608 SourceLocation LParenLoc,
1609 SourceLocation EndLoc) {
1610 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1611 LParenLoc, EndLoc);
1612 }
1613
1614 /// Build a new OpenMP 'safelen' clause.
1615 ///
1616 /// By default, performs semantic analysis to build the new OpenMP clause.
1617 /// Subclasses may override this routine to provide different behavior.
1618 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1619 SourceLocation LParenLoc,
1620 SourceLocation EndLoc) {
1621 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1622 }
1623
1624 /// Build a new OpenMP 'simdlen' clause.
1625 ///
1626 /// By default, performs semantic analysis to build the new OpenMP clause.
1627 /// Subclasses may override this routine to provide different behavior.
1628 OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1629 SourceLocation LParenLoc,
1630 SourceLocation EndLoc) {
1631 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1632 }
1633
1634 OMPClause *RebuildOMPSizesClause(ArrayRef<Expr *> Sizes,
1635 SourceLocation StartLoc,
1636 SourceLocation LParenLoc,
1637 SourceLocation EndLoc) {
1638 return getSema().ActOnOpenMPSizesClause(Sizes, StartLoc, LParenLoc, EndLoc);
1639 }
1640
1641 /// Build a new OpenMP 'full' clause.
1642 OMPClause *RebuildOMPFullClause(SourceLocation StartLoc,
1643 SourceLocation EndLoc) {
1644 return getSema().ActOnOpenMPFullClause(StartLoc, EndLoc);
1645 }
1646
1647 /// Build a new OpenMP 'partial' clause.
1648 OMPClause *RebuildOMPPartialClause(Expr *Factor, SourceLocation StartLoc,
1649 SourceLocation LParenLoc,
1650 SourceLocation EndLoc) {
1651 return getSema().ActOnOpenMPPartialClause(Factor, StartLoc, LParenLoc,
1652 EndLoc);
1653 }
1654
1655 /// Build a new OpenMP 'allocator' clause.
1656 ///
1657 /// By default, performs semantic analysis to build the new OpenMP clause.
1658 /// Subclasses may override this routine to provide different behavior.
1659 OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1660 SourceLocation LParenLoc,
1661 SourceLocation EndLoc) {
1662 return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1663 }
1664
1665 /// Build a new OpenMP 'collapse' clause.
1666 ///
1667 /// By default, performs semantic analysis to build the new OpenMP clause.
1668 /// Subclasses may override this routine to provide different behavior.
1669 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1670 SourceLocation LParenLoc,
1671 SourceLocation EndLoc) {
1672 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1673 EndLoc);
1674 }
1675
1676 /// Build a new OpenMP 'default' clause.
1677 ///
1678 /// By default, performs semantic analysis to build the new OpenMP clause.
1679 /// Subclasses may override this routine to provide different behavior.
1680 OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1681 SourceLocation StartLoc,
1682 SourceLocation LParenLoc,
1683 SourceLocation EndLoc) {
1684 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1685 StartLoc, LParenLoc, EndLoc);
1686 }
1687
1688 /// Build a new OpenMP 'proc_bind' clause.
1689 ///
1690 /// By default, performs semantic analysis to build the new OpenMP clause.
1691 /// Subclasses may override this routine to provide different behavior.
1692 OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1693 SourceLocation KindKwLoc,
1694 SourceLocation StartLoc,
1695 SourceLocation LParenLoc,
1696 SourceLocation EndLoc) {
1697 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1698 StartLoc, LParenLoc, EndLoc);
1699 }
1700
1701 /// Build a new OpenMP 'schedule' clause.
1702 ///
1703 /// By default, performs semantic analysis to build the new OpenMP clause.
1704 /// Subclasses may override this routine to provide different behavior.
1705 OMPClause *RebuildOMPScheduleClause(
1706 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1707 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1708 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1709 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1710 return getSema().ActOnOpenMPScheduleClause(
1711 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1712 CommaLoc, EndLoc);
1713 }
1714
1715 /// Build a new OpenMP 'ordered' clause.
1716 ///
1717 /// By default, performs semantic analysis to build the new OpenMP clause.
1718 /// Subclasses may override this routine to provide different behavior.
1719 OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1720 SourceLocation EndLoc,
1721 SourceLocation LParenLoc, Expr *Num) {
1722 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1723 }
1724
1725 /// Build a new OpenMP 'private' clause.
1726 ///
1727 /// By default, performs semantic analysis to build the new OpenMP clause.
1728 /// Subclasses may override this routine to provide different behavior.
1729 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1730 SourceLocation StartLoc,
1731 SourceLocation LParenLoc,
1732 SourceLocation EndLoc) {
1733 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1734 EndLoc);
1735 }
1736
1737 /// Build a new OpenMP 'firstprivate' 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 *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1742 SourceLocation StartLoc,
1743 SourceLocation LParenLoc,
1744 SourceLocation EndLoc) {
1745 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1746 EndLoc);
1747 }
1748
1749 /// Build a new OpenMP 'lastprivate' clause.
1750 ///
1751 /// By default, performs semantic analysis to build the new OpenMP clause.
1752 /// Subclasses may override this routine to provide different behavior.
1753 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1754 OpenMPLastprivateModifier LPKind,
1755 SourceLocation LPKindLoc,
1756 SourceLocation ColonLoc,
1757 SourceLocation StartLoc,
1758 SourceLocation LParenLoc,
1759 SourceLocation EndLoc) {
1760 return getSema().ActOnOpenMPLastprivateClause(
1761 VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1762 }
1763
1764 /// Build a new OpenMP 'shared' clause.
1765 ///
1766 /// By default, performs semantic analysis to build the new OpenMP clause.
1767 /// Subclasses may override this routine to provide different behavior.
1768 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1769 SourceLocation StartLoc,
1770 SourceLocation LParenLoc,
1771 SourceLocation EndLoc) {
1772 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1773 EndLoc);
1774 }
1775
1776 /// Build a new OpenMP 'reduction' clause.
1777 ///
1778 /// By default, performs semantic analysis to build the new statement.
1779 /// Subclasses may override this routine to provide different behavior.
1780 OMPClause *RebuildOMPReductionClause(
1781 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1782 SourceLocation StartLoc, SourceLocation LParenLoc,
1783 SourceLocation ModifierLoc, SourceLocation ColonLoc,
1784 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1785 const DeclarationNameInfo &ReductionId,
1786 ArrayRef<Expr *> UnresolvedReductions) {
1787 return getSema().ActOnOpenMPReductionClause(
1788 VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1789 ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1790 }
1791
1792 /// Build a new OpenMP 'task_reduction' clause.
1793 ///
1794 /// By default, performs semantic analysis to build the new statement.
1795 /// Subclasses may override this routine to provide different behavior.
1796 OMPClause *RebuildOMPTaskReductionClause(
1797 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1798 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1799 CXXScopeSpec &ReductionIdScopeSpec,
1800 const DeclarationNameInfo &ReductionId,
1801 ArrayRef<Expr *> UnresolvedReductions) {
1802 return getSema().ActOnOpenMPTaskReductionClause(
1803 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1804 ReductionId, UnresolvedReductions);
1805 }
1806
1807 /// Build a new OpenMP 'in_reduction' clause.
1808 ///
1809 /// By default, performs semantic analysis to build the new statement.
1810 /// Subclasses may override this routine to provide different behavior.
1811 OMPClause *
1812 RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1813 SourceLocation LParenLoc, SourceLocation ColonLoc,
1814 SourceLocation EndLoc,
1815 CXXScopeSpec &ReductionIdScopeSpec,
1816 const DeclarationNameInfo &ReductionId,
1817 ArrayRef<Expr *> UnresolvedReductions) {
1818 return getSema().ActOnOpenMPInReductionClause(
1819 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1820 ReductionId, UnresolvedReductions);
1821 }
1822
1823 /// Build a new OpenMP 'linear' clause.
1824 ///
1825 /// By default, performs semantic analysis to build the new OpenMP clause.
1826 /// Subclasses may override this routine to provide different behavior.
1827 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1828 SourceLocation StartLoc,
1829 SourceLocation LParenLoc,
1830 OpenMPLinearClauseKind Modifier,
1831 SourceLocation ModifierLoc,
1832 SourceLocation ColonLoc,
1833 SourceLocation EndLoc) {
1834 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1835 Modifier, ModifierLoc, ColonLoc,
1836 EndLoc);
1837 }
1838
1839 /// Build a new OpenMP 'aligned' clause.
1840 ///
1841 /// By default, performs semantic analysis to build the new OpenMP clause.
1842 /// Subclasses may override this routine to provide different behavior.
1843 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1844 SourceLocation StartLoc,
1845 SourceLocation LParenLoc,
1846 SourceLocation ColonLoc,
1847 SourceLocation EndLoc) {
1848 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1849 LParenLoc, ColonLoc, EndLoc);
1850 }
1851
1852 /// Build a new OpenMP 'copyin' clause.
1853 ///
1854 /// By default, performs semantic analysis to build the new OpenMP clause.
1855 /// Subclasses may override this routine to provide different behavior.
1856 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1857 SourceLocation StartLoc,
1858 SourceLocation LParenLoc,
1859 SourceLocation EndLoc) {
1860 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1861 EndLoc);
1862 }
1863
1864 /// Build a new OpenMP 'copyprivate' clause.
1865 ///
1866 /// By default, performs semantic analysis to build the new OpenMP clause.
1867 /// Subclasses may override this routine to provide different behavior.
1868 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1869 SourceLocation StartLoc,
1870 SourceLocation LParenLoc,
1871 SourceLocation EndLoc) {
1872 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1873 EndLoc);
1874 }
1875
1876 /// Build a new OpenMP 'flush' pseudo clause.
1877 ///
1878 /// By default, performs semantic analysis to build the new OpenMP clause.
1879 /// Subclasses may override this routine to provide different behavior.
1880 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1881 SourceLocation StartLoc,
1882 SourceLocation LParenLoc,
1883 SourceLocation EndLoc) {
1884 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1885 EndLoc);
1886 }
1887
1888 /// Build a new OpenMP 'depobj' pseudo clause.
1889 ///
1890 /// By default, performs semantic analysis to build the new OpenMP clause.
1891 /// Subclasses may override this routine to provide different behavior.
1892 OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1893 SourceLocation LParenLoc,
1894 SourceLocation EndLoc) {
1895 return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1896 EndLoc);
1897 }
1898
1899 /// Build a new OpenMP 'depend' pseudo clause.
1900 ///
1901 /// By default, performs semantic analysis to build the new OpenMP clause.
1902 /// Subclasses may override this routine to provide different behavior.
1903 OMPClause *
1904 RebuildOMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
1905 SourceLocation DepLoc, SourceLocation ColonLoc,
1906 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1907 SourceLocation LParenLoc, SourceLocation EndLoc) {
1908 return getSema().ActOnOpenMPDependClause(DepModifier, DepKind, DepLoc,
1909 ColonLoc, VarList, StartLoc,
1910 LParenLoc, EndLoc);
1911 }
1912
1913 /// Build a new OpenMP 'device' clause.
1914 ///
1915 /// By default, performs semantic analysis to build the new statement.
1916 /// Subclasses may override this routine to provide different behavior.
1917 OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
1918 Expr *Device, SourceLocation StartLoc,
1919 SourceLocation LParenLoc,
1920 SourceLocation ModifierLoc,
1921 SourceLocation EndLoc) {
1922 return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
1923 LParenLoc, ModifierLoc, EndLoc);
1924 }
1925
1926 /// Build a new OpenMP 'map' clause.
1927 ///
1928 /// By default, performs semantic analysis to build the new OpenMP clause.
1929 /// Subclasses may override this routine to provide different behavior.
1930 OMPClause *RebuildOMPMapClause(
1931 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1932 ArrayRef<SourceLocation> MapTypeModifiersLoc,
1933 CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1934 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1935 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1936 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1937 return getSema().ActOnOpenMPMapClause(
1938 MapTypeModifiers, MapTypeModifiersLoc, MapperIdScopeSpec, MapperId,
1939 MapType, IsMapTypeImplicit, MapLoc, ColonLoc, VarList, Locs,
1940 /*NoDiagnose=*/false, UnresolvedMappers);
1941 }
1942
1943 /// Build a new OpenMP 'allocate' clause.
1944 ///
1945 /// By default, performs semantic analysis to build the new OpenMP clause.
1946 /// Subclasses may override this routine to provide different behavior.
1947 OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1948 SourceLocation StartLoc,
1949 SourceLocation LParenLoc,
1950 SourceLocation ColonLoc,
1951 SourceLocation EndLoc) {
1952 return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1953 LParenLoc, ColonLoc, EndLoc);
1954 }
1955
1956 /// Build a new OpenMP 'num_teams' clause.
1957 ///
1958 /// By default, performs semantic analysis to build the new statement.
1959 /// Subclasses may override this routine to provide different behavior.
1960 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1961 SourceLocation LParenLoc,
1962 SourceLocation EndLoc) {
1963 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1964 EndLoc);
1965 }
1966
1967 /// Build a new OpenMP 'thread_limit' clause.
1968 ///
1969 /// By default, performs semantic analysis to build the new statement.
1970 /// Subclasses may override this routine to provide different behavior.
1971 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1972 SourceLocation StartLoc,
1973 SourceLocation LParenLoc,
1974 SourceLocation EndLoc) {
1975 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1976 LParenLoc, EndLoc);
1977 }
1978
1979 /// Build a new OpenMP 'priority' clause.
1980 ///
1981 /// By default, performs semantic analysis to build the new statement.
1982 /// Subclasses may override this routine to provide different behavior.
1983 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1984 SourceLocation LParenLoc,
1985 SourceLocation EndLoc) {
1986 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1987 EndLoc);
1988 }
1989
1990 /// Build a new OpenMP 'grainsize' clause.
1991 ///
1992 /// By default, performs semantic analysis to build the new statement.
1993 /// Subclasses may override this routine to provide different behavior.
1994 OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1995 SourceLocation LParenLoc,
1996 SourceLocation EndLoc) {
1997 return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1998 EndLoc);
1999 }
2000
2001 /// Build a new OpenMP 'num_tasks' clause.
2002 ///
2003 /// By default, performs semantic analysis to build the new statement.
2004 /// Subclasses may override this routine to provide different behavior.
2005 OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
2006 SourceLocation LParenLoc,
2007 SourceLocation EndLoc) {
2008 return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
2009 EndLoc);
2010 }
2011
2012 /// Build a new OpenMP 'hint' clause.
2013 ///
2014 /// By default, performs semantic analysis to build the new statement.
2015 /// Subclasses may override this routine to provide different behavior.
2016 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
2017 SourceLocation LParenLoc,
2018 SourceLocation EndLoc) {
2019 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
2020 }
2021
2022 /// Build a new OpenMP 'detach' clause.
2023 ///
2024 /// By default, performs semantic analysis to build the new statement.
2025 /// Subclasses may override this routine to provide different behavior.
2026 OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
2027 SourceLocation LParenLoc,
2028 SourceLocation EndLoc) {
2029 return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
2030 }
2031
2032 /// Build a new OpenMP 'dist_schedule' clause.
2033 ///
2034 /// By default, performs semantic analysis to build the new OpenMP clause.
2035 /// Subclasses may override this routine to provide different behavior.
2036 OMPClause *
2037 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
2038 Expr *ChunkSize, SourceLocation StartLoc,
2039 SourceLocation LParenLoc, SourceLocation KindLoc,
2040 SourceLocation CommaLoc, SourceLocation EndLoc) {
2041 return getSema().ActOnOpenMPDistScheduleClause(
2042 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2043 }
2044
2045 /// Build a new OpenMP 'to' clause.
2046 ///
2047 /// By default, performs semantic analysis to build the new statement.
2048 /// Subclasses may override this routine to provide different behavior.
2049 OMPClause *
2050 RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2051 ArrayRef<SourceLocation> MotionModifiersLoc,
2052 CXXScopeSpec &MapperIdScopeSpec,
2053 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2054 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2055 ArrayRef<Expr *> UnresolvedMappers) {
2056 return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2057 MapperIdScopeSpec, MapperId, ColonLoc,
2058 VarList, Locs, UnresolvedMappers);
2059 }
2060
2061 /// Build a new OpenMP 'from' 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 *
2066 RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2067 ArrayRef<SourceLocation> MotionModifiersLoc,
2068 CXXScopeSpec &MapperIdScopeSpec,
2069 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2070 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2071 ArrayRef<Expr *> UnresolvedMappers) {
2072 return getSema().ActOnOpenMPFromClause(
2073 MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2074 ColonLoc, VarList, Locs, UnresolvedMappers);
2075 }
2076
2077 /// Build a new OpenMP 'use_device_ptr' clause.
2078 ///
2079 /// By default, performs semantic analysis to build the new OpenMP clause.
2080 /// Subclasses may override this routine to provide different behavior.
2081 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2082 const OMPVarListLocTy &Locs) {
2083 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2084 }
2085
2086 /// Build a new OpenMP 'use_device_addr' clause.
2087 ///
2088 /// By default, performs semantic analysis to build the new OpenMP clause.
2089 /// Subclasses may override this routine to provide different behavior.
2090 OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2091 const OMPVarListLocTy &Locs) {
2092 return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2093 }
2094
2095 /// Build a new OpenMP 'is_device_ptr' clause.
2096 ///
2097 /// By default, performs semantic analysis to build the new OpenMP clause.
2098 /// Subclasses may override this routine to provide different behavior.
2099 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2100 const OMPVarListLocTy &Locs) {
2101 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2102 }
2103
2104 /// Build a new OpenMP 'has_device_addr' clause.
2105 ///
2106 /// By default, performs semantic analysis to build the new OpenMP clause.
2107 /// Subclasses may override this routine to provide different behavior.
2108 OMPClause *RebuildOMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
2109 const OMPVarListLocTy &Locs) {
2110 return getSema().ActOnOpenMPHasDeviceAddrClause(VarList, Locs);
2111 }
2112
2113 /// Build a new OpenMP 'defaultmap' clause.
2114 ///
2115 /// By default, performs semantic analysis to build the new OpenMP clause.
2116 /// Subclasses may override this routine to provide different behavior.
2117 OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2118 OpenMPDefaultmapClauseKind Kind,
2119 SourceLocation StartLoc,
2120 SourceLocation LParenLoc,
2121 SourceLocation MLoc,
2122 SourceLocation KindLoc,
2123 SourceLocation EndLoc) {
2124 return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2125 MLoc, KindLoc, EndLoc);
2126 }
2127
2128 /// Build a new OpenMP 'nontemporal' clause.
2129 ///
2130 /// By default, performs semantic analysis to build the new OpenMP clause.
2131 /// Subclasses may override this routine to provide different behavior.
2132 OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2133 SourceLocation StartLoc,
2134 SourceLocation LParenLoc,
2135 SourceLocation EndLoc) {
2136 return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2137 EndLoc);
2138 }
2139
2140 /// Build a new OpenMP 'inclusive' clause.
2141 ///
2142 /// By default, performs semantic analysis to build the new OpenMP clause.
2143 /// Subclasses may override this routine to provide different behavior.
2144 OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2145 SourceLocation StartLoc,
2146 SourceLocation LParenLoc,
2147 SourceLocation EndLoc) {
2148 return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2149 EndLoc);
2150 }
2151
2152 /// Build a new OpenMP 'exclusive' clause.
2153 ///
2154 /// By default, performs semantic analysis to build the new OpenMP clause.
2155 /// Subclasses may override this routine to provide different behavior.
2156 OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2157 SourceLocation StartLoc,
2158 SourceLocation LParenLoc,
2159 SourceLocation EndLoc) {
2160 return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2161 EndLoc);
2162 }
2163
2164 /// Build a new OpenMP 'uses_allocators' clause.
2165 ///
2166 /// By default, performs semantic analysis to build the new OpenMP clause.
2167 /// Subclasses may override this routine to provide different behavior.
2168 OMPClause *RebuildOMPUsesAllocatorsClause(
2169 ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2170 SourceLocation LParenLoc, SourceLocation EndLoc) {
2171 return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2172 Data);
2173 }
2174
2175 /// Build a new OpenMP 'affinity' clause.
2176 ///
2177 /// By default, performs semantic analysis to build the new OpenMP clause.
2178 /// Subclasses may override this routine to provide different behavior.
2179 OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2180 SourceLocation LParenLoc,
2181 SourceLocation ColonLoc,
2182 SourceLocation EndLoc, Expr *Modifier,
2183 ArrayRef<Expr *> Locators) {
2184 return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2185 EndLoc, Modifier, Locators);
2186 }
2187
2188 /// Build a new OpenMP 'order' clause.
2189 ///
2190 /// By default, performs semantic analysis to build the new OpenMP clause.
2191 /// Subclasses may override this routine to provide different behavior.
2192 OMPClause *RebuildOMPOrderClause(OpenMPOrderClauseKind Kind,
2193 SourceLocation KindKwLoc,
2194 SourceLocation StartLoc,
2195 SourceLocation LParenLoc,
2196 SourceLocation EndLoc) {
2197 return getSema().ActOnOpenMPOrderClause(Kind, KindKwLoc, StartLoc,
2198 LParenLoc, EndLoc);
2199 }
2200
2201 /// Build a new OpenMP 'init' clause.
2202 ///
2203 /// By default, performs semantic analysis to build the new OpenMP clause.
2204 /// Subclasses may override this routine to provide different behavior.
2205 OMPClause *RebuildOMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
2206 bool IsTarget, bool IsTargetSync,
2207 SourceLocation StartLoc,
2208 SourceLocation LParenLoc,
2209 SourceLocation VarLoc,
2210 SourceLocation EndLoc) {
2211 return getSema().ActOnOpenMPInitClause(InteropVar, PrefExprs, IsTarget,
2212 IsTargetSync, StartLoc, LParenLoc,
2213 VarLoc, EndLoc);
2214 }
2215
2216 /// Build a new OpenMP 'use' clause.
2217 ///
2218 /// By default, performs semantic analysis to build the new OpenMP clause.
2219 /// Subclasses may override this routine to provide different behavior.
2220 OMPClause *RebuildOMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
2221 SourceLocation LParenLoc,
2222 SourceLocation VarLoc, SourceLocation EndLoc) {
2223 return getSema().ActOnOpenMPUseClause(InteropVar, StartLoc, LParenLoc,
2224 VarLoc, EndLoc);
2225 }
2226
2227 /// Build a new OpenMP 'destroy' clause.
2228 ///
2229 /// By default, performs semantic analysis to build the new OpenMP clause.
2230 /// Subclasses may override this routine to provide different behavior.
2231 OMPClause *RebuildOMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
2232 SourceLocation LParenLoc,
2233 SourceLocation VarLoc,
2234 SourceLocation EndLoc) {
2235 return getSema().ActOnOpenMPDestroyClause(InteropVar, StartLoc, LParenLoc,
2236 VarLoc, EndLoc);
2237 }
2238
2239 /// Build a new OpenMP 'novariants' clause.
2240 ///
2241 /// By default, performs semantic analysis to build the new OpenMP clause.
2242 /// Subclasses may override this routine to provide different behavior.
2243 OMPClause *RebuildOMPNovariantsClause(Expr *Condition,
2244 SourceLocation StartLoc,
2245 SourceLocation LParenLoc,
2246 SourceLocation EndLoc) {
2247 return getSema().ActOnOpenMPNovariantsClause(Condition, StartLoc, LParenLoc,
2248 EndLoc);
2249 }
2250
2251 /// Build a new OpenMP 'nocontext' clause.
2252 ///
2253 /// By default, performs semantic analysis to build the new OpenMP clause.
2254 /// Subclasses may override this routine to provide different behavior.
2255 OMPClause *RebuildOMPNocontextClause(Expr *Condition, SourceLocation StartLoc,
2256 SourceLocation LParenLoc,
2257 SourceLocation EndLoc) {
2258 return getSema().ActOnOpenMPNocontextClause(Condition, StartLoc, LParenLoc,
2259 EndLoc);
2260 }
2261
2262 /// Build a new OpenMP 'filter' clause.
2263 ///
2264 /// By default, performs semantic analysis to build the new OpenMP clause.
2265 /// Subclasses may override this routine to provide different behavior.
2266 OMPClause *RebuildOMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
2267 SourceLocation LParenLoc,
2268 SourceLocation EndLoc) {
2269 return getSema().ActOnOpenMPFilterClause(ThreadID, StartLoc, LParenLoc,
2270 EndLoc);
2271 }
2272
2273 /// Build a new OpenMP 'bind' clause.
2274 ///
2275 /// By default, performs semantic analysis to build the new OpenMP clause.
2276 /// Subclasses may override this routine to provide different behavior.
2277 OMPClause *RebuildOMPBindClause(OpenMPBindClauseKind Kind,
2278 SourceLocation KindLoc,
2279 SourceLocation StartLoc,
2280 SourceLocation LParenLoc,
2281 SourceLocation EndLoc) {
2282 return getSema().ActOnOpenMPBindClause(Kind, KindLoc, StartLoc, LParenLoc,
2283 EndLoc);
2284 }
2285
2286 /// Build a new OpenMP 'align' 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 *RebuildOMPAlignClause(Expr *A, SourceLocation StartLoc,
2291 SourceLocation LParenLoc,
2292 SourceLocation EndLoc) {
2293 return getSema().ActOnOpenMPAlignClause(A, StartLoc, LParenLoc, EndLoc);
2294 }
2295
2296 /// Rebuild the operand to an Objective-C \@synchronized statement.
2297 ///
2298 /// By default, performs semantic analysis to build the new statement.
2299 /// Subclasses may override this routine to provide different behavior.
2300 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2301 Expr *object) {
2302 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2303 }
2304
2305 /// Build a new Objective-C \@synchronized statement.
2306 ///
2307 /// By default, performs semantic analysis to build the new statement.
2308 /// Subclasses may override this routine to provide different behavior.
2309 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2310 Expr *Object, Stmt *Body) {
2311 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2312 }
2313
2314 /// Build a new Objective-C \@autoreleasepool statement.
2315 ///
2316 /// By default, performs semantic analysis to build the new statement.
2317 /// Subclasses may override this routine to provide different behavior.
2318 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2319 Stmt *Body) {
2320 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2321 }
2322
2323 /// Build a new Objective-C fast enumeration statement.
2324 ///
2325 /// By default, performs semantic analysis to build the new statement.
2326 /// Subclasses may override this routine to provide different behavior.
2327 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2328 Stmt *Element,
2329 Expr *Collection,
2330 SourceLocation RParenLoc,
2331 Stmt *Body) {
2332 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2333 Element,
2334 Collection,
2335 RParenLoc);
2336 if (ForEachStmt.isInvalid())
2337 return StmtError();
2338
2339 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2340 }
2341
2342 /// Build a new C++ exception declaration.
2343 ///
2344 /// By default, performs semantic analysis to build the new decaration.
2345 /// Subclasses may override this routine to provide different behavior.
2346 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2347 TypeSourceInfo *Declarator,
2348 SourceLocation StartLoc,
2349 SourceLocation IdLoc,
2350 IdentifierInfo *Id) {
2351 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2352 StartLoc, IdLoc, Id);
2353 if (Var)
2354 getSema().CurContext->addDecl(Var);
2355 return Var;
2356 }
2357
2358 /// Build a new C++ catch statement.
2359 ///
2360 /// By default, performs semantic analysis to build the new statement.
2361 /// Subclasses may override this routine to provide different behavior.
2362 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2363 VarDecl *ExceptionDecl,
2364 Stmt *Handler) {
2365 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2366 Handler));
2367 }
2368
2369 /// Build a new C++ try statement.
2370 ///
2371 /// By default, performs semantic analysis to build the new statement.
2372 /// Subclasses may override this routine to provide different behavior.
2373 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2374 ArrayRef<Stmt *> Handlers) {
2375 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2376 }
2377
2378 /// Build a new C++0x range-based for statement.
2379 ///
2380 /// By default, performs semantic analysis to build the new statement.
2381 /// Subclasses may override this routine to provide different behavior.
2382 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2383 SourceLocation CoawaitLoc, Stmt *Init,
2384 SourceLocation ColonLoc, Stmt *Range,
2385 Stmt *Begin, Stmt *End, Expr *Cond,
2386 Expr *Inc, Stmt *LoopVar,
2387 SourceLocation RParenLoc) {
2388 // If we've just learned that the range is actually an Objective-C
2389 // collection, treat this as an Objective-C fast enumeration loop.
2390 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2391 if (RangeStmt->isSingleDecl()) {
2392 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2393 if (RangeVar->isInvalidDecl())
2394 return StmtError();
2395
2396 Expr *RangeExpr = RangeVar->getInit();
2397 if (!RangeExpr->isTypeDependent() &&
2398 RangeExpr->getType()->isObjCObjectPointerType()) {
2399 // FIXME: Support init-statements in Objective-C++20 ranged for
2400 // statement.
2401 if (Init) {
2402 return SemaRef.Diag(Init->getBeginLoc(),
2403 diag::err_objc_for_range_init_stmt)
2404 << Init->getSourceRange();
2405 }
2406 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2407 RangeExpr, RParenLoc);
2408 }
2409 }
2410 }
2411 }
2412
2413 return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2414 Range, Begin, End, Cond, Inc, LoopVar,
2415 RParenLoc, Sema::BFRK_Rebuild);
2416 }
2417
2418 /// Build a new C++0x range-based for statement.
2419 ///
2420 /// By default, performs semantic analysis to build the new statement.
2421 /// Subclasses may override this routine to provide different behavior.
2422 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2423 bool IsIfExists,
2424 NestedNameSpecifierLoc QualifierLoc,
2425 DeclarationNameInfo NameInfo,
2426 Stmt *Nested) {
2427 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2428 QualifierLoc, NameInfo, Nested);
2429 }
2430
2431 /// Attach body to a C++0x range-based for statement.
2432 ///
2433 /// By default, performs semantic analysis to finish the new statement.
2434 /// Subclasses may override this routine to provide different behavior.
2435 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2436 return getSema().FinishCXXForRangeStmt(ForRange, Body);
2437 }
2438
2439 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2440 Stmt *TryBlock, Stmt *Handler) {
2441 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2442 }
2443
2444 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2445 Stmt *Block) {
2446 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2447 }
2448
2449 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2450 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2451 }
2452
2453 ExprResult RebuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
2454 SourceLocation LParen,
2455 SourceLocation RParen,
2456 TypeSourceInfo *TSI) {
2457 return getSema().BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
2458 }
2459
2460 /// Build a new predefined expression.
2461 ///
2462 /// By default, performs semantic analysis to build the new expression.
2463 /// Subclasses may override this routine to provide different behavior.
2464 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2465 PredefinedExpr::IdentKind IK) {
2466 return getSema().BuildPredefinedExpr(Loc, IK);
2467 }
2468
2469 /// Build a new expression that references a declaration.
2470 ///
2471 /// By default, performs semantic analysis to build the new expression.
2472 /// Subclasses may override this routine to provide different behavior.
2473 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2474 LookupResult &R,
2475 bool RequiresADL) {
2476 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2477 }
2478
2479
2480 /// Build a new expression that references a declaration.
2481 ///
2482 /// By default, performs semantic analysis to build the new expression.
2483 /// Subclasses may override this routine to provide different behavior.
2484 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2485 ValueDecl *VD,
2486 const DeclarationNameInfo &NameInfo,
2487 NamedDecl *Found,
2488 TemplateArgumentListInfo *TemplateArgs) {
2489 CXXScopeSpec SS;
2490 SS.Adopt(QualifierLoc);
2491 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2492 TemplateArgs);
2493 }
2494
2495 /// Build a new expression in parentheses.
2496 ///
2497 /// By default, performs semantic analysis to build the new expression.
2498 /// Subclasses may override this routine to provide different behavior.
2499 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2500 SourceLocation RParen) {
2501 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2502 }
2503
2504 /// Build a new pseudo-destructor expression.
2505 ///
2506 /// By default, performs semantic analysis to build the new expression.
2507 /// Subclasses may override this routine to provide different behavior.
2508 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2509 SourceLocation OperatorLoc,
2510 bool isArrow,
2511 CXXScopeSpec &SS,
2512 TypeSourceInfo *ScopeType,
2513 SourceLocation CCLoc,
2514 SourceLocation TildeLoc,
2515 PseudoDestructorTypeStorage Destroyed);
2516
2517 /// Build a new unary operator expression.
2518 ///
2519 /// By default, performs semantic analysis to build the new expression.
2520 /// Subclasses may override this routine to provide different behavior.
2521 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2522 UnaryOperatorKind Opc,
2523 Expr *SubExpr) {
2524 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2525 }
2526
2527 /// Build a new builtin offsetof expression.
2528 ///
2529 /// By default, performs semantic analysis to build the new expression.
2530 /// Subclasses may override this routine to provide different behavior.
2531 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2532 TypeSourceInfo *Type,
2533 ArrayRef<Sema::OffsetOfComponent> Components,
2534 SourceLocation RParenLoc) {
2535 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2536 RParenLoc);
2537 }
2538
2539 /// Build a new sizeof, alignof or vec_step expression with a
2540 /// type argument.
2541 ///
2542 /// By default, performs semantic analysis to build the new expression.
2543 /// Subclasses may override this routine to provide different behavior.
2544 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2545 SourceLocation OpLoc,
2546 UnaryExprOrTypeTrait ExprKind,
2547 SourceRange R) {
2548 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2549 }
2550
2551 /// Build a new sizeof, alignof or vec step expression with an
2552 /// expression argument.
2553 ///
2554 /// By default, performs semantic analysis to build the new expression.
2555 /// Subclasses may override this routine to provide different behavior.
2556 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2557 UnaryExprOrTypeTrait ExprKind,
2558 SourceRange R) {
2559 ExprResult Result
2560 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2561 if (Result.isInvalid())
2562 return ExprError();
2563
2564 return Result;
2565 }
2566
2567 /// Build a new array subscript expression.
2568 ///
2569 /// By default, performs semantic analysis to build the new expression.
2570 /// Subclasses may override this routine to provide different behavior.
2571 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2572 SourceLocation LBracketLoc,
2573 Expr *RHS,
2574 SourceLocation RBracketLoc) {
2575 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2576 LBracketLoc, RHS,
2577 RBracketLoc);
2578 }
2579
2580 /// Build a new matrix subscript expression.
2581 ///
2582 /// By default, performs semantic analysis to build the new expression.
2583 /// Subclasses may override this routine to provide different behavior.
2584 ExprResult RebuildMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
2585 Expr *ColumnIdx,
2586 SourceLocation RBracketLoc) {
2587 return getSema().CreateBuiltinMatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
2588 RBracketLoc);
2589 }
2590
2591 /// Build a new array section expression.
2592 ///
2593 /// By default, performs semantic analysis to build the new expression.
2594 /// Subclasses may override this routine to provide different behavior.
2595 ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2596 Expr *LowerBound,
2597 SourceLocation ColonLocFirst,
2598 SourceLocation ColonLocSecond,
2599 Expr *Length, Expr *Stride,
2600 SourceLocation RBracketLoc) {
2601 return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2602 ColonLocFirst, ColonLocSecond,
2603 Length, Stride, RBracketLoc);
2604 }
2605
2606 /// Build a new array shaping expression.
2607 ///
2608 /// By default, performs semantic analysis to build the new expression.
2609 /// Subclasses may override this routine to provide different behavior.
2610 ExprResult RebuildOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
2611 SourceLocation RParenLoc,
2612 ArrayRef<Expr *> Dims,
2613 ArrayRef<SourceRange> BracketsRanges) {
2614 return getSema().ActOnOMPArrayShapingExpr(Base, LParenLoc, RParenLoc, Dims,
2615 BracketsRanges);
2616 }
2617
2618 /// Build a new iterator expression.
2619 ///
2620 /// By default, performs semantic analysis to build the new expression.
2621 /// Subclasses may override this routine to provide different behavior.
2622 ExprResult RebuildOMPIteratorExpr(
2623 SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc,
2624 ArrayRef<Sema::OMPIteratorData> Data) {
2625 return getSema().ActOnOMPIteratorExpr(/*Scope=*/nullptr, IteratorKwLoc,
2626 LLoc, RLoc, Data);
2627 }
2628
2629 /// Build a new call expression.
2630 ///
2631 /// By default, performs semantic analysis to build the new expression.
2632 /// Subclasses may override this routine to provide different behavior.
2633 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2634 MultiExprArg Args,
2635 SourceLocation RParenLoc,
2636 Expr *ExecConfig = nullptr) {
2637 return getSema().ActOnCallExpr(
2638 /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc, ExecConfig);
2639 }
2640
2641 ExprResult RebuildCxxSubscriptExpr(Expr *Callee, SourceLocation LParenLoc,
2642 MultiExprArg Args,
2643 SourceLocation RParenLoc) {
2644 return getSema().ActOnArraySubscriptExpr(
11
Calling 'Sema::ActOnArraySubscriptExpr'
2645 /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc);
2646 }
2647
2648 /// Build a new member access expression.
2649 ///
2650 /// By default, performs semantic analysis to build the new expression.
2651 /// Subclasses may override this routine to provide different behavior.
2652 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2653 bool isArrow,
2654 NestedNameSpecifierLoc QualifierLoc,
2655 SourceLocation TemplateKWLoc,
2656 const DeclarationNameInfo &MemberNameInfo,
2657 ValueDecl *Member,
2658 NamedDecl *FoundDecl,
2659 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2660 NamedDecl *FirstQualifierInScope) {
2661 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2662 isArrow);
2663 if (!Member->getDeclName()) {
2664 // We have a reference to an unnamed field. This is always the
2665 // base of an anonymous struct/union member access, i.e. the
2666 // field is always of record type.
2667 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", 2668, __extension__ __PRETTY_FUNCTION__
))
2668 "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", 2668, __extension__ __PRETTY_FUNCTION__
))
;
2669
2670 BaseResult =
2671 getSema().PerformObjectMemberConversion(BaseResult.get(),
2672 QualifierLoc.getNestedNameSpecifier(),
2673 FoundDecl, Member);
2674 if (BaseResult.isInvalid())
2675 return ExprError();
2676 Base = BaseResult.get();
2677
2678 CXXScopeSpec EmptySS;
2679 return getSema().BuildFieldReferenceExpr(
2680 Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2681 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2682 }
2683
2684 CXXScopeSpec SS;
2685 SS.Adopt(QualifierLoc);
2686
2687 Base = BaseResult.get();
2688 QualType BaseType = Base->getType();
2689
2690 if (isArrow && !BaseType->isPointerType())
2691 return ExprError();
2692
2693 // FIXME: this involves duplicating earlier analysis in a lot of
2694 // cases; we should avoid this when possible.
2695 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2696 R.addDecl(FoundDecl);
2697 R.resolveKind();
2698
2699 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2700 SS, TemplateKWLoc,
2701 FirstQualifierInScope,
2702 R, ExplicitTemplateArgs,
2703 /*S*/nullptr);
2704 }
2705
2706 /// Build a new binary operator expression.
2707 ///
2708 /// By default, performs semantic analysis to build the new expression.
2709 /// Subclasses may override this routine to provide different behavior.
2710 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2711 BinaryOperatorKind Opc,
2712 Expr *LHS, Expr *RHS) {
2713 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2714 }
2715
2716 /// Build a new rewritten operator expression.
2717 ///
2718 /// By default, performs semantic analysis to build the new expression.
2719 /// Subclasses may override this routine to provide different behavior.
2720 ExprResult RebuildCXXRewrittenBinaryOperator(
2721 SourceLocation OpLoc, BinaryOperatorKind Opcode,
2722 const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2723 return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2724 RHS, /*RequiresADL*/false);
2725 }
2726
2727 /// Build a new conditional operator expression.
2728 ///
2729 /// By default, performs semantic analysis to build the new expression.
2730 /// Subclasses may override this routine to provide different behavior.
2731 ExprResult RebuildConditionalOperator(Expr *Cond,
2732 SourceLocation QuestionLoc,
2733 Expr *LHS,
2734 SourceLocation ColonLoc,
2735 Expr *RHS) {
2736 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2737 LHS, RHS);
2738 }
2739
2740 /// Build a new C-style cast expression.
2741 ///
2742 /// By default, performs semantic analysis to build the new expression.
2743 /// Subclasses may override this routine to provide different behavior.
2744 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2745 TypeSourceInfo *TInfo,
2746 SourceLocation RParenLoc,
2747 Expr *SubExpr) {
2748 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2749 SubExpr);
2750 }
2751
2752 /// Build a new compound literal expression.
2753 ///
2754 /// By default, performs semantic analysis to build the new expression.
2755 /// Subclasses may override this routine to provide different behavior.
2756 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2757 TypeSourceInfo *TInfo,
2758 SourceLocation RParenLoc,
2759 Expr *Init) {
2760 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2761 Init);
2762 }
2763
2764 /// Build a new extended vector element access expression.
2765 ///
2766 /// By default, performs semantic analysis to build the new expression.
2767 /// Subclasses may override this routine to provide different behavior.
2768 ExprResult RebuildExtVectorElementExpr(Expr *Base,
2769 SourceLocation OpLoc,
2770 SourceLocation AccessorLoc,
2771 IdentifierInfo &Accessor) {
2772
2773 CXXScopeSpec SS;
2774 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2775 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2776 OpLoc, /*IsArrow*/ false,
2777 SS, SourceLocation(),
2778 /*FirstQualifierInScope*/ nullptr,
2779 NameInfo,
2780 /* TemplateArgs */ nullptr,
2781 /*S*/ nullptr);
2782 }
2783
2784 /// Build a new initializer list expression.
2785 ///
2786 /// By default, performs semantic analysis to build the new expression.
2787 /// Subclasses may override this routine to provide different behavior.
2788 ExprResult RebuildInitList(SourceLocation LBraceLoc,
2789 MultiExprArg Inits,
2790 SourceLocation RBraceLoc) {
2791 return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2792 }
2793
2794 /// Build a new designated initializer expression.
2795 ///
2796 /// By default, performs semantic analysis to build the new expression.
2797 /// Subclasses may override this routine to provide different behavior.
2798 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2799 MultiExprArg ArrayExprs,
2800 SourceLocation EqualOrColonLoc,
2801 bool GNUSyntax,
2802 Expr *Init) {
2803 ExprResult Result
2804 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2805 Init);
2806 if (Result.isInvalid())
2807 return ExprError();
2808
2809 return Result;
2810 }
2811
2812 /// Build a new value-initialized expression.
2813 ///
2814 /// By default, builds the implicit value initialization without performing
2815 /// any semantic analysis. Subclasses may override this routine to provide
2816 /// different behavior.
2817 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2818 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2819 }
2820
2821 /// Build a new \c va_arg expression.
2822 ///
2823 /// By default, performs semantic analysis to build the new expression.
2824 /// Subclasses may override this routine to provide different behavior.
2825 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2826 Expr *SubExpr, TypeSourceInfo *TInfo,
2827 SourceLocation RParenLoc) {
2828 return getSema().BuildVAArgExpr(BuiltinLoc,
2829 SubExpr, TInfo,
2830 RParenLoc);
2831 }
2832
2833 /// Build a new expression list in parentheses.
2834 ///
2835 /// By default, performs semantic analysis to build the new expression.
2836 /// Subclasses may override this routine to provide different behavior.
2837 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2838 MultiExprArg SubExprs,
2839 SourceLocation RParenLoc) {
2840 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2841 }
2842
2843 /// Build a new address-of-label expression.
2844 ///
2845 /// By default, performs semantic analysis, using the name of the label
2846 /// rather than attempting to map the label statement itself.
2847 /// Subclasses may override this routine to provide different behavior.
2848 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2849 SourceLocation LabelLoc, LabelDecl *Label) {
2850 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2851 }
2852
2853 /// Build a new GNU statement expression.
2854 ///
2855 /// By default, performs semantic analysis to build the new expression.
2856 /// Subclasses may override this routine to provide different behavior.
2857 ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
2858 SourceLocation RParenLoc, unsigned TemplateDepth) {
2859 return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
2860 TemplateDepth);
2861 }
2862
2863 /// Build a new __builtin_choose_expr expression.
2864 ///
2865 /// By default, performs semantic analysis to build the new expression.
2866 /// Subclasses may override this routine to provide different behavior.
2867 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2868 Expr *Cond, Expr *LHS, Expr *RHS,
2869 SourceLocation RParenLoc) {
2870 return SemaRef.ActOnChooseExpr(BuiltinLoc,
2871 Cond, LHS, RHS,
2872 RParenLoc);
2873 }
2874
2875 /// Build a new generic selection expression.
2876 ///
2877 /// By default, performs semantic analysis to build the new expression.
2878 /// Subclasses may override this routine to provide different behavior.
2879 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2880 SourceLocation DefaultLoc,
2881 SourceLocation RParenLoc,
2882 Expr *ControllingExpr,
2883 ArrayRef<TypeSourceInfo *> Types,
2884 ArrayRef<Expr *> Exprs) {
2885 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2886 ControllingExpr, Types, Exprs);
2887 }
2888
2889 /// Build a new overloaded operator call expression.
2890 ///
2891 /// By default, performs semantic analysis to build the new expression.
2892 /// The semantic analysis provides the behavior of template instantiation,
2893 /// copying with transformations that turn what looks like an overloaded
2894 /// operator call into a use of a builtin operator, performing
2895 /// argument-dependent lookup, etc. Subclasses may override this routine to
2896 /// provide different behavior.
2897 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2898 SourceLocation OpLoc,
2899 Expr *Callee,
2900 Expr *First,
2901 Expr *Second);
2902
2903 /// Build a new C++ "named" cast expression, such as static_cast or
2904 /// reinterpret_cast.
2905 ///
2906 /// By default, this routine dispatches to one of the more-specific routines
2907 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2908 /// Subclasses may override this routine to provide different behavior.
2909 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2910 Stmt::StmtClass Class,
2911 SourceLocation LAngleLoc,
2912 TypeSourceInfo *TInfo,
2913 SourceLocation RAngleLoc,
2914 SourceLocation LParenLoc,
2915 Expr *SubExpr,
2916 SourceLocation RParenLoc) {
2917 switch (Class) {
2918 case Stmt::CXXStaticCastExprClass:
2919 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2920 RAngleLoc, LParenLoc,
2921 SubExpr, RParenLoc);
2922
2923 case Stmt::CXXDynamicCastExprClass:
2924 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2925 RAngleLoc, LParenLoc,
2926 SubExpr, RParenLoc);
2927
2928 case Stmt::CXXReinterpretCastExprClass:
2929 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2930 RAngleLoc, LParenLoc,
2931 SubExpr,
2932 RParenLoc);
2933
2934 case Stmt::CXXConstCastExprClass:
2935 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2936 RAngleLoc, LParenLoc,
2937 SubExpr, RParenLoc);
2938
2939 case Stmt::CXXAddrspaceCastExprClass:
2940 return getDerived().RebuildCXXAddrspaceCastExpr(
2941 OpLoc, LAngleLoc, TInfo, RAngleLoc, LParenLoc, SubExpr, RParenLoc);
2942
2943 default:
2944 llvm_unreachable("Invalid C++ named cast")::llvm::llvm_unreachable_internal("Invalid C++ named cast", "clang/lib/Sema/TreeTransform.h"
, 2944)
;
2945 }
2946 }
2947
2948 /// Build a new C++ static_cast expression.
2949 ///
2950 /// By default, performs semantic analysis to build the new expression.
2951 /// Subclasses may override this routine to provide different behavior.
2952 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2953 SourceLocation LAngleLoc,
2954 TypeSourceInfo *TInfo,
2955 SourceLocation RAngleLoc,
2956 SourceLocation LParenLoc,
2957 Expr *SubExpr,
2958 SourceLocation RParenLoc) {
2959 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2960 TInfo, SubExpr,
2961 SourceRange(LAngleLoc, RAngleLoc),
2962 SourceRange(LParenLoc, RParenLoc));
2963 }
2964
2965 /// Build a new C++ dynamic_cast expression.
2966 ///
2967 /// By default, performs semantic analysis to build the new expression.
2968 /// Subclasses may override this routine to provide different behavior.
2969 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2970 SourceLocation LAngleLoc,
2971 TypeSourceInfo *TInfo,
2972 SourceLocation RAngleLoc,
2973 SourceLocation LParenLoc,
2974 Expr *SubExpr,
2975 SourceLocation RParenLoc) {
2976 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2977 TInfo, SubExpr,
2978 SourceRange(LAngleLoc, RAngleLoc),
2979 SourceRange(LParenLoc, RParenLoc));
2980 }
2981
2982 /// Build a new C++ reinterpret_cast expression.
2983 ///
2984 /// By default, performs semantic analysis to build the new expression.
2985 /// Subclasses may override this routine to provide different behavior.
2986 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2987 SourceLocation LAngleLoc,
2988 TypeSourceInfo *TInfo,
2989 SourceLocation RAngleLoc,
2990 SourceLocation LParenLoc,
2991 Expr *SubExpr,
2992 SourceLocation RParenLoc) {
2993 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2994 TInfo, SubExpr,
2995 SourceRange(LAngleLoc, RAngleLoc),
2996 SourceRange(LParenLoc, RParenLoc));
2997 }
2998
2999 /// Build a new C++ const_cast expression.
3000 ///
3001 /// By default, performs semantic analysis to build the new expression.
3002 /// Subclasses may override this routine to provide different behavior.
3003 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
3004 SourceLocation LAngleLoc,
3005 TypeSourceInfo *TInfo,
3006 SourceLocation RAngleLoc,
3007 SourceLocation LParenLoc,
3008 Expr *SubExpr,
3009 SourceLocation RParenLoc) {
3010 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
3011 TInfo, SubExpr,
3012 SourceRange(LAngleLoc, RAngleLoc),
3013 SourceRange(LParenLoc, RParenLoc));
3014 }
3015
3016 ExprResult
3017 RebuildCXXAddrspaceCastExpr(SourceLocation OpLoc, SourceLocation LAngleLoc,
3018 TypeSourceInfo *TInfo, SourceLocation RAngleLoc,
3019 SourceLocation LParenLoc, Expr *SubExpr,
3020 SourceLocation RParenLoc) {
3021 return getSema().BuildCXXNamedCast(
3022 OpLoc, tok::kw_addrspace_cast, TInfo, SubExpr,
3023 SourceRange(LAngleLoc, RAngleLoc), SourceRange(LParenLoc, RParenLoc));
3024 }
3025
3026 /// Build a new C++ functional-style cast expression.
3027 ///
3028 /// By default, performs semantic analysis to build the new expression.
3029 /// Subclasses may override this routine to provide different behavior.
3030 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
3031 SourceLocation LParenLoc,
3032 Expr *Sub,
3033 SourceLocation RParenLoc,
3034 bool ListInitialization) {
3035 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
3036 MultiExprArg(&Sub, 1), RParenLoc,
3037 ListInitialization);
3038 }
3039
3040 /// Build a new C++ __builtin_bit_cast expression.
3041 ///
3042 /// By default, performs semantic analysis to build the new expression.
3043 /// Subclasses may override this routine to provide different behavior.
3044 ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
3045 TypeSourceInfo *TSI, Expr *Sub,
3046 SourceLocation RParenLoc) {
3047 return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
3048 }
3049
3050 /// Build a new C++ typeid(type) expression.
3051 ///
3052 /// By default, performs semantic analysis to build the new expression.
3053 /// Subclasses may override this routine to provide different behavior.
3054 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3055 SourceLocation TypeidLoc,
3056 TypeSourceInfo *Operand,
3057 SourceLocation RParenLoc) {
3058 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3059 RParenLoc);
3060 }
3061
3062
3063 /// Build a new C++ typeid(expr) expression.
3064 ///
3065 /// By default, performs semantic analysis to build the new expression.
3066 /// Subclasses may override this routine to provide different behavior.
3067 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3068 SourceLocation TypeidLoc,
3069 Expr *Operand,
3070 SourceLocation RParenLoc) {
3071 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3072 RParenLoc);
3073 }
3074
3075 /// Build a new C++ __uuidof(type) expression.
3076 ///
3077 /// By default, performs semantic analysis to build the new expression.
3078 /// Subclasses may override this routine to provide different behavior.
3079 ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3080 TypeSourceInfo *Operand,
3081 SourceLocation RParenLoc) {
3082 return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3083 }
3084
3085 /// Build a new C++ __uuidof(expr) expression.
3086 ///
3087 /// By default, performs semantic analysis to build the new expression.
3088 /// Subclasses may override this routine to provide different behavior.
3089 ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3090 Expr *Operand, SourceLocation RParenLoc) {
3091 return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3092 }
3093
3094 /// Build a new C++ "this" expression.
3095 ///
3096 /// By default, builds a new "this" expression without performing any
3097 /// semantic analysis. Subclasses may override this routine to provide
3098 /// different behavior.
3099 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
3100 QualType ThisType,
3101 bool isImplicit) {
3102 return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
3103 }
3104
3105 /// Build a new C++ throw expression.
3106 ///
3107 /// By default, performs semantic analysis to build the new expression.
3108 /// Subclasses may override this routine to provide different behavior.
3109 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
3110 bool IsThrownVariableInScope) {
3111 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
3112 }
3113
3114 /// Build a new C++ default-argument expression.
3115 ///
3116 /// By default, builds a new default-argument expression, which does not
3117 /// require any semantic analysis. Subclasses may override this routine to
3118 /// provide different behavior.
3119 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
3120 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
3121 getSema().CurContext);
3122 }
3123
3124 /// Build a new C++11 default-initialization expression.
3125 ///
3126 /// By default, builds a new default field initialization expression, which
3127 /// does not require any semantic analysis. Subclasses may override this
3128 /// routine to provide different behavior.
3129 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
3130 FieldDecl *Field) {
3131 return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
3132 getSema().CurContext);
3133 }
3134
3135 /// Build a new C++ zero-initialization expression.
3136 ///
3137 /// By default, performs semantic analysis to build the new expression.
3138 /// Subclasses may override this routine to provide different behavior.
3139 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
3140 SourceLocation LParenLoc,
3141 SourceLocation RParenLoc) {
3142 return getSema().BuildCXXTypeConstructExpr(
3143 TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
3144 }
3145
3146 /// Build a new C++ "new" expression.
3147 ///
3148 /// By default, performs semantic analysis to build the new expression.
3149 /// Subclasses may override this routine to provide different behavior.
3150 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
3151 bool UseGlobal,
3152 SourceLocation PlacementLParen,
3153 MultiExprArg PlacementArgs,
3154 SourceLocation PlacementRParen,
3155 SourceRange TypeIdParens,
3156 QualType AllocatedType,
3157 TypeSourceInfo *AllocatedTypeInfo,
3158 Optional<Expr *> ArraySize,
3159 SourceRange DirectInitRange,
3160 Expr *Initializer) {
3161 return getSema().BuildCXXNew(StartLoc, UseGlobal,
3162 PlacementLParen,
3163 PlacementArgs,
3164 PlacementRParen,
3165 TypeIdParens,
3166 AllocatedType,
3167 AllocatedTypeInfo,
3168 ArraySize,
3169 DirectInitRange,
3170 Initializer);
3171 }
3172
3173 /// Build a new C++ "delete" expression.
3174 ///
3175 /// By default, performs semantic analysis to build the new expression.
3176 /// Subclasses may override this routine to provide different behavior.
3177 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
3178 bool IsGlobalDelete,
3179 bool IsArrayForm,
3180 Expr *Operand) {
3181 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
3182 Operand);
3183 }
3184
3185 /// Build a new type trait expression.
3186 ///
3187 /// By default, performs semantic analysis to build the new expression.
3188 /// Subclasses may override this routine to provide different behavior.
3189 ExprResult RebuildTypeTrait(TypeTrait Trait,
3190 SourceLocation StartLoc,
3191 ArrayRef<TypeSourceInfo *> Args,
3192 SourceLocation RParenLoc) {
3193 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
3194 }
3195
3196 /// Build a new array type trait expression.
3197 ///
3198 /// By default, performs semantic analysis to build the new expression.
3199 /// Subclasses may override this routine to provide different behavior.
3200 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
3201 SourceLocation StartLoc,
3202 TypeSourceInfo *TSInfo,
3203 Expr *DimExpr,
3204 SourceLocation RParenLoc) {
3205 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
3206 }
3207
3208 /// Build a new expression trait expression.
3209 ///
3210 /// By default, performs semantic analysis to build the new expression.
3211 /// Subclasses may override this routine to provide different behavior.
3212 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
3213 SourceLocation StartLoc,
3214 Expr *Queried,
3215 SourceLocation RParenLoc) {
3216 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
3217 }
3218
3219 /// Build a new (previously unresolved) declaration reference
3220 /// expression.
3221 ///
3222 /// By default, performs semantic analysis to build the new expression.
3223 /// Subclasses may override this routine to provide different behavior.
3224 ExprResult RebuildDependentScopeDeclRefExpr(
3225 NestedNameSpecifierLoc QualifierLoc,
3226 SourceLocation TemplateKWLoc,
3227 const DeclarationNameInfo &NameInfo,
3228 const TemplateArgumentListInfo *TemplateArgs,
3229 bool IsAddressOfOperand,
3230 TypeSourceInfo **RecoveryTSI) {
3231 CXXScopeSpec SS;
3232 SS.Adopt(QualifierLoc);
3233
3234 if (TemplateArgs || TemplateKWLoc.isValid())
3235 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
3236 TemplateArgs);
3237
3238 return getSema().BuildQualifiedDeclarationNameExpr(
3239 SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
3240 }
3241
3242 /// Build a new template-id expression.
3243 ///
3244 /// By default, performs semantic analysis to build the new expression.
3245 /// Subclasses may override this routine to provide different behavior.
3246 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
3247 SourceLocation TemplateKWLoc,
3248 LookupResult &R,
3249 bool RequiresADL,
3250 const TemplateArgumentListInfo *TemplateArgs) {
3251 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
3252 TemplateArgs);
3253 }
3254
3255 /// Build a new object-construction expression.
3256 ///
3257 /// By default, performs semantic analysis to build the new expression.
3258 /// Subclasses may override this routine to provide different behavior.
3259 ExprResult RebuildCXXConstructExpr(QualType T,
3260 SourceLocation Loc,
3261 CXXConstructorDecl *Constructor,
3262 bool IsElidable,
3263 MultiExprArg Args,
3264 bool HadMultipleCandidates,
3265 bool ListInitialization,
3266 bool StdInitListInitialization,
3267 bool RequiresZeroInit,
3268 CXXConstructExpr::ConstructionKind ConstructKind,
3269 SourceRange ParenRange) {
3270 // Reconstruct the constructor we originally found, which might be
3271 // different if this is a call to an inherited constructor.
3272 CXXConstructorDecl *FoundCtor = Constructor;
3273 if (Constructor->isInheritingConstructor())
3274 FoundCtor = Constructor->getInheritedConstructor().getConstructor();
3275
3276 SmallVector<Expr *, 8> ConvertedArgs;
3277 if (getSema().CompleteConstructorCall(FoundCtor, T, Args, Loc,
3278 ConvertedArgs))
3279 return ExprError();
3280
3281 return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
3282 IsElidable,
3283 ConvertedArgs,
3284 HadMultipleCandidates,
3285 ListInitialization,
3286 StdInitListInitialization,
3287 RequiresZeroInit, ConstructKind,
3288 ParenRange);
3289 }
3290
3291 /// Build a new implicit construction via inherited constructor
3292 /// expression.
3293 ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
3294 CXXConstructorDecl *Constructor,
3295 bool ConstructsVBase,
3296 bool InheritedFromVBase) {
3297 return new (getSema().Context) CXXInheritedCtorInitExpr(
3298 Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
3299 }
3300
3301 /// Build a new object-construction expression.
3302 ///
3303 /// By default, performs semantic analysis to build the new expression.
3304 /// Subclasses may override this routine to provide different behavior.
3305 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
3306 SourceLocation LParenOrBraceLoc,
3307 MultiExprArg Args,
3308 SourceLocation RParenOrBraceLoc,
3309 bool ListInitialization) {
3310 return getSema().BuildCXXTypeConstructExpr(
3311 TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
3312 }
3313
3314 /// Build a new object-construction expression.
3315 ///
3316 /// By default, performs semantic analysis to build the new expression.
3317 /// Subclasses may override this routine to provide different behavior.
3318 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
3319 SourceLocation LParenLoc,
3320 MultiExprArg Args,
3321 SourceLocation RParenLoc,
3322 bool ListInitialization) {
3323 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
3324 RParenLoc, ListInitialization);
3325 }
3326
3327 /// Build a new member reference expression.
3328 ///
3329 /// By default, performs semantic analysis to build the new expression.
3330 /// Subclasses may override this routine to provide different behavior.
3331 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
3332 QualType BaseType,
3333 bool IsArrow,
3334 SourceLocation OperatorLoc,
3335 NestedNameSpecifierLoc QualifierLoc,
3336 SourceLocation TemplateKWLoc,
3337 NamedDecl *FirstQualifierInScope,
3338 const DeclarationNameInfo &MemberNameInfo,
3339 const TemplateArgumentListInfo *TemplateArgs) {
3340 CXXScopeSpec SS;
3341 SS.Adopt(QualifierLoc);
3342
3343 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3344 OperatorLoc, IsArrow,
3345 SS, TemplateKWLoc,
3346 FirstQualifierInScope,
3347 MemberNameInfo,
3348 TemplateArgs, /*S*/nullptr);
3349 }
3350
3351 /// Build a new member reference expression.
3352 ///
3353 /// By default, performs semantic analysis to build the new expression.
3354 /// Subclasses may override this routine to provide different behavior.
3355 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3356 SourceLocation OperatorLoc,
3357 bool IsArrow,
3358 NestedNameSpecifierLoc QualifierLoc,
3359 SourceLocation TemplateKWLoc,
3360 NamedDecl *FirstQualifierInScope,
3361 LookupResult &R,
3362 const TemplateArgumentListInfo *TemplateArgs) {
3363 CXXScopeSpec SS;
3364 SS.Adopt(QualifierLoc);
3365
3366 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3367 OperatorLoc, IsArrow,
3368 SS, TemplateKWLoc,
3369 FirstQualifierInScope,
3370 R, TemplateArgs, /*S*/nullptr);
3371 }
3372
3373 /// Build a new noexcept expression.
3374 ///
3375 /// By default, performs semantic analysis to build the new expression.
3376 /// Subclasses may override this routine to provide different behavior.
3377 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3378 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3379 }
3380
3381 /// Build a new expression to compute the length of a parameter pack.
3382 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
3383 NamedDecl *Pack,
3384 SourceLocation PackLoc,
3385 SourceLocation RParenLoc,
3386 Optional<unsigned> Length,
3387 ArrayRef<TemplateArgument> PartialArgs) {
3388 return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3389 RParenLoc, Length, PartialArgs);
3390 }
3391
3392 /// Build a new expression representing a call to a source location
3393 /// builtin.
3394 ///
3395 /// By default, performs semantic analysis to build the new expression.
3396 /// Subclasses may override this routine to provide different behavior.
3397 ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3398 QualType ResultTy, SourceLocation BuiltinLoc,
3399 SourceLocation RPLoc,
3400 DeclContext *ParentContext) {
3401 return getSema().BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc,
3402 ParentContext);
3403 }
3404
3405 /// Build a new Objective-C boxed expression.
3406 ///
3407 /// By default, performs semantic analysis to build the new expression.
3408 /// Subclasses may override this routine to provide different behavior.
3409 ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3410 SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3411 NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3412 TemplateArgumentListInfo *TALI) {
3413 CXXScopeSpec SS;
3414 SS.Adopt(NNS);
3415 ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3416 ConceptNameInfo,
3417 FoundDecl,
3418 NamedConcept, TALI);
3419 if (Result.isInvalid())
3420 return ExprError();
3421 return Result;
3422 }
3423
3424 /// \brief Build a new requires expression.
3425 ///
3426 /// By default, performs semantic analysis to build the new expression.
3427 /// Subclasses may override this routine to provide different behavior.
3428 ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3429 RequiresExprBodyDecl *Body,
3430 ArrayRef<ParmVarDecl *> LocalParameters,
3431 ArrayRef<concepts::Requirement *> Requirements,
3432 SourceLocation ClosingBraceLoc) {
3433 return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body,
3434 LocalParameters, Requirements, ClosingBraceLoc);
3435 }
3436
3437 concepts::TypeRequirement *
3438 RebuildTypeRequirement(
3439 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3440 return SemaRef.BuildTypeRequirement(SubstDiag);
3441 }
3442
3443 concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3444 return SemaRef.BuildTypeRequirement(T);
3445 }
3446
3447 concepts::ExprRequirement *
3448 RebuildExprRequirement(
3449 concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3450 SourceLocation NoexceptLoc,
3451 concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3452 return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3453 std::move(Ret));
3454 }
3455
3456 concepts::ExprRequirement *
3457 RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3458 concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3459 return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3460 std::move(Ret));
3461 }
3462
3463 concepts::NestedRequirement *
3464 RebuildNestedRequirement(
3465 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3466 return SemaRef.BuildNestedRequirement(SubstDiag);
3467 }
3468
3469 concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3470 return SemaRef.BuildNestedRequirement(Constraint);
3471 }
3472
3473 /// \brief Build a new Objective-C boxed expression.
3474 ///
3475 /// By default, performs semantic analysis to build the new expression.
3476 /// Subclasses may override this routine to provide different behavior.
3477 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3478 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3479 }
3480
3481 /// Build a new Objective-C array literal.
3482 ///
3483 /// By default, performs semantic analysis to build the new expression.
3484 /// Subclasses may override this routine to provide different behavior.
3485 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3486 Expr **Elements, unsigned NumElements) {
3487 return getSema().BuildObjCArrayLiteral(Range,
3488 MultiExprArg(Elements, NumElements));
3489 }
3490
3491 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3492 Expr *Base, Expr *Key,
3493 ObjCMethodDecl *getterMethod,
3494 ObjCMethodDecl *setterMethod) {
3495 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3496 getterMethod, setterMethod);
3497 }
3498
3499 /// Build a new Objective-C dictionary literal.
3500 ///
3501 /// By default, performs semantic analysis to build the new expression.
3502 /// Subclasses may override this routine to provide different behavior.
3503 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3504 MutableArrayRef<ObjCDictionaryElement> Elements) {
3505 return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3506 }
3507
3508 /// Build a new Objective-C \@encode expression.
3509 ///
3510 /// By default, performs semantic analysis to build the new expression.
3511 /// Subclasses may override this routine to provide different behavior.
3512 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3513 TypeSourceInfo *EncodeTypeInfo,
3514 SourceLocation RParenLoc) {
3515 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3516 }
3517
3518 /// Build a new Objective-C class message.
3519 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3520 Selector Sel,
3521 ArrayRef<SourceLocation> SelectorLocs,
3522 ObjCMethodDecl *Method,
3523 SourceLocation LBracLoc,
3524 MultiExprArg Args,
3525 SourceLocation RBracLoc) {
3526 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3527 ReceiverTypeInfo->getType(),
3528 /*SuperLoc=*/SourceLocation(),
3529 Sel, Method, LBracLoc, SelectorLocs,
3530 RBracLoc, Args);
3531 }
3532
3533 /// Build a new Objective-C instance message.
3534 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3535 Selector Sel,
3536 ArrayRef<SourceLocation> SelectorLocs,
3537 ObjCMethodDecl *Method,
3538 SourceLocation LBracLoc,
3539 MultiExprArg Args,
3540 SourceLocation RBracLoc) {
3541 return SemaRef.BuildInstanceMessage(Receiver,
3542 Receiver->getType(),
3543 /*SuperLoc=*/SourceLocation(),
3544 Sel, Method, LBracLoc, SelectorLocs,
3545 RBracLoc, Args);
3546 }
3547
3548 /// Build a new Objective-C instance/class message to 'super'.
3549 ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3550 Selector Sel,
3551 ArrayRef<SourceLocation> SelectorLocs,
3552 QualType SuperType,
3553 ObjCMethodDecl *Method,
3554 SourceLocation LBracLoc,
3555 MultiExprArg Args,
3556 SourceLocation RBracLoc) {
3557 return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3558 SuperType,
3559 SuperLoc,
3560 Sel, Method, LBracLoc, SelectorLocs,
3561 RBracLoc, Args)
3562 : SemaRef.BuildClassMessage(nullptr,
3563 SuperType,
3564 SuperLoc,
3565 Sel, Method, LBracLoc, SelectorLocs,
3566 RBracLoc, Args);
3567
3568
3569 }
3570
3571 /// Build a new Objective-C ivar reference expression.
3572 ///
3573 /// By default, performs semantic analysis to build the new expression.
3574 /// Subclasses may override this routine to provide different behavior.
3575 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3576 SourceLocation IvarLoc,
3577 bool IsArrow, bool IsFreeIvar) {
3578 CXXScopeSpec SS;
3579 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3580 ExprResult Result = getSema().BuildMemberReferenceExpr(
3581 BaseArg, BaseArg->getType(),
3582 /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3583 /*FirstQualifierInScope=*/nullptr, NameInfo,
3584 /*TemplateArgs=*/nullptr,
3585 /*S=*/nullptr);
3586 if (IsFreeIvar && Result.isUsable())
3587 cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3588 return Result;
3589 }
3590
3591 /// Build a new Objective-C property reference expression.
3592 ///
3593 /// By default, performs semantic analysis to build the new expression.
3594 /// Subclasses may override this routine to provide different behavior.
3595 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3596 ObjCPropertyDecl *Property,
3597 SourceLocation PropertyLoc) {
3598 CXXScopeSpec SS;
3599 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3600 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3601 /*FIXME:*/PropertyLoc,
3602 /*IsArrow=*/false,
3603 SS, SourceLocation(),
3604 /*FirstQualifierInScope=*/nullptr,
3605 NameInfo,
3606 /*TemplateArgs=*/nullptr,
3607 /*S=*/nullptr);
3608 }
3609
3610 /// Build a new Objective-C property reference expression.
3611 ///
3612 /// By default, performs semantic analysis to build the new expression.
3613 /// Subclasses may override this routine to provide different behavior.
3614 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3615 ObjCMethodDecl *Getter,
3616 ObjCMethodDecl *Setter,
3617 SourceLocation PropertyLoc) {
3618 // Since these expressions can only be value-dependent, we do not
3619 // need to perform semantic analysis again.
3620 return Owned(
3621 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3622 VK_LValue, OK_ObjCProperty,
3623 PropertyLoc, Base));
3624 }
3625
3626 /// Build a new Objective-C "isa" expression.
3627 ///
3628 /// By default, performs semantic analysis to build the new expression.
3629 /// Subclasses may override this routine to provide different behavior.
3630 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3631 SourceLocation OpLoc, bool IsArrow) {
3632 CXXScopeSpec SS;
3633 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3634 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3635 OpLoc, IsArrow,
3636 SS, SourceLocation(),
3637 /*FirstQualifierInScope=*/nullptr,
3638 NameInfo,
3639 /*TemplateArgs=*/nullptr,
3640 /*S=*/nullptr);
3641 }
3642
3643 /// Build a new shuffle vector expression.
3644 ///
3645 /// By default, performs semantic analysis to build the new expression.
3646 /// Subclasses may override this routine to provide different behavior.
3647 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3648 MultiExprArg SubExprs,
3649 SourceLocation RParenLoc) {
3650 // Find the declaration for __builtin_shufflevector
3651 const IdentifierInfo &Name
3652 = SemaRef.Context.Idents.get("__builtin_shufflevector");
3653 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3654 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3655 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", 3655, __extension__ __PRETTY_FUNCTION__
))
;
3656
3657 // Build a reference to the __builtin_shufflevector builtin
3658 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3659 Expr *Callee = new (SemaRef.Context)
3660 DeclRefExpr(SemaRef.Context, Builtin, false,
3661 SemaRef.Context.BuiltinFnTy, VK_PRValue, BuiltinLoc);
3662 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3663 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3664 CK_BuiltinFnToFnPtr).get();
3665
3666 // Build the CallExpr
3667 ExprResult TheCall = CallExpr::Create(
3668 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3669 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc,
3670 FPOptionsOverride());
3671
3672 // Type-check the __builtin_shufflevector expression.
3673 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3674 }
3675
3676 /// Build a new convert vector expression.
3677 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3678 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3679 SourceLocation RParenLoc) {
3680 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3681 BuiltinLoc, RParenLoc);
3682 }
3683
3684 /// Build a new template argument pack expansion.
3685 ///
3686 /// By default, performs semantic analysis to build a new pack expansion
3687 /// for a template argument. Subclasses may override this routine to provide
3688 /// different behavior.
3689 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3690 SourceLocation EllipsisLoc,
3691 Optional<unsigned> NumExpansions) {
3692 switch (Pattern.getArgument().getKind()) {
3693 case TemplateArgument::Expression: {
3694 ExprResult Result
3695 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3696 EllipsisLoc, NumExpansions);
3697 if (Result.isInvalid())
3698 return TemplateArgumentLoc();
3699
3700 return TemplateArgumentLoc(Result.get(), Result.get());
3701 }
3702
3703 case TemplateArgument::Template:
3704 return TemplateArgumentLoc(
3705 SemaRef.Context,
3706 TemplateArgument(Pattern.getArgument().getAsTemplate(),
3707 NumExpansions),
3708 Pattern.getTemplateQualifierLoc(), Pattern.getTemplateNameLoc(),
3709 EllipsisLoc);
3710
3711 case TemplateArgument::Null:
3712 case TemplateArgument::Integral:
3713 case TemplateArgument::Declaration:
3714 case TemplateArgument::Pack:
3715 case TemplateArgument::TemplateExpansion:
3716 case TemplateArgument::NullPtr:
3717 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", 3717)
;
3718
3719 case TemplateArgument::Type:
3720 if (TypeSourceInfo *Expansion
3721 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3722 EllipsisLoc,
3723 NumExpansions))
3724 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3725 Expansion);
3726 break;
3727 }
3728
3729 return TemplateArgumentLoc();
3730 }
3731
3732 /// Build a new expression pack expansion.
3733 ///
3734 /// By default, performs semantic analysis to build a new pack expansion
3735 /// for an expression. Subclasses may override this routine to provide
3736 /// different behavior.
3737 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3738 Optional<unsigned> NumExpansions) {
3739 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3740 }
3741
3742 /// Build a new C++1z fold-expression.
3743 ///
3744 /// By default, performs semantic analysis in order to build a new fold
3745 /// expression.
3746 ExprResult RebuildCXXFoldExpr(UnresolvedLookupExpr *ULE,
3747 SourceLocation LParenLoc, Expr *LHS,
3748 BinaryOperatorKind Operator,
3749 SourceLocation EllipsisLoc, Expr *RHS,
3750 SourceLocation RParenLoc,
3751 Optional<unsigned> NumExpansions) {
3752 return getSema().BuildCXXFoldExpr(ULE, LParenLoc, LHS, Operator,
3753 EllipsisLoc, RHS, RParenLoc,
3754 NumExpansions);
3755 }
3756
3757 /// Build an empty C++1z fold-expression with the given operator.
3758 ///
3759 /// By default, produces the fallback value for the fold-expression, or
3760 /// produce an error if there is no fallback value.
3761 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3762 BinaryOperatorKind Operator) {
3763 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3764 }
3765
3766 /// Build a new atomic operation expression.
3767 ///
3768 /// By default, performs semantic analysis to build the new expression.
3769 /// Subclasses may override this routine to provide different behavior.
3770 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3771 AtomicExpr::AtomicOp Op,
3772 SourceLocation RParenLoc) {
3773 // Use this for all of the locations, since we don't know the difference
3774 // between the call and the expr at this point.
3775 SourceRange Range{BuiltinLoc, RParenLoc};
3776 return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3777 Sema::AtomicArgumentOrder::AST);
3778 }
3779
3780 ExprResult RebuildRecoveryExpr(SourceLocation BeginLoc, SourceLocation EndLoc,
3781 ArrayRef<Expr *> SubExprs, QualType Type) {
3782 return getSema().CreateRecoveryExpr(BeginLoc, EndLoc, SubExprs, Type);
3783 }
3784
3785private:
3786 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3787 QualType ObjectType,
3788 NamedDecl *FirstQualifierInScope,
3789 CXXScopeSpec &SS);
3790
3791 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3792 QualType ObjectType,
3793 NamedDecl *FirstQualifierInScope,
3794 CXXScopeSpec &SS);
3795
3796 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3797 NamedDecl *FirstQualifierInScope,
3798 CXXScopeSpec &SS);
3799
3800 QualType TransformDependentNameType(TypeLocBuilder &TLB,
3801 DependentNameTypeLoc TL,
3802 bool DeducibleTSTContext);
3803};
3804
3805template <typename Derived>
3806StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3807 if (!S)
3808 return S;
3809
3810 switch (S->getStmtClass()) {
3811 case Stmt::NoStmtClass: break;
3812
3813 // Transform individual statement nodes
3814 // Pass SDK into statements that can produce a value
3815#define STMT(Node, Parent) \
3816 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3817#define VALUESTMT(Node, Parent) \
3818 case Stmt::Node##Class: \
3819 return getDerived().Transform##Node(cast<Node>(S), SDK);
3820#define ABSTRACT_STMT(Node)
3821#define EXPR(Node, Parent)
3822#include "clang/AST/StmtNodes.inc"
3823
3824 // Transform expressions by calling TransformExpr.
3825#define STMT(Node, Parent)
3826#define ABSTRACT_STMT(Stmt)
3827#define EXPR(Node, Parent) case Stmt::Node##Class:
3828#include "clang/AST/StmtNodes.inc"
3829 {
3830 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3831
3832 if (SDK == SDK_StmtExprResult)
3833 E = getSema().ActOnStmtExprResult(E);
3834 return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3835 }
3836 }
3837
3838 return S;
3839}
3840
3841template<typename Derived>
3842OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3843 if (!S)
3844 return S;
3845
3846 switch (S->getClauseKind()) {
3847 default: break;
3848 // Transform individual clause nodes
3849#define GEN_CLANG_CLAUSE_CLASS
3850#define CLAUSE_CLASS(Enum, Str, Class) \
3851 case Enum: \
3852 return getDerived().Transform##Class(cast<Class>(S));
3853#include "llvm/Frontend/OpenMP/OMP.inc"
3854 }
3855
3856 return S;
3857}
3858
3859
3860template<typename Derived>
3861ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3862 if (!E)
3863 return E;
3864
3865 switch (E->getStmtClass()) {
3866 case Stmt::NoStmtClass: break;
3867#define STMT(Node, Parent) case Stmt::Node##Class: break;
3868#define ABSTRACT_STMT(Stmt)
3869#define EXPR(Node, Parent) \
3870 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3871#include "clang/AST/StmtNodes.inc"
3872 }
3873
3874 return E;
3875}
3876
3877template<typename Derived>
3878ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3879 bool NotCopyInit) {
3880 // Initializers are instantiated like expressions, except that various outer
3881 // layers are stripped.
3882 if (!Init)
3883 return Init;
3884
3885 if (auto *FE = dyn_cast<FullExpr>(Init))
3886 Init = FE->getSubExpr();
3887
3888 if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init)) {
3889 OpaqueValueExpr *OVE = AIL->getCommonExpr();
3890 Init = OVE->getSourceExpr();
3891 }
3892
3893 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3894 Init = MTE->getSubExpr();
3895
3896 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3897 Init = Binder->getSubExpr();
3898
3899 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3900 Init = ICE->getSubExprAsWritten();
3901
3902 if (CXXStdInitializerListExpr *ILE =
3903 dyn_cast<CXXStdInitializerListExpr>(Init))
3904 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3905
3906 // If this is copy-initialization, we only need to reconstruct
3907 // InitListExprs. Other forms of copy-initialization will be a no-op if
3908 // the initializer is already the right type.
3909 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3910 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3911 return getDerived().TransformExpr(Init);
3912
3913 // Revert value-initialization back to empty parens.
3914 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3915 SourceRange Parens = VIE->getSourceRange();
3916 return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3917 Parens.getEnd());
3918 }
3919
3920 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3921 if (isa<ImplicitValueInitExpr>(Init))
3922 return getDerived().RebuildParenListExpr(SourceLocation(), None,
3923 SourceLocation());
3924
3925 // Revert initialization by constructor back to a parenthesized or braced list
3926 // of expressions. Any other form of initializer can just be reused directly.
3927 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3928 return getDerived().TransformExpr(Init);
3929
3930 // If the initialization implicitly converted an initializer list to a
3931 // std::initializer_list object, unwrap the std::initializer_list too.
3932 if (Construct && Construct->isStdInitListInitialization())
3933 return TransformInitializer(Construct->getArg(0), NotCopyInit);
3934
3935 // Enter a list-init context if this was list initialization.
3936 EnterExpressionEvaluationContext Context(
3937 getSema(), EnterExpressionEvaluationContext::InitList,
3938 Construct->isListInitialization());
3939
3940 SmallVector<Expr*, 8> NewArgs;
3941 bool ArgChanged = false;
3942 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3943 /*IsCall*/true, NewArgs, &ArgChanged))
3944 return ExprError();
3945
3946 // If this was list initialization, revert to syntactic list form.
3947 if (Construct->isListInitialization())
3948 return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3949 Construct->getEndLoc());
3950
3951 // Build a ParenListExpr to represent anything else.
3952 SourceRange Parens = Construct->getParenOrBraceRange();
3953 if (Parens.isInvalid()) {
3954 // This was a variable declaration's initialization for which no initializer
3955 // was specified.
3956 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", 3957, __extension__ __PRETTY_FUNCTION__
))
3957 "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", 3957, __extension__ __PRETTY_FUNCTION__
))
;
3958 return ExprEmpty();
3959 }
3960 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3961 Parens.getEnd());
3962}
3963
3964template<typename Derived>
3965bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3966 unsigned NumInputs,
3967 bool IsCall,
3968 SmallVectorImpl<Expr *> &Outputs,
3969 bool *ArgChanged) {
3970 for (unsigned I = 0; I != NumInputs; ++I) {
3971 // If requested, drop call arguments that need to be dropped.
3972 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3973 if (ArgChanged)
3974 *ArgChanged = true;
3975
3976 break;
3977 }
3978
3979 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3980 Expr *Pattern = Expansion->getPattern();
3981
3982 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3983 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3984 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", 3984, __extension__ __PRETTY_FUNCTION__
))
;
3985
3986 // Determine whether the set of unexpanded parameter packs can and should
3987 // be expanded.
3988 bool Expand = true;
3989 bool RetainExpansion = false;
3990 Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3991 Optional<unsigned> NumExpansions = OrigNumExpansions;
3992 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3993 Pattern->getSourceRange(),
3994 Unexpanded,
3995 Expand, RetainExpansion,
3996 NumExpansions))
3997 return true;
3998
3999 if (!Expand) {
4000 // The transform has determined that we should perform a simple
4001 // transformation on the pack expansion, producing another pack
4002 // expansion.
4003 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4004 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
4005 if (OutPattern.isInvalid())
4006 return true;
4007
4008 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
4009 Expansion->getEllipsisLoc(),
4010 NumExpansions);
4011 if (Out.isInvalid())
4012 return true;
4013
4014 if (ArgChanged)
4015 *ArgChanged = true;
4016 Outputs.push_back(Out.get());
4017 continue;
4018 }
4019
4020 // Record right away that the argument was changed. This needs
4021 // to happen even if the array expands to nothing.
4022 if (ArgChanged) *ArgChanged = true;
4023
4024 // The transform has determined that we should perform an elementwise
4025 // expansion of the pattern. Do so.
4026 for (unsigned I = 0; I != *NumExpansions; ++I) {
4027 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4028 ExprResult Out = getDerived().TransformExpr(Pattern);
4029 if (Out.isInvalid())
4030 return true;
4031
4032 if (Out.get()->containsUnexpandedParameterPack()) {
4033 Out = getDerived().RebuildPackExpansion(
4034 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4035 if (Out.isInvalid())
4036 return true;
4037 }
4038
4039 Outputs.push_back(Out.get());
4040 }
4041
4042 // If we're supposed to retain a pack expansion, do so by temporarily
4043 // forgetting the partially-substituted parameter pack.
4044 if (RetainExpansion) {
4045 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4046
4047 ExprResult Out = getDerived().TransformExpr(Pattern);
4048 if (Out.isInvalid())
4049 return true;
4050
4051 Out = getDerived().RebuildPackExpansion(
4052 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4053 if (Out.isInvalid())
4054 return true;
4055
4056 Outputs.push_back(Out.get());
4057 }
4058
4059 continue;
4060 }
4061
4062 ExprResult Result =
4063 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
4064 : getDerived().TransformExpr(Inputs[I]);
4065 if (Result.isInvalid())
4066 return true;
4067
4068 if (Result.get() != Inputs[I] && ArgChanged)
4069 *ArgChanged = true;
4070
4071 Outputs.push_back(Result.get());
4072 }
4073
4074 return false;
4075}
4076
4077template <typename Derived>
4078Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
4079 SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
4080 if (Var) {
4081 VarDecl *ConditionVar = cast_or_null<VarDecl>(
4082 getDerived().TransformDefinition(Var->getLocation(), Var));
4083
4084 if (!ConditionVar)
4085 return Sema::ConditionError();
4086
4087 return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
4088 }
4089
4090 if (Expr) {
4091 ExprResult CondExpr = getDerived().TransformExpr(Expr);
4092
4093 if (CondExpr.isInvalid())
4094 return Sema::ConditionError();
4095
4096 return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind,
4097 /*MissingOK=*/true);
4098 }
4099
4100 return Sema::ConditionResult();
4101}
4102
4103template <typename Derived>
4104NestedNameSpecifierLoc TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
4105 NestedNameSpecifierLoc NNS, QualType ObjectType,
4106 NamedDecl *FirstQualifierInScope) {
4107 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
4108 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
4109 Qualifier = Qualifier.getPrefix())
4110 Qualifiers.push_back(Qualifier);
4111
4112 CXXScopeSpec SS;
4113 while (!Qualifiers.empty()) {
4114 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
4115 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
4116
4117 switch (QNNS->getKind()) {
4118 case NestedNameSpecifier::Identifier: {
4119 Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
4120 Q.getLocalBeginLoc(), Q.getLocalEndLoc(),
4121 ObjectType);
4122 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
4123 SS, FirstQualifierInScope, false))
4124 return NestedNameSpecifierLoc();
4125 break;
4126 }
4127
4128 case NestedNameSpecifier::Namespace: {
4129 NamespaceDecl *NS =
4130 cast_or_null<NamespaceDecl>(getDerived().TransformDecl(
4131 Q.getLocalBeginLoc(), QNNS->getAsNamespace()));
4132 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
4133 break;
4134 }
4135
4136 case NestedNameSpecifier::NamespaceAlias: {
4137 NamespaceAliasDecl *Alias =
4138 cast_or_null<NamespaceAliasDecl>(getDerived().TransformDecl(
4139 Q.getLocalBeginLoc(), QNNS->getAsNamespaceAlias()));
4140 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
4141 Q.getLocalEndLoc());
4142 break;
4143 }
4144
4145 case NestedNameSpecifier::Global:
4146 // There is no meaningful transformation that one could perform on the
4147 // global scope.
4148 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
4149 break;
4150
4151 case NestedNameSpecifier::Super: {
4152 CXXRecordDecl *RD =
4153 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
4154 SourceLocation(), QNNS->getAsRecordDecl()));
4155 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
4156 break;
4157 }
4158
4159 case NestedNameSpecifier::TypeSpecWithTemplate:
4160 case NestedNameSpecifier::TypeSpec: {
4161 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
4162 FirstQualifierInScope, SS);
4163
4164 if (!TL)
4165 return NestedNameSpecifierLoc();
4166
4167 if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
4168 (SemaRef.getLangOpts().CPlusPlus11 &&
4169 TL.getType()->isEnumeralType())) {
4170 assert(!TL.getType().hasLocalQualifiers() &&(static_cast <bool> (!TL.getType().hasLocalQualifiers()
&& "Can't get cv-qualifiers here") ? void (0) : __assert_fail
("!TL.getType().hasLocalQualifiers() && \"Can't get cv-qualifiers here\""
, "clang/lib/Sema/TreeTransform.h", 4171, __extension__ __PRETTY_FUNCTION__
))
4171 "Can't get cv-qualifiers here")(static_cast <bool> (!TL.getType().hasLocalQualifiers()
&& "Can't get cv-qualifiers here") ? void (0) : __assert_fail
("!TL.getType().hasLocalQualifiers() && \"Can't get cv-qualifiers here\""
, "clang/lib/Sema/TreeTransform.h", 4171, __extension__ __PRETTY_FUNCTION__
))
;
4172 if (TL.getType()->isEnumeralType())
4173 SemaRef.Diag(TL.getBeginLoc(),
4174 diag::warn_cxx98_compat_enum_nested_name_spec);
4175 SS.Extend(SemaRef.Context, /*FIXME:*/ SourceLocation(), TL,
4176 Q.getLocalEndLoc());
4177 break;
4178 }
4179 // If the nested-name-specifier is an invalid type def, don't emit an
4180 // error because a previous error should have already been emitted.
4181 TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
4182 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
4183 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
4184 << TL.getType() << SS.getRange();
4185 }
4186 return NestedNameSpecifierLoc();
4187 }
4188 }
4189
4190 // The qualifier-in-scope and object type only apply to the leftmost entity.
4191 FirstQualifierInScope = nullptr;
4192 ObjectType = QualType();
4193 }
4194
4195 // Don't rebuild the nested-name-specifier if we don't have to.
4196 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
4197 !getDerived().AlwaysRebuild())
4198 return NNS;
4199
4200 // If we can re-use the source-location data from the original
4201 // nested-name-specifier, do so.
4202 if (SS.location_size() == NNS.getDataLength() &&
4203 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
4204 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
4205
4206 // Allocate new nested-name-specifier location information.
4207 return SS.getWithLocInContext(SemaRef.Context);
4208}
4209
4210template<typename Derived>
4211DeclarationNameInfo
4212TreeTransform<Derived>
4213::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
4214 DeclarationName Name = NameInfo.getName();
4215 if (!Name)
4216 return DeclarationNameInfo();
4217
4218 switch (Name.getNameKind()) {
4219 case DeclarationName::Identifier:
4220 case DeclarationName::ObjCZeroArgSelector:
4221 case DeclarationName::ObjCOneArgSelector:
4222 case DeclarationName::ObjCMultiArgSelector:
4223 case DeclarationName::CXXOperatorName:
4224 case DeclarationName::CXXLiteralOperatorName:
4225 case DeclarationName::CXXUsingDirective:
4226 return NameInfo;
4227
4228 case DeclarationName::CXXDeductionGuideName: {
4229 TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
4230 TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
4231 getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
4232 if (!NewTemplate)
4233 return DeclarationNameInfo();
4234
4235 DeclarationNameInfo NewNameInfo(NameInfo);
4236 NewNameInfo.setName(
4237 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
4238 return NewNameInfo;
4239 }
4240
4241 case DeclarationName::CXXConstructorName:
4242 case DeclarationName::CXXDestructorName:
4243 case DeclarationName::CXXConversionFunctionName: {
4244 TypeSourceInfo *NewTInfo;
4245 CanQualType NewCanTy;
4246 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
4247 NewTInfo = getDerived().TransformType(OldTInfo);
4248 if (!NewTInfo)
4249 return DeclarationNameInfo();
4250 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
4251 }
4252 else {
4253 NewTInfo = nullptr;
4254 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
4255 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
4256 if (NewT.isNull())
4257 return DeclarationNameInfo();
4258 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
4259 }
4260
4261 DeclarationName NewName
4262 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
4263 NewCanTy);
4264 DeclarationNameInfo NewNameInfo(NameInfo);
4265 NewNameInfo.setName(NewName);
4266 NewNameInfo.setNamedTypeInfo(NewTInfo);
4267 return NewNameInfo;
4268 }
4269 }
4270
4271 llvm_unreachable("Unknown name kind.")::llvm::llvm_unreachable_internal("Unknown name kind.", "clang/lib/Sema/TreeTransform.h"
, 4271)
;
4272}
4273
4274template<typename Derived>
4275TemplateName
4276TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
4277 TemplateName Name,
4278 SourceLocation NameLoc,
4279 QualType ObjectType,
4280 NamedDecl *FirstQualifierInScope,
4281 bool AllowInjectedClassName) {
4282 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
4283 TemplateDecl *Template = QTN->getTemplateDecl();
4284 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", 4284, __extension__ __PRETTY_FUNCTION__
))
;
4285
4286 TemplateDecl *TransTemplate
4287 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4288 Template));
4289 if (!TransTemplate)
4290 return TemplateName();
4291
4292 if (!getDerived().AlwaysRebuild() &&
4293 SS.getScopeRep() == QTN->getQualifier() &&
4294 TransTemplate == Template)
4295 return Name;
4296
4297 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
4298 TransTemplate);
4299 }
4300
4301 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
4302 if (SS.getScopeRep()) {
4303 // These apply to the scope specifier, not the template.
4304 ObjectType = QualType();
4305 FirstQualifierInScope = nullptr;
4306 }
4307
4308 if (!getDerived().AlwaysRebuild() &&
4309 SS.getScopeRep() == DTN->getQualifier() &&
4310 ObjectType.isNull())
4311 return Name;
4312
4313 // FIXME: Preserve the location of the "template" keyword.
4314 SourceLocation TemplateKWLoc = NameLoc;
4315
4316 if (DTN->isIdentifier()) {
4317 return getDerived().RebuildTemplateName(SS,
4318 TemplateKWLoc,
4319 *DTN->getIdentifier(),
4320 NameLoc,
4321 ObjectType,
4322 FirstQualifierInScope,
4323 AllowInjectedClassName);
4324 }
4325
4326 return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
4327 DTN->getOperator(), NameLoc,
4328 ObjectType, AllowInjectedClassName);
4329 }
4330
4331 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4332 TemplateDecl *TransTemplate
4333 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4334 Template));
4335 if (!TransTemplate)
4336 return TemplateName();
4337
4338 if (!getDerived().AlwaysRebuild() &&
4339 TransTemplate == Template)
4340 return Name;
4341
4342 return TemplateName(TransTemplate);
4343 }
4344
4345 if (SubstTemplateTemplateParmPackStorage *SubstPack
4346 = Name.getAsSubstTemplateTemplateParmPack()) {
4347 TemplateTemplateParmDecl *TransParam
4348 = cast_or_null<TemplateTemplateParmDecl>(
4349 getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
4350 if (!TransParam)
4351 return TemplateName();
4352
4353 if (!getDerived().AlwaysRebuild() &&
4354 TransParam == SubstPack->getParameterPack())
4355 return Name;
4356
4357 return getDerived().RebuildTemplateName(TransParam,
4358 SubstPack->getArgumentPack());
4359 }
4360
4361 // These should be getting filtered out before they reach the AST.
4362 llvm_unreachable("overloaded function decl survived to here")::llvm::llvm_unreachable_internal("overloaded function decl survived to here"
, "clang/lib/Sema/TreeTransform.h", 4362)
;
4363}
4364
4365template<typename Derived>
4366void TreeTransform<Derived>::InventTemplateArgumentLoc(
4367 const TemplateArgument &Arg,
4368 TemplateArgumentLoc &Output) {
4369 Output = getSema().getTrivialTemplateArgumentLoc(
4370 Arg, QualType(), getDerived().getBaseLocation());
4371}
4372
4373template <typename Derived>
4374bool TreeTransform<Derived>::TransformTemplateArgument(
4375 const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
4376 bool Uneval) {
4377 const TemplateArgument &Arg = Input.getArgument();
4378 switch (Arg.getKind()) {
4379 case TemplateArgument::Null:
4380 case TemplateArgument::Pack:
4381 llvm_unreachable("Unexpected TemplateArgument")::llvm::llvm_unreachable_internal("Unexpected TemplateArgument"
, "clang/lib/Sema/TreeTransform.h", 4381)
;
4382
4383 case TemplateArgument::Integral:
4384 case TemplateArgument::NullPtr:
4385 case TemplateArgument::Declaration: {
4386 // Transform a resolved template argument straight to a resolved template
4387 // argument. We get here when substituting into an already-substituted
4388 // template type argument during concept satisfaction checking.
4389 QualType T = Arg.getNonTypeTemplateArgumentType();
4390 QualType NewT = getDerived().TransformType(T);
4391 if (NewT.isNull())
4392 return true;
4393
4394 ValueDecl *D = Arg.getKind() == TemplateArgument::Declaration
4395 ? Arg.getAsDecl()
4396 : nullptr;
4397 ValueDecl *NewD = D ? cast_or_null<ValueDecl>(getDerived().TransformDecl(
4398 getDerived().getBaseLocation(), D))
4399 : nullptr;
4400 if (D && !NewD)
4401 return true;
4402
4403 if (NewT == T && D == NewD)
4404 Output = Input;
4405 else if (Arg.getKind() == TemplateArgument::Integral)
4406 Output = TemplateArgumentLoc(
4407 TemplateArgument(getSema().Context, Arg.getAsIntegral(), NewT),
4408 TemplateArgumentLocInfo());
4409 else if (Arg.getKind() == TemplateArgument::NullPtr)
4410 Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true),
4411 TemplateArgumentLocInfo());
4412 else
4413 Output = TemplateArgumentLoc(TemplateArgument(NewD, NewT),
4414 TemplateArgumentLocInfo());
4415
4416 return false;
4417 }
4418
4419 case TemplateArgument::Type: {
4420 TypeSourceInfo *DI = Input.getTypeSourceInfo();
4421 if (!DI)
4422 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4423
4424 DI = getDerived().TransformType(DI);
4425 if (!DI)
4426 return true;
4427
4428 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4429 return false;
4430 }
4431
4432 case TemplateArgument::Template: {
4433 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4434 if (QualifierLoc) {
4435 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4436 if (!QualifierLoc)
4437 return true;
4438 }
4439
4440 CXXScopeSpec SS;
4441 SS.Adopt(QualifierLoc);
4442 TemplateName Template = getDerived().TransformTemplateName(
4443 SS, Arg.getAsTemplate(), Input.getTemplateNameLoc());
4444 if (Template.isNull())
4445 return true;
4446
4447 Output = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template),
4448 QualifierLoc, Input.getTemplateNameLoc());
4449 return false;
4450 }
4451
4452 case TemplateArgument::TemplateExpansion:
4453 llvm_unreachable("Caller should expand pack expansions")::llvm::llvm_unreachable_internal("Caller should expand pack expansions"
, "clang/lib/Sema/TreeTransform.h", 4453)
;
4454
4455 case TemplateArgument::Expression: {
4456 // Template argument expressions are constant expressions.
4457 EnterExpressionEvaluationContext Unevaluated(
4458 getSema(),
4459 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4460 : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4461 /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4462 Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4463
4464 Expr *InputExpr = Input.getSourceExpression();
4465 if (!InputExpr)
4466 InputExpr = Input.getArgument().getAsExpr();
4467
4468 ExprResult E = getDerived().TransformExpr(InputExpr);
4469 E = SemaRef.ActOnConstantExpression(E);
4470 if (E.isInvalid())
4471 return true;
4472 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4473 return false;
4474 }
4475 }
4476
4477 // Work around bogus GCC warning
4478 return true;
4479}
4480
4481/// Iterator adaptor that invents template argument location information
4482/// for each of the template arguments in its underlying iterator.
4483template<typename Derived, typename InputIterator>
4484class TemplateArgumentLocInventIterator {
4485 TreeTransform<Derived> &Self;
4486 InputIterator Iter;
4487
4488public:
4489 typedef TemplateArgumentLoc value_type;
4490 typedef TemplateArgumentLoc reference;
4491 typedef typename std::iterator_traits<InputIterator>::difference_type
4492 difference_type;
4493 typedef std::input_iterator_tag iterator_category;
4494
4495 class pointer {
4496 TemplateArgumentLoc Arg;
4497
4498 public:
4499 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4500
4501 const TemplateArgumentLoc *operator->() const { return &Arg; }
4502 };
4503
4504 TemplateArgumentLocInventIterator() { }
4505
4506 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4507 InputIterator Iter)
4508 : Self(Self), Iter(Iter) { }
4509
4510 TemplateArgumentLocInventIterator &operator++() {
4511 ++Iter;
4512 return *this;
4513 }
4514
4515 TemplateArgumentLocInventIterator operator++(int) {
4516 TemplateArgumentLocInventIterator Old(*this);
4517 ++(*this);
4518 return Old;
4519 }
4520
4521 reference operator*() const {
4522 TemplateArgumentLoc Result;
4523 Self.InventTemplateArgumentLoc(*Iter, Result);
4524 return Result;
4525 }
4526
4527 pointer operator->() const { return pointer(**this); }
4528
4529 friend bool operator==(const TemplateArgumentLocInventIterator &X,
4530 const TemplateArgumentLocInventIterator &Y) {
4531 return X.Iter == Y.Iter;
4532 }
4533
4534 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4535 const TemplateArgumentLocInventIterator &Y) {
4536 return X.Iter != Y.Iter;
4537 }
4538};
4539
4540template<typename Derived>
4541template<typename InputIterator>
4542bool TreeTransform<Derived>::TransformTemplateArguments(
4543 InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4544 bool Uneval) {
4545 for (; First != Last; ++First) {
4546 TemplateArgumentLoc Out;
4547 TemplateArgumentLoc In = *First;
4548
4549 if (In.getArgument().getKind() == TemplateArgument::Pack) {
4550 // Unpack argument packs, which we translate them into separate
4551 // arguments.
4552 // FIXME: We could do much better if we could guarantee that the
4553 // TemplateArgumentLocInfo for the pack expansion would be usable for
4554 // all of the template arguments in the argument pack.
4555 typedef TemplateArgumentLocInventIterator<Derived,
4556 TemplateArgument::pack_iterator>
4557 PackLocIterator;
4558 if (TransformTemplateArguments(PackLocIterator(*this,
4559 In.getArgument().pack_begin()),
4560 PackLocIterator(*this,
4561 In.getArgument().pack_end()),
4562 Outputs, Uneval))
4563 return true;
4564
4565 continue;
4566 }
4567
4568 if (In.getArgument().isPackExpansion()) {
4569 // We have a pack expansion, for which we will be substituting into
4570 // the pattern.
4571 SourceLocation Ellipsis;
4572 Optional<unsigned> OrigNumExpansions;
4573 TemplateArgumentLoc Pattern
4574 = getSema().getTemplateArgumentPackExpansionPattern(
4575 In, Ellipsis, OrigNumExpansions);
4576
4577 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4578 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4579 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", 4579, __extension__ __PRETTY_FUNCTION__
))
;
4580
4581 // Determine whether the set of unexpanded parameter packs can and should
4582 // be expanded.
4583 bool Expand = true;
4584 bool RetainExpansion = false;
4585 Optional<unsigned> NumExpansions = OrigNumExpansions;
4586 if (getDerived().TryExpandParameterPacks(Ellipsis,
4587 Pattern.getSourceRange(),
4588 Unexpanded,
4589 Expand,
4590 RetainExpansion,
4591 NumExpansions))
4592 return true;
4593
4594 if (!Expand) {
4595 // The transform has determined that we should perform a simple
4596 // transformation on the pack expansion, producing another pack
4597 // expansion.
4598 TemplateArgumentLoc OutPattern;
4599 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4600 if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4601 return true;
4602
4603 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4604 NumExpansions);
4605 if (Out.getArgument().isNull())
4606 return true;
4607
4608 Outputs.addArgument(Out);
4609 continue;
4610 }
4611
4612 // The transform has determined that we should perform an elementwise
4613 // expansion of the pattern. Do so.
4614 for (unsigned I = 0; I != *NumExpansions; ++I) {
4615 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4616
4617 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4618 return true;
4619
4620 if (Out.getArgument().containsUnexpandedParameterPack()) {
4621 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4622 OrigNumExpansions);
4623 if (Out.getArgument().isNull())
4624 return true;
4625 }
4626
4627 Outputs.addArgument(Out);
4628 }
4629
4630 // If we're supposed to retain a pack expansion, do so by temporarily
4631 // forgetting the partially-substituted parameter pack.
4632 if (RetainExpansion) {
4633 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4634
4635 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4636 return true;
4637
4638 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4639 OrigNumExpansions);
4640 if (Out.getArgument().isNull())
4641 return true;
4642
4643 Outputs.addArgument(Out);
4644 }
4645
4646 continue;
4647 }
4648
4649 // The simple case:
4650 if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4651 return true;
4652
4653 Outputs.addArgument(Out);
4654 }
4655
4656 return false;
4657
4658}
4659
4660//===----------------------------------------------------------------------===//
4661// Type transformation
4662//===----------------------------------------------------------------------===//
4663
4664template<typename Derived>
4665QualType TreeTransform<Derived>::TransformType(QualType T) {
4666 if (getDerived().AlreadyTransformed(T))
4667 return T;
4668
4669 // Temporary workaround. All of these transformations should
4670 // eventually turn into transformations on TypeLocs.
4671 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4672 getDerived().getBaseLocation());
4673
4674 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4675
4676 if (!NewDI)
4677 return QualType();
4678
4679 return NewDI->getType();
4680}
4681
4682template<typename Derived>
4683TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4684 // Refine the base location to the type's location.
4685 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4686 getDerived().getBaseEntity());
4687 if (getDerived().AlreadyTransformed(DI->getType()))
4688 return DI;
4689
4690 TypeLocBuilder TLB;
4691
4692 TypeLoc TL = DI->getTypeLoc();
4693 TLB.reserve(TL.getFullDataSize());
4694
4695 QualType Result = getDerived().TransformType(TLB, TL);
4696 if (Result.isNull())
4697 return nullptr;
4698
4699 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4700}
4701
4702template<typename Derived>
4703QualType
4704TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4705 switch (T.getTypeLocClass()) {
4706#define ABSTRACT_TYPELOC(CLASS, PARENT)
4707#define TYPELOC(CLASS, PARENT) \
4708 case TypeLoc::CLASS: \
4709 return getDerived().Transform##CLASS##Type(TLB, \
4710 T.castAs<CLASS##TypeLoc>());
4711#include "clang/AST/TypeLocNodes.def"
4712 }
4713
4714 llvm_unreachable("unhandled type loc!")::llvm::llvm_unreachable_internal("unhandled type loc!", "clang/lib/Sema/TreeTransform.h"
, 4714)
;
4715}
4716
4717template<typename Derived>
4718QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4719 if (!isa<DependentNameType>(T))
4720 return TransformType(T);
4721
4722 if (getDerived().AlreadyTransformed(T))
4723 return T;
4724 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4725 getDerived().getBaseLocation());
4726 TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4727 return NewDI ? NewDI->getType() : QualType();
4728}
4729
4730template<typename Derived>
4731TypeSourceInfo *
4732TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4733 if (!isa<DependentNameType>(DI->getType()))
4734 return TransformType(DI);
4735
4736 // Refine the base location to the type's location.
4737 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4738 getDerived().getBaseEntity());
4739 if (getDerived().AlreadyTransformed(DI->getType()))
4740 return DI;
4741
4742 TypeLocBuilder TLB;
4743
4744 TypeLoc TL = DI->getTypeLoc();
4745 TLB.reserve(TL.getFullDataSize());
4746
4747 auto QTL = TL.getAs<QualifiedTypeLoc>();
4748 if (QTL)
4749 TL = QTL.getUnqualifiedLoc();
4750
4751 auto DNTL = TL.castAs<DependentNameTypeLoc>();
4752
4753 QualType Result = getDerived().TransformDependentNameType(
4754 TLB, DNTL, /*DeducedTSTContext*/true);
4755 if (Result.isNull())
4756 return nullptr;
4757
4758 if (QTL) {
4759 Result = getDerived().RebuildQualifiedType(Result, QTL);
4760 if (Result.isNull())
4761 return nullptr;
4762 TLB.TypeWasModifiedSafely(Result);
4763 }
4764
4765 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4766}
4767
4768template<typename Derived>
4769QualType
4770TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4771 QualifiedTypeLoc T) {
4772 QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4773 if (Result.isNull())
4774 return QualType();
4775
4776 Result = getDerived().RebuildQualifiedType(Result, T);
4777
4778 if (Result.isNull())
4779 return QualType();
4780
4781 // RebuildQualifiedType might have updated the type, but not in a way
4782 // that invalidates the TypeLoc. (There's no location information for
4783 // qualifiers.)
4784 TLB.TypeWasModifiedSafely(Result);
4785
4786 return Result;
4787}
4788
4789template <typename Derived>
4790QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4791 QualifiedTypeLoc TL) {
4792
4793 SourceLocation Loc = TL.getBeginLoc();
4794 Qualifiers Quals = TL.getType().getLocalQualifiers();
4795
4796 if ((T.getAddressSpace() != LangAS::Default &&
4797 Quals.getAddressSpace() != LangAS::Default) &&
4798 T.getAddressSpace() != Quals.getAddressSpace()) {
4799 SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4800 << TL.getType() << T;
4801 return QualType();
4802 }
4803
4804 // C++ [dcl.fct]p7:
4805 // [When] adding cv-qualifications on top of the function type [...] the
4806 // cv-qualifiers are ignored.
4807 if (T->isFunctionType()) {
4808 T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4809 Quals.getAddressSpace());
4810 return T;
4811 }
4812
4813 // C++ [dcl.ref]p1:
4814 // when the cv-qualifiers are introduced through the use of a typedef-name
4815 // or decltype-specifier [...] the cv-qualifiers are ignored.
4816 // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4817 // applied to a reference type.
4818 if (T->isReferenceType()) {
4819 // The only qualifier that applies to a reference type is restrict.
4820 if (!Quals.hasRestrict())
4821 return T;
4822 Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4823 }
4824
4825 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4826 // resulting type.
4827 if (Quals.hasObjCLifetime()) {
4828 if (!T->isObjCLifetimeType() && !T->isDependentType())
4829 Quals.removeObjCLifetime();
4830 else if (T.getObjCLifetime()) {
4831 // Objective-C ARC:
4832 // A lifetime qualifier applied to a substituted template parameter
4833 // overrides the lifetime qualifier from the template argument.
4834 const AutoType *AutoTy;
4835 if (const SubstTemplateTypeParmType *SubstTypeParam
4836 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4837 QualType Replacement = SubstTypeParam->getReplacementType();
4838 Qualifiers Qs = Replacement.getQualifiers();
4839 Qs.removeObjCLifetime();
4840 Replacement = SemaRef.Context.getQualifiedType(
4841 Replacement.getUnqualifiedType(), Qs);
4842 T = SemaRef.Context.getSubstTemplateTypeParmType(
4843 SubstTypeParam->getReplacedParameter(), Replacement);
4844 } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4845 // 'auto' types behave the same way as template parameters.
4846 QualType Deduced = AutoTy->getDeducedType();
4847 Qualifiers Qs = Deduced.getQualifiers();
4848 Qs.removeObjCLifetime();
4849 Deduced =
4850 SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4851 T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4852 AutoTy->isDependentType(),
4853 /*isPack=*/false,
4854 AutoTy->getTypeConstraintConcept(),
4855 AutoTy->getTypeConstraintArguments());
4856 } else {
4857 // Otherwise, complain about the addition of a qualifier to an
4858 // already-qualified type.
4859 // FIXME: Why is this check not in Sema::BuildQualifiedType?
4860 SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4861 Quals.removeObjCLifetime();
4862 }
4863 }
4864 }
4865
4866 return SemaRef.BuildQualifiedType(T, Loc, Quals);
4867}
4868
4869template<typename Derived>
4870TypeLoc
4871TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4872 QualType ObjectType,
4873 NamedDecl *UnqualLookup,
4874 CXXScopeSpec &SS) {
4875 if (getDerived().AlreadyTransformed(TL.getType()))
4876 return TL;
4877
4878 TypeSourceInfo *TSI =
4879 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4880 if (TSI)
4881 return TSI->getTypeLoc();
4882 return TypeLoc();
4883}
4884
4885template<typename Derived>
4886TypeSourceInfo *
4887TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4888 QualType ObjectType,
4889 NamedDecl *UnqualLookup,
4890 CXXScopeSpec &SS) {
4891 if (getDerived().AlreadyTransformed(TSInfo->getType()))
4892 return TSInfo;
4893
4894 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4895 UnqualLookup, SS);
4896}
4897
4898template <typename Derived>
4899TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4900 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4901 CXXScopeSpec &SS) {
4902 QualType T = TL.getType();
4903 assert(!getDerived().AlreadyTransformed(T))(static_cast <bool> (!getDerived().AlreadyTransformed(T
)) ? void (0) : __assert_fail ("!getDerived().AlreadyTransformed(T)"
, "clang/lib/Sema/TreeTransform.h", 4903, __extension__ __PRETTY_FUNCTION__
))
;
4904
4905 TypeLocBuilder TLB;
4906 QualType Result;
4907
4908 if (isa<TemplateSpecializationType>(T)) {
4909 TemplateSpecializationTypeLoc SpecTL =
4910 TL.castAs<TemplateSpecializationTypeLoc>();
4911
4912 TemplateName Template = getDerived().TransformTemplateName(
4913 SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4914 ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4915 if (Template.isNull())
4916 return nullptr;
4917
4918 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4919 Template);
4920 } else if (isa<DependentTemplateSpecializationType>(T)) {
4921 DependentTemplateSpecializationTypeLoc SpecTL =
4922 TL.castAs<DependentTemplateSpecializationTypeLoc>();
4923
4924 TemplateName Template
4925 = getDerived().RebuildTemplateName(SS,
4926 SpecTL.getTemplateKeywordLoc(),
4927 *SpecTL.getTypePtr()->getIdentifier(),
4928 SpecTL.getTemplateNameLoc(),
4929 ObjectType, UnqualLookup,
4930 /*AllowInjectedClassName*/true);
4931 if (Template.isNull())
4932 return nullptr;
4933
4934 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4935 SpecTL,
4936 Template,
4937 SS);
4938 } else {
4939 // Nothing special needs to be done for these.
4940 Result = getDerived().TransformType(TLB, TL);
4941 }
4942
4943 if (Result.isNull())
4944 return nullptr;
4945
4946 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4947}
4948
4949template <class TyLoc> static inline
4950QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4951 TyLoc NewT = TLB.push<TyLoc>(T.getType());
4952 NewT.setNameLoc(T.getNameLoc());
4953 return T.getType();
4954}
4955
4956template<typename Derived>
4957QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4958 BuiltinTypeLoc T) {
4959 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4960 NewT.setBuiltinLoc(T.getBuiltinLoc());
4961 if (T.needsExtraLocalData())
4962 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4963 return T.getType();
4964}
4965
4966template<typename Derived>
4967QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4968 ComplexTypeLoc T) {
4969 // FIXME: recurse?
4970 return TransformTypeSpecType(TLB, T);
4971}
4972
4973template <typename Derived>
4974QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4975 AdjustedTypeLoc TL) {
4976 // Adjustments applied during transformation are handled elsewhere.
4977 return getDerived().TransformType(TLB, TL.getOriginalLoc());
4978}
4979
4980template<typename Derived>
4981QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4982 DecayedTypeLoc TL) {
4983 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4984 if (OriginalType.isNull())
4985 return QualType();
4986
4987 QualType Result = TL.getType();
4988 if (getDerived().AlwaysRebuild() ||
4989 OriginalType != TL.getOriginalLoc().getType())
4990 Result = SemaRef.Context.getDecayedType(OriginalType);
4991 TLB.push<DecayedTypeLoc>(Result);
4992 // Nothing to set for DecayedTypeLoc.
4993 return Result;
4994}
4995
4996template<typename Derived>
4997QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4998 PointerTypeLoc TL) {
4999 QualType PointeeType
5000 = getDerived().TransformType(TLB, TL.getPointeeLoc());
5001 if (PointeeType.isNull())
5002 return QualType();
5003
5004 QualType Result = TL.getType();
5005 if (PointeeType->getAs<ObjCObjectType>()) {
5006 // A dependent pointer type 'T *' has is being transformed such
5007 // that an Objective-C class type is being replaced for 'T'. The
5008 // resulting pointer type is an ObjCObjectPointerType, not a
5009 // PointerType.
5010 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
5011
5012 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
5013 NewT.setStarLoc(TL.getStarLoc());
5014 return Result;
5015 }
5016
5017 if (getDerived().AlwaysRebuild() ||
5018 PointeeType != TL.getPointeeLoc().getType()) {
5019 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
5020 if (Result.isNull())
5021 return QualType();
5022 }
5023
5024 // Objective-C ARC can add lifetime qualifiers to the type that we're
5025 // pointing to.
5026 TLB.TypeWasModifiedSafely(Result->getPointeeType());
5027
5028 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
5029 NewT.setSigilLoc(TL.getSigilLoc());
5030 return Result;
5031}
5032
5033template<typename Derived>
5034QualType
5035TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
5036 BlockPointerTypeLoc TL) {
5037 QualType PointeeType
5038 = getDerived().TransformType(TLB, TL.getPointeeLoc());
5039 if (PointeeType.isNull())
5040 return QualType();
5041
5042 QualType Result = TL.getType();
5043 if (getDerived().AlwaysRebuild() ||
5044 PointeeType != TL.getPointeeLoc().getType()) {
5045 Result = getDerived().RebuildBlockPointerType(PointeeType,
5046 TL.getSigilLoc());
5047 if (Result.isNull())
5048 return QualType();
5049 }
5050
5051 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
5052 NewT.setSigilLoc(TL.getSigilLoc());
5053 return Result;
5054}
5055
5056/// Transforms a reference type. Note that somewhat paradoxically we
5057/// don't care whether the type itself is an l-value type or an r-value
5058/// type; we only care if the type was *written* as an l-value type
5059/// or an r-value type.
5060template<typename Derived>
5061QualType
5062TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
5063 ReferenceTypeLoc TL) {
5064 const ReferenceType *T = TL.getTypePtr();
5065
5066 // Note that this works with the pointee-as-written.
5067 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5068 if (PointeeType.isNull())
5069 return QualType();
5070
5071 QualType Result = TL.getType();
5072 if (getDerived().AlwaysRebuild() ||
5073 PointeeType != T->getPointeeTypeAsWritten()) {
5074 Result = getDerived().RebuildReferenceType(PointeeType,
5075 T->isSpelledAsLValue(),
5076 TL.getSigilLoc());
5077 if (Result.isNull())
5078 return QualType();
5079 }
5080
5081 // Objective-C ARC can add lifetime qualifiers to the type that we're
5082 // referring to.
5083 TLB.TypeWasModifiedSafely(
5084 Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
5085
5086 // r-value references can be rebuilt as l-value references.
5087 ReferenceTypeLoc NewTL;
5088 if (isa<LValueReferenceType>(Result))
5089 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
5090 else
5091 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
5092 NewTL.setSigilLoc(TL.getSigilLoc());
5093
5094 return Result;
5095}
5096
5097template<typename Derived>
5098QualType
5099TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
5100 LValueReferenceTypeLoc TL) {
5101 return TransformReferenceType(TLB, TL);
5102}
5103
5104template<typename Derived>
5105QualType
5106TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
5107 RValueReferenceTypeLoc TL) {
5108 return TransformReferenceType(TLB, TL);
5109}
5110
5111template<typename Derived>
5112QualType
5113TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
5114 MemberPointerTypeLoc TL) {
5115 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5116 if (PointeeType.isNull())
5117 return QualType();
5118
5119 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
5120 TypeSourceInfo *NewClsTInfo = nullptr;
5121 if (OldClsTInfo) {
5122 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
5123 if (!NewClsTInfo)
5124 return QualType();
5125 }
5126
5127 const MemberPointerType *T = TL.getTypePtr();
5128 QualType OldClsType = QualType(T->getClass(), 0);
5129 QualType NewClsType;
5130 if (NewClsTInfo)
5131 NewClsType = NewClsTInfo->getType();
5132 else {
5133 NewClsType = getDerived().TransformType(OldClsType);
5134 if (NewClsType.isNull())
5135 return QualType();
5136 }
5137
5138 QualType Result = TL.getType();
5139 if (getDerived().AlwaysRebuild() ||
5140 PointeeType != T->getPointeeType() ||
5141 NewClsType != OldClsType) {
5142 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
5143 TL.getStarLoc());
5144 if (Result.isNull())
5145 return QualType();
5146 }
5147
5148 // If we had to adjust the pointee type when building a member pointer, make
5149 // sure to push TypeLoc info for it.
5150 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
5151 if (MPT && PointeeType != MPT->getPointeeType()) {
5152 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", 5152, __extension__ __PRETTY_FUNCTION__
))
;
5153 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
5154 }
5155
5156 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
5157 NewTL.setSigilLoc(TL.getSigilLoc());
5158 NewTL.setClassTInfo(NewClsTInfo);
5159
5160 return Result;
5161}
5162
5163template<typename Derived>
5164QualType
5165TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
5166 ConstantArrayTypeLoc TL) {
5167 const ConstantArrayType *T = TL.getTypePtr();
5168 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5169 if (ElementType.isNull())
5170 return QualType();
5171
5172 // Prefer the expression from the TypeLoc; the other may have been uniqued.
5173 Expr *OldSize = TL.getSizeExpr();
5174 if (!OldSize)
5175 OldSize = const_cast<Expr*>(T->getSizeExpr());
5176 Expr *NewSize = nullptr;
5177 if (OldSize) {
5178 EnterExpressionEvaluationContext Unevaluated(
5179 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5180 NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
5181 NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
5182 }
5183
5184 QualType Result = TL.getType();
5185 if (getDerived().AlwaysRebuild() ||
5186 ElementType != T->getElementType() ||
5187 (T->getSizeExpr() && NewSize != OldSize)) {
5188 Result = getDerived().RebuildConstantArrayType(ElementType,
5189 T->getSizeModifier(),
5190 T->getSize(), NewSize,
5191 T->getIndexTypeCVRQualifiers(),
5192 TL.getBracketsRange());
5193 if (Result.isNull())
5194 return QualType();
5195 }
5196
5197 // We might have either a ConstantArrayType or a VariableArrayType now:
5198 // a ConstantArrayType is allowed to have an element type which is a
5199 // VariableArrayType if the type is dependent. Fortunately, all array
5200 // types have the same location layout.
5201 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5202 NewTL.setLBracketLoc(TL.getLBracketLoc());
5203 NewTL.setRBracketLoc(TL.getRBracketLoc());
5204 NewTL.setSizeExpr(NewSize);
5205
5206 return Result;
5207}
5208
5209template<typename Derived>
5210QualType TreeTransform<Derived>::TransformIncompleteArrayType(
5211 TypeLocBuilder &TLB,
5212 IncompleteArrayTypeLoc TL) {
5213 const IncompleteArrayType *T = TL.getTypePtr();
5214 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5215 if (ElementType.isNull())
5216 return QualType();
5217
5218 QualType Result = TL.getType();
5219 if (getDerived().AlwaysRebuild() ||
5220 ElementType != T->getElementType()) {
5221 Result = getDerived().RebuildIncompleteArrayType(ElementType,
5222 T->getSizeModifier(),
5223 T->getIndexTypeCVRQualifiers(),
5224 TL.getBracketsRange());
5225 if (Result.isNull())
5226 return QualType();
5227 }
5228
5229 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
5230 NewTL.setLBracketLoc(TL.getLBracketLoc());
5231 NewTL.setRBracketLoc(TL.getRBracketLoc());
5232 NewTL.setSizeExpr(nullptr);
5233
5234 return Result;
5235}
5236
5237template<typename Derived>
5238QualType
5239TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
5240 VariableArrayTypeLoc TL) {
5241 const VariableArrayType *T = TL.getTypePtr();
5242 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5243 if (ElementType.isNull())
5244 return QualType();
5245
5246 ExprResult SizeResult;
5247 {
5248 EnterExpressionEvaluationContext Context(
5249 SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5250 SizeResult = getDerived().TransformExpr(T->getSizeExpr());
5251 }
5252 if (SizeResult.isInvalid())
5253 return QualType();
5254 SizeResult =
5255 SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
5256 if (SizeResult.isInvalid())
5257 return QualType();
5258
5259 Expr *Size = SizeResult.get();
5260
5261 QualType Result = TL.getType();
5262 if (getDerived().AlwaysRebuild() ||
5263 ElementType != T->getElementType() ||
5264 Size != T->getSizeExpr()) {
5265 Result = getDerived().RebuildVariableArrayType(ElementType,
5266 T->getSizeModifier(),
5267 Size,
5268 T->getIndexTypeCVRQualifiers(),
5269 TL.getBracketsRange());
5270 if (Result.isNull())
5271 return QualType();
5272 }
5273
5274 // We might have constant size array now, but fortunately it has the same
5275 // location layout.
5276 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5277 NewTL.setLBracketLoc(TL.getLBracketLoc());
5278 NewTL.setRBracketLoc(TL.getRBracketLoc());
5279 NewTL.setSizeExpr(Size);
5280
5281 return Result;
5282}
5283
5284template<typename Derived>
5285QualType
5286TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
5287 DependentSizedArrayTypeLoc TL) {
5288 const DependentSizedArrayType *T = TL.getTypePtr();
5289 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5290 if (ElementType.isNull())
5291 return QualType();
5292
5293 // Array bounds are constant expressions.
5294 EnterExpressionEvaluationContext Unevaluated(
5295 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5296
5297 // Prefer the expression from the TypeLoc; the other may have been uniqued.
5298 Expr *origSize = TL.getSizeExpr();
5299 if (!origSize) origSize = T->getSizeExpr();
5300
5301 ExprResult sizeResult
5302 = getDerived().TransformExpr(origSize);
5303 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
5304 if (sizeResult.isInvalid())
5305 return QualType();
5306
5307 Expr *size = sizeResult.get();
5308
5309 QualType Result = TL.getType();
5310 if (getDerived().AlwaysRebuild() ||
5311 ElementType != T->getElementType() ||
5312 size != origSize) {
5313 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
5314 T->getSizeModifier(),
5315 size,
5316 T->getIndexTypeCVRQualifiers(),
5317 TL.getBracketsRange());
5318 if (Result.isNull())
5319 return QualType();
5320 }
5321
5322 // We might have any sort of array type now, but fortunately they
5323 // all have the same location layout.
5324 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5325 NewTL.setLBracketLoc(TL.getLBracketLoc());
5326 NewTL.setRBracketLoc(TL.getRBracketLoc());
5327 NewTL.setSizeExpr(size);
5328
5329 return Result;
5330}
5331
5332template <typename Derived>
5333QualType TreeTransform<Derived>::TransformDependentVectorType(
5334 TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
5335 const DependentVectorType *T = TL.getTypePtr();
5336 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5337 if (ElementType.isNull())
5338 return QualType();
5339
5340 EnterExpressionEvaluationContext Unevaluated(
5341 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5342
5343 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5344 Size = SemaRef.ActOnConstantExpression(Size);
5345 if (Size.isInvalid())
5346 return QualType();
5347
5348 QualType Result = TL.getType();
5349 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5350 Size.get() != T->getSizeExpr()) {
5351 Result = getDerived().RebuildDependentVectorType(
5352 ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5353 if (Result.isNull())
5354 return QualType();
5355 }
5356
5357 // Result might be dependent or not.
5358 if (isa<DependentVectorType>(Result)) {
5359 DependentVectorTypeLoc NewTL =
5360 TLB.push<DependentVectorTypeLoc>(Result);
5361 NewTL.setNameLoc(TL.getNameLoc());
5362 } else {
5363 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5364 NewTL.setNameLoc(TL.getNameLoc());
5365 }
5366
5367 return Result;
5368}
5369
5370template<typename Derived>
5371QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5372 TypeLocBuilder &TLB,
5373 DependentSizedExtVectorTypeLoc TL) {
5374 const DependentSizedExtVectorType *T = TL.getTypePtr();
5375
5376 // FIXME: ext vector locs should be nested
5377 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5378 if (ElementType.isNull())
5379 return QualType();
5380
5381 // Vector sizes are constant expressions.
5382 EnterExpressionEvaluationContext Unevaluated(
5383 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5384
5385 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5386 Size = SemaRef.ActOnConstantExpression(Size);
5387 if (Size.isInvalid())
5388 return QualType();
5389
5390 QualType Result = TL.getType();
5391 if (getDerived().AlwaysRebuild() ||
5392 ElementType != T->getElementType() ||
5393 Size.get() != T->getSizeExpr()) {
5394 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5395 Size.get(),
5396 T->getAttributeLoc());
5397 if (Result.isNull())
5398 return QualType();
5399 }
5400
5401 // Result might be dependent or not.
5402 if (isa<DependentSizedExtVectorType>(Result)) {
5403 DependentSizedExtVectorTypeLoc NewTL
5404 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5405 NewTL.setNameLoc(TL.getNameLoc());
5406 } else {
5407 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5408 NewTL.setNameLoc(TL.getNameLoc());
5409 }
5410
5411 return Result;
5412}
5413
5414template <typename Derived>
5415QualType
5416TreeTransform<Derived>::TransformConstantMatrixType(TypeLocBuilder &TLB,
5417 ConstantMatrixTypeLoc TL) {
5418 const ConstantMatrixType *T = TL.getTypePtr();
5419 QualType ElementType = getDerived().TransformType(T->getElementType());
5420 if (ElementType.isNull())
5421 return QualType();
5422
5423 QualType Result = TL.getType();
5424 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType()) {
5425 Result = getDerived().RebuildConstantMatrixType(
5426 ElementType, T->getNumRows(), T->getNumColumns());
5427 if (Result.isNull())
5428 return QualType();
5429 }
5430
5431 ConstantMatrixTypeLoc NewTL = TLB.push<ConstantMatrixTypeLoc>(Result);
5432 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5433 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5434 NewTL.setAttrRowOperand(TL.getAttrRowOperand());
5435 NewTL.setAttrColumnOperand(TL.getAttrColumnOperand());
5436
5437 return Result;
5438}
5439
5440template <typename Derived>
5441QualType TreeTransform<Derived>::TransformDependentSizedMatrixType(
5442 TypeLocBuilder &TLB, DependentSizedMatrixTypeLoc TL) {
5443 const DependentSizedMatrixType *T = TL.getTypePtr();
5444
5445 QualType ElementType = getDerived().TransformType(T->getElementType());
5446 if (ElementType.isNull()) {
5447 return QualType();
5448 }
5449
5450 // Matrix dimensions are constant expressions.
5451 EnterExpressionEvaluationContext Unevaluated(
5452 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5453
5454 Expr *origRows = TL.getAttrRowOperand();
5455 if (!origRows)
5456 origRows = T->getRowExpr();
5457 Expr *origColumns = TL.getAttrColumnOperand();
5458 if (!origColumns)
5459 origColumns = T->getColumnExpr();
5460
5461 ExprResult rowResult = getDerived().TransformExpr(origRows);
5462 rowResult = SemaRef.ActOnConstantExpression(rowResult);
5463 if (rowResult.isInvalid())
5464 return QualType();
5465
5466 ExprResult columnResult = getDerived().TransformExpr(origColumns);
5467 columnResult = SemaRef.ActOnConstantExpression(columnResult);
5468 if (columnResult.isInvalid())
5469 return QualType();
5470
5471 Expr *rows = rowResult.get();
5472 Expr *columns = columnResult.get();
5473
5474 QualType Result = TL.getType();
5475 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5476 rows != origRows || columns != origColumns) {
5477 Result = getDerived().RebuildDependentSizedMatrixType(
5478 ElementType, rows, columns, T->getAttributeLoc());
5479
5480 if (Result.isNull())
5481 return QualType();
5482 }
5483
5484 // We might have any sort of matrix type now, but fortunately they
5485 // all have the same location layout.
5486 MatrixTypeLoc NewTL = TLB.push<MatrixTypeLoc>(Result);
5487 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5488 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5489 NewTL.setAttrRowOperand(rows);
5490 NewTL.setAttrColumnOperand(columns);
5491 return Result;
5492}
5493
5494template <typename Derived>
5495QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5496 TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5497 const DependentAddressSpaceType *T = TL.getTypePtr();
5498
5499 QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5500
5501 if (pointeeType.isNull())
5502 return QualType();
5503
5504 // Address spaces are constant expressions.
5505 EnterExpressionEvaluationContext Unevaluated(
5506 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5507
5508 ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5509 AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5510 if (AddrSpace.isInvalid())
5511 return QualType();
5512
5513 QualType Result = TL.getType();
5514 if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5515 AddrSpace.get() != T->getAddrSpaceExpr()) {
5516 Result = getDerived().RebuildDependentAddressSpaceType(
5517 pointeeType, AddrSpace.get(), T->getAttributeLoc());
5518 if (Result.isNull())
5519 return QualType();
5520 }
5521
5522 // Result might be dependent or not.
5523 if (isa<DependentAddressSpaceType>(Result)) {
5524 DependentAddressSpaceTypeLoc NewTL =
5525 TLB.push<DependentAddressSpaceTypeLoc>(Result);
5526
5527 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5528 NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5529 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5530
5531 } else {
5532 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5533 Result, getDerived().getBaseLocation());
5534 TransformType(TLB, DI->getTypeLoc());
5535 }
5536
5537 return Result;
5538}
5539
5540template <typename Derived>
5541QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5542 VectorTypeLoc TL) {
5543 const VectorType *T = TL.getTypePtr();
5544 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5545 if (ElementType.isNull())
5546 return QualType();
5547
5548 QualType Result = TL.getType();
5549 if (getDerived().AlwaysRebuild() ||
5550 ElementType != T->getElementType()) {
5551 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5552 T->getVectorKind());
5553 if (Result.isNull())
5554 return QualType();
5555 }
5556
5557 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5558 NewTL.setNameLoc(TL.getNameLoc());
5559
5560 return Result;
5561}
5562
5563template<typename Derived>
5564QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5565 ExtVectorTypeLoc TL) {
5566 const VectorType *T = TL.getTypePtr();
5567 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5568 if (ElementType.isNull())
5569 return QualType();
5570
5571 QualType Result = TL.getType();
5572 if (getDerived().AlwaysRebuild() ||
5573 ElementType != T->getElementType()) {
5574 Result = getDerived().RebuildExtVectorType(ElementType,
5575 T->getNumElements(),
5576 /*FIXME*/ SourceLocation());
5577 if (Result.isNull())
5578 return QualType();
5579 }
5580
5581 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5582 NewTL.setNameLoc(TL.getNameLoc());
5583
5584 return Result;
5585}
5586
5587template <typename Derived>
5588ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5589 ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
5590 bool ExpectParameterPack) {
5591 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5592 TypeSourceInfo *NewDI = nullptr;
5593
5594 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5595 // If we're substituting into a pack expansion type and we know the
5596 // length we want to expand to, just substitute for the pattern.
5597 TypeLoc OldTL = OldDI->getTypeLoc();
5598 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5599
5600 TypeLocBuilder TLB;
5601 TypeLoc NewTL = OldDI->getTypeLoc();
5602 TLB.reserve(NewTL.getFullDataSize());
5603
5604 QualType Result = getDerived().TransformType(TLB,
5605 OldExpansionTL.getPatternLoc());
5606 if (Result.isNull())
5607 return nullptr;
5608
5609 Result = RebuildPackExpansionType(Result,
5610 OldExpansionTL.getPatternLoc().getSourceRange(),
5611 OldExpansionTL.getEllipsisLoc(),
5612 NumExpansions);
5613 if (Result.isNull())
5614 return nullptr;
5615
5616 PackExpansionTypeLoc NewExpansionTL
5617 = TLB.push<PackExpansionTypeLoc>(Result);
5618 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5619 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5620 } else
5621 NewDI = getDerived().TransformType(OldDI);
5622 if (!NewDI)
5623 return nullptr;
5624
5625 if (NewDI == OldDI && indexAdjustment == 0)
5626 return OldParm;
5627
5628 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5629 OldParm->getDeclContext(),
5630 OldParm->getInnerLocStart(),
5631 OldParm->getLocation(),
5632 OldParm->getIdentifier(),
5633 NewDI->getType(),
5634 NewDI,
5635 OldParm->getStorageClass(),
5636 /* DefArg */ nullptr);
5637 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5638 OldParm->getFunctionScopeIndex() + indexAdjustment);
5639 transformedLocalDecl(OldParm, {newParm});
5640 return newParm;
5641}
5642
5643template <typename Derived>
5644bool TreeTransform<Derived>::TransformFunctionTypeParams(
5645 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5646 const QualType *ParamTypes,
5647 const FunctionProtoType::ExtParameterInfo *ParamInfos,
5648 SmallVectorImpl<QualType> &OutParamTypes,
5649 SmallVectorImpl<ParmVarDecl *> *PVars,
5650 Sema::ExtParameterInfoBuilder &PInfos) {
5651 int indexAdjustment = 0;
5652
5653 unsigned NumParams = Params.size();
5654 for (unsigned i = 0; i != NumParams; ++i) {
5655 if (ParmVarDecl *OldParm = Params[i]) {
5656 assert(OldParm->getFunctionScopeIndex() == i)(static_cast <bool> (OldParm->getFunctionScopeIndex(
) == i) ? void (0) : __assert_fail ("OldParm->getFunctionScopeIndex() == i"
, "clang/lib/Sema/TreeTransform.h", 5656, __extension__ __PRETTY_FUNCTION__
))
;
5657
5658 Optional<unsigned> NumExpansions;
5659 ParmVarDecl *NewParm = nullptr;
5660 if (OldParm->isParameterPack()) {
5661 // We have a function parameter pack that may need to be expanded.
5662 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5663
5664 // Find the parameter packs that could be expanded.
5665 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5666 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5667 TypeLoc Pattern = ExpansionTL.getPatternLoc();
5668 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5669
5670 // Determine whether we should expand the parameter packs.
5671 bool ShouldExpand = false;
5672 bool RetainExpansion = false;
5673 Optional<unsigned> OrigNumExpansions;
5674 if (Unexpanded.size() > 0) {
5675 OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5676 NumExpansions = OrigNumExpansions;
5677 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5678 Pattern.getSourceRange(),
5679 Unexpanded,
5680 ShouldExpand,
5681 RetainExpansion,
5682 NumExpansions)) {
5683 return true;
5684 }
5685 } else {
5686#ifndef NDEBUG
5687 const AutoType *AT =
5688 Pattern.getType().getTypePtr()->getContainedAutoType();
5689 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", 5690, __extension__ __PRETTY_FUNCTION__
))
5690 "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", 5690, __extension__ __PRETTY_FUNCTION__
))
;
5691#endif
5692 }
5693
5694 if (ShouldExpand) {
5695 // Expand the function parameter pack into multiple, separate
5696 // parameters.
5697 getDerived().ExpandingFunctionParameterPack(OldParm);
5698 for (unsigned I = 0; I != *NumExpansions; ++I) {
5699 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5700 ParmVarDecl *NewParm
5701 = getDerived().TransformFunctionTypeParam(OldParm,
5702 indexAdjustment++,
5703 OrigNumExpansions,
5704 /*ExpectParameterPack=*/false);
5705 if (!NewParm)
5706 return true;
5707
5708 if (ParamInfos)
5709 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5710 OutParamTypes.push_back(NewParm->getType());
5711 if (PVars)
5712 PVars->push_back(NewParm);
5713 }
5714
5715 // If we're supposed to retain a pack expansion, do so by temporarily
5716 // forgetting the partially-substituted parameter pack.
5717 if (RetainExpansion) {
5718 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5719 ParmVarDecl *NewParm
5720 = getDerived().TransformFunctionTypeParam(OldParm,
5721 indexAdjustment++,
5722 OrigNumExpansions,
5723 /*ExpectParameterPack=*/false);
5724 if (!NewParm)
5725 return true;
5726
5727 if (ParamInfos)
5728 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5729 OutParamTypes.push_back(NewParm->getType());
5730 if (PVars)
5731 PVars->push_back(NewParm);
5732 }
5733
5734 // The next parameter should have the same adjustment as the
5735 // last thing we pushed, but we post-incremented indexAdjustment
5736 // on every push. Also, if we push nothing, the adjustment should
5737 // go down by one.
5738 indexAdjustment--;
5739
5740 // We're done with the pack expansion.
5741 continue;
5742 }
5743
5744 // We'll substitute the parameter now without expanding the pack
5745 // expansion.
5746 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5747 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5748 indexAdjustment,
5749 NumExpansions,
5750 /*ExpectParameterPack=*/true);
5751 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", 5753, __extension__ __PRETTY_FUNCTION__
))
5752 "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", 5753, __extension__ __PRETTY_FUNCTION__
))
5753 "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", 5753, __extension__ __PRETTY_FUNCTION__
))
;
5754 } else {
5755 NewParm = getDerived().TransformFunctionTypeParam(
5756 OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5757 }
5758
5759 if (!NewParm)
5760 return true;
5761
5762 if (ParamInfos)
5763 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5764 OutParamTypes.push_back(NewParm->getType());
5765 if (PVars)
5766 PVars->push_back(NewParm);
5767 continue;
5768 }
5769
5770 // Deal with the possibility that we don't have a parameter
5771 // declaration for this parameter.
5772 QualType OldType = ParamTypes[i];
5773 bool IsPackExpansion = false;
5774 Optional<unsigned> NumExpansions;
5775 QualType NewType;
5776 if (const PackExpansionType *Expansion
5777 = dyn_cast<PackExpansionType>(OldType)) {
5778 // We have a function parameter pack that may need to be expanded.
5779 QualType Pattern = Expansion->getPattern();
5780 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5781 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5782
5783 // Determine whether we should expand the parameter packs.
5784 bool ShouldExpand = false;
5785 bool RetainExpansion = false;
5786 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5787 Unexpanded,
5788 ShouldExpand,
5789 RetainExpansion,
5790 NumExpansions)) {
5791 return true;
5792 }
5793
5794 if (ShouldExpand) {
5795 // Expand the function parameter pack into multiple, separate
5796 // parameters.
5797 for (unsigned I = 0; I != *NumExpansions; ++I) {
5798 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5799 QualType NewType = getDerived().TransformType(Pattern);
5800 if (NewType.isNull())
5801 return true;
5802
5803 if (NewType->containsUnexpandedParameterPack()) {
5804 NewType =
5805 getSema().getASTContext().getPackExpansionType(NewType, None);
5806
5807 if (NewType.isNull())
5808 return true;
5809 }
5810
5811 if (ParamInfos)
5812 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5813 OutParamTypes.push_back(NewType);
5814 if (PVars)
5815 PVars->push_back(nullptr);
5816 }
5817
5818 // We're done with the pack expansion.
5819 continue;
5820 }
5821
5822 // If we're supposed to retain a pack expansion, do so by temporarily
5823 // forgetting the partially-substituted parameter pack.
5824 if (RetainExpansion) {
5825 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5826 QualType NewType = getDerived().TransformType(Pattern);
5827 if (NewType.isNull())
5828 return true;
5829
5830 if (ParamInfos)
5831 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5832 OutParamTypes.push_back(NewType);
5833 if (PVars)
5834 PVars->push_back(nullptr);
5835 }
5836
5837 // We'll substitute the parameter now without expanding the pack
5838 // expansion.
5839 OldType = Expansion->getPattern();
5840 IsPackExpansion = true;
5841 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5842 NewType = getDerived().TransformType(OldType);
5843 } else {
5844 NewType = getDerived().TransformType(OldType);
5845 }
5846
5847 if (NewType.isNull())
5848 return true;
5849
5850 if (IsPackExpansion)
5851 NewType = getSema().Context.getPackExpansionType(NewType,
5852 NumExpansions);
5853
5854 if (ParamInfos)
5855 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5856 OutParamTypes.push_back(NewType);
5857 if (PVars)
5858 PVars->push_back(nullptr);
5859 }
5860
5861#ifndef NDEBUG
5862 if (PVars) {
5863 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5864 if (ParmVarDecl *parm = (*PVars)[i])
5865 assert(parm->getFunctionScopeIndex() == i)(static_cast <bool> (parm->getFunctionScopeIndex() ==
i) ? void (0) : __assert_fail ("parm->getFunctionScopeIndex() == i"
, "clang/lib/Sema/TreeTransform.h", 5865, __extension__ __PRETTY_FUNCTION__
))
;
5866 }
5867#endif
5868
5869 return false;
5870}
5871
5872template<typename Derived>
5873QualType
5874TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5875 FunctionProtoTypeLoc TL) {
5876 SmallVector<QualType, 4> ExceptionStorage;
5877 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5878 return getDerived().TransformFunctionProtoType(
5879 TLB, TL, nullptr, Qualifiers(),
5880 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5881 return This->getDerived().TransformExceptionSpec(
5882 TL.getBeginLoc(), ESI, ExceptionStorage, Changed);
5883 });
5884}
5885
5886template<typename Derived> template<typename Fn>
5887QualType TreeTransform<Derived>::TransformFunctionProtoType(
5888 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5889 Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5890
5891 // Transform the parameters and return type.
5892 //
5893 // We are required to instantiate the params and return type in source order.
5894 // When the function has a trailing return type, we instantiate the
5895 // parameters before the return type, since the return type can then refer
5896 // to the parameters themselves (via decltype, sizeof, etc.).
5897 //
5898 SmallVector<QualType, 4> ParamTypes;
5899 SmallVector<ParmVarDecl*, 4> ParamDecls;
5900 Sema::ExtParameterInfoBuilder ExtParamInfos;
5901 const FunctionProtoType *T = TL.getTypePtr();
5902
5903 QualType ResultType;
5904
5905 if (T->hasTrailingReturn()) {
5906 if (getDerived().TransformFunctionTypeParams(
5907 TL.getBeginLoc(), TL.getParams(),
5908 TL.getTypePtr()->param_type_begin(),
5909 T->getExtParameterInfosOrNull(),
5910 ParamTypes, &ParamDecls, ExtParamInfos))
5911 return QualType();
5912
5913 {
5914 // C++11 [expr.prim.general]p3:
5915 // If a declaration declares a member function or member function
5916 // template of a class X, the expression this is a prvalue of type
5917 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5918 // and the end of the function-definition, member-declarator, or
5919 // declarator.
5920 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5921
5922 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5923 if (ResultType.isNull())
5924 return QualType();
5925 }
5926 }
5927 else {
5928 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5929 if (ResultType.isNull())
5930 return QualType();
5931
5932 if (getDerived().TransformFunctionTypeParams(
5933 TL.getBeginLoc(), TL.getParams(),
5934 TL.getTypePtr()->param_type_begin(),
5935 T->getExtParameterInfosOrNull(),
5936 ParamTypes, &ParamDecls, ExtParamInfos))
5937 return QualType();
5938 }
5939
5940 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5941
5942 bool EPIChanged = false;
5943 if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5944 return QualType();
5945
5946 // Handle extended parameter information.
5947 if (auto NewExtParamInfos =
5948 ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5949 if (!EPI.ExtParameterInfos ||
5950 llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5951 != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5952 EPIChanged = true;
5953 }
5954 EPI.ExtParameterInfos = NewExtParamInfos;
5955 } else if (EPI.ExtParameterInfos) {
5956 EPIChanged = true;
5957 EPI.ExtParameterInfos = nullptr;
5958 }
5959
5960 QualType Result = TL.getType();
5961 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5962 T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5963 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5964 if (Result.isNull())
5965 return QualType();
5966 }
5967
5968 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5969 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5970 NewTL.setLParenLoc(TL.getLParenLoc());
5971 NewTL.setRParenLoc(TL.getRParenLoc());
5972 NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5973 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5974 for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5975 NewTL.setParam(i, ParamDecls[i]);
5976
5977 return Result;
5978}
5979
5980template<typename Derived>
5981bool TreeTransform<Derived>::TransformExceptionSpec(
5982 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5983 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5984 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", 5984, __extension__ __PRETTY_FUNCTION__
))
;
5985
5986 // Instantiate a dynamic noexcept expression, if any.
5987 if (isComputedNoexcept(ESI.Type)) {
5988 EnterExpressionEvaluationContext Unevaluated(
5989 getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5990 ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5991 if (NoexceptExpr.isInvalid())
5992 return true;
5993
5994 ExceptionSpecificationType EST = ESI.Type;
5995 NoexceptExpr =
5996 getSema().ActOnNoexceptSpec(NoexceptExpr.get(), EST);
5997 if (NoexceptExpr.isInvalid())
5998 return true;
5999
6000 if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
6001 Changed = true;
6002 ESI.NoexceptExpr = NoexceptExpr.get();
6003 ESI.Type = EST;
6004 }
6005
6006 if (ESI.Type != EST_Dynamic)
6007 return false;
6008
6009 // Instantiate a dynamic exception specification's type.
6010 for (QualType T : ESI.Exceptions) {
6011 if (const PackExpansionType *PackExpansion =
6012 T->getAs<PackExpansionType>()) {
6013 Changed = true;
6014
6015 // We have a pack expansion. Instantiate it.
6016 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6017 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6018 Unexpanded);
6019 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", 6019, __extension__ __PRETTY_FUNCTION__
))
;
6020
6021 // Determine whether the set of unexpanded parameter packs can and
6022 // should
6023 // be expanded.
6024 bool Expand = false;
6025 bool RetainExpansion = false;
6026 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6027 // FIXME: Track the location of the ellipsis (and track source location
6028 // information for the types in the exception specification in general).
6029 if (getDerived().TryExpandParameterPacks(
6030 Loc, SourceRange(), Unexpanded, Expand,
6031 RetainExpansion, NumExpansions))
6032 return true;
6033
6034 if (!Expand) {
6035 // We can't expand this pack expansion into separate arguments yet;
6036 // just substitute into the pattern and create a new pack expansion
6037 // type.
6038 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6039 QualType U = getDerived().TransformType(PackExpansion->getPattern());
6040 if (U.isNull())
6041 return true;
6042
6043 U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
6044 Exceptions.push_back(U);
6045 continue;
6046 }
6047
6048 // Substitute into the pack expansion pattern for each slice of the
6049 // pack.
6050 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6051 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6052
6053 QualType U = getDerived().TransformType(PackExpansion->getPattern());
6054 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6055 return true;
6056
6057 Exceptions.push_back(U);
6058 }
6059 } else {
6060 QualType U = getDerived().TransformType(T);
6061 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6062 return true;
6063 if (T != U)
6064 Changed = true;
6065
6066 Exceptions.push_back(U);
6067 }
6068 }
6069
6070 ESI.Exceptions = Exceptions;
6071 if (ESI.Exceptions.empty())
6072 ESI.Type = EST_DynamicNone;
6073 return false;
6074}
6075
6076template<typename Derived>
6077QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
6078 TypeLocBuilder &TLB,
6079 FunctionNoProtoTypeLoc TL) {
6080 const FunctionNoProtoType *T = TL.getTypePtr();
6081 QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6082 if (ResultType.isNull())
6083 return QualType();
6084
6085 QualType Result = TL.getType();
6086 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
6087 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
6088
6089 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
6090 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6091 NewTL.setLParenLoc(TL.getLParenLoc());
6092 NewTL.setRParenLoc(TL.getRParenLoc());
6093 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6094
6095 return Result;
6096}
6097
6098template <typename Derived>
6099QualType TreeTransform<Derived>::TransformUnresolvedUsingType(
6100 TypeLocBuilder &TLB, UnresolvedUsingTypeLoc TL) {
6101 const UnresolvedUsingType *T = TL.getTypePtr();
6102 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
6103 if (!D)
6104 return QualType();
6105
6106 QualType Result = TL.getType();
6107 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
6108 Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
6109 if (Result.isNull())
6110 return QualType();
6111 }
6112
6113 // We might get an arbitrary type spec type back. We should at
6114 // least always get a type spec type, though.
6115 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
6116 NewTL.setNameLoc(TL.getNameLoc());
6117
6118 return Result;
6119}
6120
6121template <typename Derived>
6122QualType TreeTransform<Derived>::TransformUsingType(TypeLocBuilder &TLB,
6123 UsingTypeLoc TL) {
6124 const UsingType *T = TL.getTypePtr();
6125
6126 auto *Found = cast_or_null<UsingShadowDecl>(getDerived().TransformDecl(
6127 TL.getLocalSourceRange().getBegin(), T->getFoundDecl()));
6128 if (!Found)
6129 return QualType();
6130
6131 QualType Underlying = getDerived().TransformType(T->desugar());
6132 if (Underlying.isNull())
6133 return QualType();
6134
6135 QualType Result = TL.getType();
6136 if (getDerived().AlwaysRebuild() || Found != T->getFoundDecl() ||
6137 Underlying != T->getUnderlyingType()) {
6138 Result = getDerived().RebuildUsingType(Found, Underlying);
6139 if (Result.isNull())
6140 return QualType();
6141 }
6142
6143 TLB.pushTypeSpec(Result).setNameLoc(TL.getNameLoc());
6144 return Result;
6145}
6146
6147template<typename Derived>
6148QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
6149 TypedefTypeLoc TL) {
6150 const TypedefType *T = TL.getTypePtr();
6151 TypedefNameDecl *Typedef
6152 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6153 T->getDecl()));
6154 if (!Typedef)
6155 return QualType();
6156
6157 QualType Result = TL.getType();
6158 if (getDerived().AlwaysRebuild() ||
6159 Typedef != T->getDecl()) {
6160 Result = getDerived().RebuildTypedefType(Typedef);
6161 if (Result.isNull())
6162 return QualType();
6163 }
6164
6165 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
6166 NewTL.setNameLoc(TL.getNameLoc());
6167
6168 return Result;
6169}
6170
6171template<typename Derived>
6172QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
6173 TypeOfExprTypeLoc TL) {
6174 // typeof expressions are not potentially evaluated contexts
6175 EnterExpressionEvaluationContext Unevaluated(
6176 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
6177 Sema::ReuseLambdaContextDecl);
6178
6179 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
6180 if (E.isInvalid())
6181 return QualType();
6182
6183 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
6184 if (E.isInvalid())
6185 return QualType();
6186
6187 QualType Result = TL.getType();
6188 if (getDerived().AlwaysRebuild() ||
6189 E.get() != TL.getUnderlyingExpr()) {
6190 Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
6191 if (Result.isNull())
6192 return QualType();
6193 }
6194 else E.get();
6195
6196 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
6197 NewTL.setTypeofLoc(TL.getTypeofLoc());
6198 NewTL.setLParenLoc(TL.getLParenLoc());
6199 NewTL.setRParenLoc(TL.getRParenLoc());
6200
6201 return Result;
6202}
6203
6204template<typename Derived>
6205QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
6206 TypeOfTypeLoc TL) {
6207 TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
6208 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
6209 if (!New_Under_TI)
6210 return QualType();
6211
6212 QualType Result = TL.getType();
6213 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
6214 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
6215 if (Result.isNull())
6216 return QualType();
6217 }
6218
6219 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
6220 NewTL.setTypeofLoc(TL.getTypeofLoc());
6221 NewTL.setLParenLoc(TL.getLParenLoc());
6222 NewTL.setRParenLoc(TL.getRParenLoc());
6223 NewTL.setUnderlyingTInfo(New_Under_TI);
6224
6225 return Result;
6226}
6227
6228template<typename Derived>
6229QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
6230 DecltypeTypeLoc TL) {
6231 const DecltypeType *T = TL.getTypePtr();
6232
6233 // decltype expressions are not potentially evaluated contexts
6234 EnterExpressionEvaluationContext Unevaluated(
6235 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
6236 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
6237
6238 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
6239 if (E.isInvalid())
6240 return QualType();
6241
6242 E = getSema().ActOnDecltypeExpression(E.get());
6243 if (E.isInvalid())
6244 return QualType();
6245
6246 QualType Result = TL.getType();
6247 if (getDerived().AlwaysRebuild() ||
6248 E.get() != T->getUnderlyingExpr()) {
6249 Result = getDerived().RebuildDecltypeType(E.get(), TL.getDecltypeLoc());
6250 if (Result.isNull())
6251 return QualType();
6252 }
6253 else E.get();
6254
6255 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
6256 NewTL.setDecltypeLoc(TL.getDecltypeLoc());
6257 NewTL.setRParenLoc(TL.getRParenLoc());
6258 return Result;
6259}
6260
6261template<typename Derived>
6262QualType TreeTransform<Derived>::TransformUnaryTransformType(
6263 TypeLocBuilder &TLB,
6264 UnaryTransformTypeLoc TL) {
6265 QualType Result = TL.getType();
6266 if (Result->isDependentType()) {
6267 const UnaryTransformType *T = TL.getTypePtr();
6268 QualType NewBase =
6269 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
6270 Result = getDerived().RebuildUnaryTransformType(NewBase,
6271 T->getUTTKind(),
6272 TL.getKWLoc());
6273 if (Result.isNull())
6274 return QualType();
6275 }
6276
6277 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
6278 NewTL.setKWLoc(TL.getKWLoc());
6279 NewTL.setParensRange(TL.getParensRange());
6280 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
6281 return Result;
6282}
6283
6284template<typename Derived>
6285QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
6286 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
6287 const DeducedTemplateSpecializationType *T = TL.getTypePtr();
6288
6289 CXXScopeSpec SS;
6290 TemplateName TemplateName = getDerived().TransformTemplateName(
6291 SS, T->getTemplateName(), TL.getTemplateNameLoc());
6292 if (TemplateName.isNull())
6293 return QualType();
6294
6295 QualType OldDeduced = T->getDeducedType();
6296 QualType NewDeduced;
6297 if (!OldDeduced.isNull()) {
6298 NewDeduced = getDerived().TransformType(OldDeduced);
6299 if (NewDeduced.isNull())
6300 return QualType();
6301 }
6302
6303 QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
6304 TemplateName, NewDeduced);
6305 if (Result.isNull())
6306 return QualType();
6307
6308 DeducedTemplateSpecializationTypeLoc NewTL =
6309 TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
6310 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6311
6312 return Result;
6313}
6314
6315template<typename Derived>
6316QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
6317 RecordTypeLoc TL) {
6318 const RecordType *T = TL.getTypePtr();
6319 RecordDecl *Record
6320 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6321 T->getDecl()));
6322 if (!Record)
6323 return QualType();
6324
6325 QualType Result = TL.getType();
6326 if (getDerived().AlwaysRebuild() ||
6327 Record != T->getDecl()) {
6328 Result = getDerived().RebuildRecordType(Record);
6329 if (Result.isNull())
6330 return QualType();
6331 }
6332
6333 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6334 NewTL.setNameLoc(TL.getNameLoc());
6335
6336 return Result;
6337}
6338
6339template<typename Derived>
6340QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
6341 EnumTypeLoc TL) {
6342 const EnumType *T = TL.getTypePtr();
6343 EnumDecl *Enum
6344 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6345 T->getDecl()));
6346 if (!Enum)
6347 return QualType();
6348
6349 QualType Result = TL.getType();
6350 if (getDerived().AlwaysRebuild() ||
6351 Enum != T->getDecl()) {
6352 Result = getDerived().RebuildEnumType(Enum);
6353 if (Result.isNull())
6354 return QualType();
6355 }
6356
6357 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
6358 NewTL.setNameLoc(TL.getNameLoc());
6359
6360 return Result;
6361}
6362
6363template<typename Derived>
6364QualType TreeTransform<Derived>::TransformInjectedClassNameType(
6365 TypeLocBuilder &TLB,
6366 InjectedClassNameTypeLoc TL) {
6367 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
6368 TL.getTypePtr()->getDecl());
6369 if (!D) return QualType();
6370
6371 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
6372 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
6373 return T;
6374}
6375
6376template<typename Derived>
6377QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6378 TypeLocBuilder &TLB,
6379 TemplateTypeParmTypeLoc TL) {
6380 return TransformTypeSpecType(TLB, TL);
6381}
6382
6383template<typename Derived>
6384QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
6385 TypeLocBuilder &TLB,
6386 SubstTemplateTypeParmTypeLoc TL) {
6387 const SubstTemplateTypeParmType *T = TL.getTypePtr();
6388
6389 // Substitute into the replacement type, which itself might involve something
6390 // that needs to be transformed. This only tends to occur with default
6391 // template arguments of template template parameters.
6392 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
6393 QualType Replacement = getDerived().TransformType(T->getReplacementType());
6394 if (Replacement.isNull())
6395 return QualType();
6396
6397 // Always canonicalize the replacement type.
6398 Replacement = SemaRef.Context.getCanonicalType(Replacement);
6399 QualType Result
6400 = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
6401 Replacement);
6402
6403 // Propagate type-source information.
6404 SubstTemplateTypeParmTypeLoc NewTL
6405 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
6406 NewTL.setNameLoc(TL.getNameLoc());
6407 return Result;
6408
6409}
6410
6411template<typename Derived>
6412QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6413 TypeLocBuilder &TLB,
6414 SubstTemplateTypeParmPackTypeLoc TL) {
6415 return TransformTypeSpecType(TLB, TL);
6416}
6417
6418template<typename Derived>
6419QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6420 TypeLocBuilder &TLB,
6421 TemplateSpecializationTypeLoc TL) {
6422 const TemplateSpecializationType *T = TL.getTypePtr();
6423
6424 // The nested-name-specifier never matters in a TemplateSpecializationType,
6425 // because we can't have a dependent nested-name-specifier anyway.
6426 CXXScopeSpec SS;
6427 TemplateName Template
6428 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
6429 TL.getTemplateNameLoc());
6430 if (Template.isNull())
6431 return QualType();
6432
6433 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
6434}
6435
6436template<typename Derived>
6437QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
6438 AtomicTypeLoc TL) {
6439 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6440 if (ValueType.isNull())
6441 return QualType();
6442
6443 QualType Result = TL.getType();
6444 if (getDerived().AlwaysRebuild() ||
6445 ValueType != TL.getValueLoc().getType()) {
6446 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6447 if (Result.isNull())
6448 return QualType();
6449 }
6450
6451 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6452 NewTL.setKWLoc(TL.getKWLoc());
6453 NewTL.setLParenLoc(TL.getLParenLoc());
6454 NewTL.setRParenLoc(TL.getRParenLoc());
6455
6456 return Result;
6457}
6458
6459template <typename Derived>
6460QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6461 PipeTypeLoc TL) {
6462 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6463 if (ValueType.isNull())
6464 return QualType();
6465
6466 QualType Result = TL.getType();
6467 if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
6468 const PipeType *PT = Result->castAs<PipeType>();
6469 bool isReadPipe = PT->isReadOnly();
6470 Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6471 if (Result.isNull())
6472 return QualType();
6473 }
6474
6475 PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6476 NewTL.setKWLoc(TL.getKWLoc());
6477
6478 return Result;
6479}
6480
6481template <typename Derived>
6482QualType TreeTransform<Derived>::TransformBitIntType(TypeLocBuilder &TLB,
6483 BitIntTypeLoc TL) {
6484 const BitIntType *EIT = TL.getTypePtr();
6485 QualType Result = TL.getType();
6486
6487 if (getDerived().AlwaysRebuild()) {
6488 Result = getDerived().RebuildBitIntType(EIT->isUnsigned(),
6489 EIT->getNumBits(), TL.getNameLoc());
6490 if (Result.isNull())
6491 return QualType();
6492 }
6493
6494 BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6495 NewTL.setNameLoc(TL.getNameLoc());
6496 return Result;
6497}
6498
6499template <typename Derived>
6500QualType TreeTransform<Derived>::TransformDependentBitIntType(
6501 TypeLocBuilder &TLB, DependentBitIntTypeLoc TL) {
6502 const DependentBitIntType *EIT = TL.getTypePtr();
6503
6504 EnterExpressionEvaluationContext Unevaluated(
6505 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6506 ExprResult BitsExpr = getDerived().TransformExpr(EIT->getNumBitsExpr());
6507 BitsExpr = SemaRef.ActOnConstantExpression(BitsExpr);
6508
6509 if (BitsExpr.isInvalid())
6510 return QualType();
6511
6512 QualType Result = TL.getType();
6513
6514 if (getDerived().AlwaysRebuild() || BitsExpr.get() != EIT->getNumBitsExpr()) {
6515 Result = getDerived().RebuildDependentBitIntType(
6516 EIT->isUnsigned(), BitsExpr.get(), TL.getNameLoc());
6517
6518 if (Result.isNull())
6519 return QualType();
6520 }
6521
6522 if (isa<DependentBitIntType>(Result)) {
6523 DependentBitIntTypeLoc NewTL = TLB.push<DependentBitIntTypeLoc>(Result);
6524 NewTL.setNameLoc(TL.getNameLoc());
6525 } else {
6526 BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6527 NewTL.setNameLoc(TL.getNameLoc());
6528 }
6529 return Result;
6530}
6531
6532 /// Simple iterator that traverses the template arguments in a
6533 /// container that provides a \c getArgLoc() member function.
6534 ///
6535 /// This iterator is intended to be used with the iterator form of
6536 /// \c TreeTransform<Derived>::TransformTemplateArguments().
6537 template<typename ArgLocContainer>
6538 class TemplateArgumentLocContainerIterator {
6539 ArgLocContainer *Container;
6540 unsigned Index;
6541
6542 public:
6543 typedef TemplateArgumentLoc value_type;
6544 typedef TemplateArgumentLoc reference;
6545 typedef int difference_type;
6546 typedef std::input_iterator_tag iterator_category;
6547
6548 class pointer {
6549 TemplateArgumentLoc Arg;
6550
6551 public:
6552 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6553
6554 const TemplateArgumentLoc *operator->() const {
6555 return &Arg;
6556 }
6557 };
6558
6559
6560 TemplateArgumentLocContainerIterator() {}
6561
6562 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6563 unsigned Index)
6564 : Container(&Container), Index(Index) { }
6565
6566 TemplateArgumentLocContainerIterator &operator++() {
6567 ++Index;
6568 return *this;
6569 }
6570
6571 TemplateArgumentLocContainerIterator operator++(int) {
6572 TemplateArgumentLocContainerIterator Old(*this);
6573 ++(*this);
6574 return Old;
6575 }
6576
6577 TemplateArgumentLoc operator*() const {
6578 return Container->getArgLoc(Index);
6579 }
6580
6581 pointer operator->() const {
6582 return pointer(Container->getArgLoc(Index));
6583 }
6584
6585 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6586 const TemplateArgumentLocContainerIterator &Y) {
6587 return X.Container == Y.Container && X.Index == Y.Index;
6588 }
6589
6590 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6591 const TemplateArgumentLocContainerIterator &Y) {
6592 return !(X == Y);
6593 }
6594 };
6595
6596template<typename Derived>
6597QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6598 AutoTypeLoc TL) {
6599 const AutoType *T = TL.getTypePtr();
6600 QualType OldDeduced = T->getDeducedType();
6601 QualType NewDeduced;
6602 if (!OldDeduced.isNull()) {
6603 NewDeduced = getDerived().TransformType(OldDeduced);
6604 if (NewDeduced.isNull())
6605 return QualType();
6606 }
6607
6608 ConceptDecl *NewCD = nullptr;
6609 TemplateArgumentListInfo NewTemplateArgs;
6610 NestedNameSpecifierLoc NewNestedNameSpec;
6611 if (T->isConstrained()) {
6612 NewCD = cast_or_null<ConceptDecl>(getDerived().TransformDecl(
6613 TL.getConceptNameLoc(), T->getTypeConstraintConcept()));
6614
6615 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6616 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6617 typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6618 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6619 ArgIterator(TL,
6620 TL.getNumArgs()),
6621 NewTemplateArgs))
6622 return QualType();
6623
6624 if (TL.getNestedNameSpecifierLoc()) {
6625 NewNestedNameSpec
6626 = getDerived().TransformNestedNameSpecifierLoc(
6627 TL.getNestedNameSpecifierLoc());
6628 if (!NewNestedNameSpec)
6629 return QualType();
6630 }
6631 }
6632
6633 QualType Result = TL.getType();
6634 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6635 T->isDependentType() || T->isConstrained()) {
6636 // FIXME: Maybe don't rebuild if all template arguments are the same.
6637 llvm::SmallVector<TemplateArgument, 4> NewArgList;
6638 NewArgList.reserve(NewTemplateArgs.size());
6639 for (const auto &ArgLoc : NewTemplateArgs.arguments())
6640 NewArgList.push_back(ArgLoc.getArgument());
6641 Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6642 NewArgList);
6643 if (Result.isNull())
6644 return QualType();
6645 }
6646
6647 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6648 NewTL.setNameLoc(TL.getNameLoc());
6649 NewTL.setNestedNameSpecifierLoc(NewNestedNameSpec);
6650 NewTL.setTemplateKWLoc(TL.getTemplateKWLoc());
6651 NewTL.setConceptNameLoc(TL.getConceptNameLoc());
6652 NewTL.setFoundDecl(TL.getFoundDecl());
6653 NewTL.setLAngleLoc(TL.getLAngleLoc());
6654 NewTL.setRAngleLoc(TL.getRAngleLoc());
6655 NewTL.setRParenLoc(TL.getRParenLoc());
6656 for (unsigned I = 0; I < NewTL.getNumArgs(); ++I)
6657 NewTL.setArgLocInfo(I, NewTemplateArgs.arguments()[I].getLocInfo());
6658
6659 return Result;
6660}
6661
6662template <typename Derived>
6663QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6664 TypeLocBuilder &TLB,
6665 TemplateSpecializationTypeLoc TL,
6666 TemplateName Template) {
6667 TemplateArgumentListInfo NewTemplateArgs;
6668 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6669 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6670 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6671 ArgIterator;
6672 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6673 ArgIterator(TL, TL.getNumArgs()),
6674 NewTemplateArgs))
6675 return QualType();
6676
6677 // FIXME: maybe don't rebuild if all the template arguments are the same.
6678
6679 QualType Result =
6680 getDerived().RebuildTemplateSpecializationType(Template,
6681 TL.getTemplateNameLoc(),
6682 NewTemplateArgs);
6683
6684 if (!Result.isNull()) {
6685 // Specializations of template template parameters are represented as
6686 // TemplateSpecializationTypes, and substitution of type alias templates
6687 // within a dependent context can transform them into
6688 // DependentTemplateSpecializationTypes.
6689 if (isa<DependentTemplateSpecializationType>(Result)) {
6690 DependentTemplateSpecializationTypeLoc NewTL
6691 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6692 NewTL.setElaboratedKeywordLoc(SourceLocation());
6693 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6694 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6695 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6696 NewTL.setLAngleLoc(TL.getLAngleLoc());
6697 NewTL.setRAngleLoc(TL.getRAngleLoc());
6698 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6699 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6700 return Result;
6701 }
6702
6703 TemplateSpecializationTypeLoc NewTL
6704 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6705 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6706 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6707 NewTL.setLAngleLoc(TL.getLAngleLoc());
6708 NewTL.setRAngleLoc(TL.getRAngleLoc());
6709 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6710 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6711 }
6712
6713 return Result;
6714}
6715
6716template <typename Derived>
6717QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6718 TypeLocBuilder &TLB,
6719 DependentTemplateSpecializationTypeLoc TL,
6720 TemplateName Template,
6721 CXXScopeSpec &SS) {
6722 TemplateArgumentListInfo NewTemplateArgs;
6723 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6724 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6725 typedef TemplateArgumentLocContainerIterator<
6726 DependentTemplateSpecializationTypeLoc> ArgIterator;
6727 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6728 ArgIterator(TL, TL.getNumArgs()),
6729 NewTemplateArgs))
6730 return QualType();
6731
6732 // FIXME: maybe don't rebuild if all the template arguments are the same.
6733
6734 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6735 QualType Result
6736 = getSema().Context.getDependentTemplateSpecializationType(
6737 TL.getTypePtr()->getKeyword(),
6738 DTN->getQualifier(),
6739 DTN->getIdentifier(),
6740 NewTemplateArgs);
6741
6742 DependentTemplateSpecializationTypeLoc NewTL
6743 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6744 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6745 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6746 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6747 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6748 NewTL.setLAngleLoc(TL.getLAngleLoc());
6749 NewTL.setRAngleLoc(TL.getRAngleLoc());
6750 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6751 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6752 return Result;
6753 }
6754
6755 QualType Result
6756 = getDerived().RebuildTemplateSpecializationType(Template,
6757 TL.getTemplateNameLoc(),
6758 NewTemplateArgs);
6759
6760 if (!Result.isNull()) {
6761 /// FIXME: Wrap this in an elaborated-type-specifier?
6762 TemplateSpecializationTypeLoc NewTL
6763 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6764 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6765 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6766 NewTL.setLAngleLoc(TL.getLAngleLoc());
6767 NewTL.setRAngleLoc(TL.getRAngleLoc());
6768 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6769 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6770 }
6771
6772 return Result;
6773}
6774
6775template<typename Derived>
6776QualType
6777TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6778 ElaboratedTypeLoc TL) {
6779 const ElaboratedType *T = TL.getTypePtr();
6780
6781 NestedNameSpecifierLoc QualifierLoc;
6782 // NOTE: the qualifier in an ElaboratedType is optional.
6783 if (TL.getQualifierLoc()) {
6784 QualifierLoc
6785 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6786 if (!QualifierLoc)
6787 return QualType();
6788 }
6789
6790 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6791 if (NamedT.isNull())
6792 return QualType();
6793
6794 // C++0x [dcl.type.elab]p2:
6795 // If the identifier resolves to a typedef-name or the simple-template-id
6796 // resolves to an alias template specialization, the
6797 // elaborated-type-specifier is ill-formed.
6798 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6799 if (const TemplateSpecializationType *TST =
6800 NamedT->getAs<TemplateSpecializationType>()) {
6801 TemplateName Template = TST->getTemplateName();
6802 if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6803 Template.getAsTemplateDecl())) {
6804 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6805 diag::err_tag_reference_non_tag)
6806 << TAT << Sema::NTK_TypeAliasTemplate
6807 << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6808 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6809 }
6810 }
6811 }
6812
6813 QualType Result = TL.getType();
6814 if (getDerived().AlwaysRebuild() ||
6815 QualifierLoc != TL.getQualifierLoc() ||
6816 NamedT != T->getNamedType()) {
6817 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6818 T->getKeyword(),
6819 QualifierLoc, NamedT);
6820 if (Result.isNull())
6821 return QualType();
6822 }
6823
6824 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6825 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6826 NewTL.setQualifierLoc(QualifierLoc);
6827 return Result;
6828}
6829
6830template<typename Derived>
6831QualType TreeTransform<Derived>::TransformAttributedType(
6832 TypeLocBuilder &TLB,
6833 AttributedTypeLoc TL) {
6834 const AttributedType *oldType = TL.getTypePtr();
6835 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6836 if (modifiedType.isNull())
6837 return QualType();
6838
6839 // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6840 const Attr *oldAttr = TL.getAttr();
6841 const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6842 if (oldAttr && !newAttr)
6843 return QualType();
6844
6845 QualType result = TL.getType();
6846
6847 // FIXME: dependent operand expressions?
6848 if (getDerived().AlwaysRebuild() ||
6849 modifiedType != oldType->getModifiedType()) {
6850 // TODO: this is really lame; we should really be rebuilding the
6851 // equivalent type from first principles.
6852 QualType equivalentType
6853 = getDerived().TransformType(oldType->getEquivalentType());
6854 if (equivalentType.isNull())
6855 return QualType();
6856
6857 // Check whether we can add nullability; it is only represented as
6858 // type sugar, and therefore cannot be diagnosed in any other way.
6859 if (auto nullability = oldType->getImmediateNullability()) {
6860 if (!modifiedType->canHaveNullability()) {
6861 SemaRef.Diag(TL.getAttr()->getLocation(),
6862 diag::err_nullability_nonpointer)
6863 << DiagNullabilityKind(*nullability, false) << modifiedType;
6864 return QualType();
6865 }
6866 }
6867
6868 result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6869 modifiedType,
6870 equivalentType);
6871 }
6872
6873 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6874 newTL.setAttr(newAttr);
6875 return result;
6876}
6877
6878template <typename Derived>
6879QualType TreeTransform<Derived>::TransformBTFTagAttributedType(
6880 TypeLocBuilder &TLB, BTFTagAttributedTypeLoc TL) {
6881 // The BTFTagAttributedType is available for C only.
6882 llvm_unreachable("Unexpected TreeTransform for BTFTagAttributedType")::llvm::llvm_unreachable_internal("Unexpected TreeTransform for BTFTagAttributedType"
, "clang/lib/Sema/TreeTransform.h", 6882)
;
6883}
6884
6885template<typename Derived>
6886QualType
6887TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6888 ParenTypeLoc TL) {
6889 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6890 if (Inner.isNull())
6891 return QualType();
6892
6893 QualType Result = TL.getType();
6894 if (getDerived().AlwaysRebuild() ||
6895 Inner != TL.getInnerLoc().getType()) {
6896 Result = getDerived().RebuildParenType(Inner);
6897 if (Result.isNull())
6898 return QualType();
6899 }
6900
6901 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6902 NewTL.setLParenLoc(TL.getLParenLoc());
6903 NewTL.setRParenLoc(TL.getRParenLoc());
6904 return Result;
6905}
6906
6907template <typename Derived>
6908QualType
6909TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
6910 MacroQualifiedTypeLoc TL) {
6911 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6912 if (Inner.isNull())
6913 return QualType();
6914
6915 QualType Result = TL.getType();
6916 if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
6917 Result =
6918 getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
6919 if (Result.isNull())
6920 return QualType();
6921 }
6922
6923 MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
6924 NewTL.setExpansionLoc(TL.getExpansionLoc());
6925 return Result;
6926}
6927
6928template<typename Derived>
6929QualType TreeTransform<Derived>::TransformDependentNameType(
6930 TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6931 return TransformDependentNameType(TLB, TL, false);
6932}
6933
6934template<typename Derived>
6935QualType TreeTransform<Derived>::TransformDependentNameType(
6936 TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6937 const DependentNameType *T = TL.getTypePtr();
6938
6939 NestedNameSpecifierLoc QualifierLoc
6940 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6941 if (!QualifierLoc)
6942 return QualType();
6943
6944 QualType Result
6945 = getDerived().RebuildDependentNameType(T->getKeyword(),
6946 TL.getElaboratedKeywordLoc(),
6947 QualifierLoc,
6948 T->getIdentifier(),
6949 TL.getNameLoc(),
6950 DeducedTSTContext);
6951 if (Result.isNull())
6952 return QualType();
6953
6954 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6955 QualType NamedT = ElabT->getNamedType();
6956 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6957
6958 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6959 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6960 NewTL.setQualifierLoc(QualifierLoc);
6961 } else {
6962 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6963 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6964 NewTL.setQualifierLoc(QualifierLoc);
6965 NewTL.setNameLoc(TL.getNameLoc());
6966 }
6967 return Result;
6968}
6969
6970template<typename Derived>
6971QualType TreeTransform<Derived>::
6972 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6973 DependentTemplateSpecializationTypeLoc TL) {
6974 NestedNameSpecifierLoc QualifierLoc;
6975 if (TL.getQualifierLoc()) {
6976 QualifierLoc
6977 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6978 if (!QualifierLoc)
6979 return QualType();
6980 }
6981
6982 return getDerived()
6983 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6984}
6985
6986template<typename Derived>
6987QualType TreeTransform<Derived>::
6988TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6989 DependentTemplateSpecializationTypeLoc TL,
6990 NestedNameSpecifierLoc QualifierLoc) {
6991 const DependentTemplateSpecializationType *T = TL.getTypePtr();
6992
6993 TemplateArgumentListInfo NewTemplateArgs;
6994 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6995 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6996
6997 typedef TemplateArgumentLocContainerIterator<
6998 DependentTemplateSpecializationTypeLoc> ArgIterator;
6999 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
7000 ArgIterator(TL, TL.getNumArgs()),
7001 NewTemplateArgs))
7002 return QualType();
7003
7004 QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
7005 T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
7006 T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
7007 /*AllowInjectedClassName*/ false);
7008 if (Result.isNull())
7009 return QualType();
7010
7011 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
7012 QualType NamedT = ElabT->getNamedType();
7013
7014 // Copy information relevant to the template specialization.
7015 TemplateSpecializationTypeLoc NamedTL
7016 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
7017 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7018 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7019 NamedTL.setLAngleLoc(TL.getLAngleLoc());
7020 NamedTL.setRAngleLoc(TL.getRAngleLoc());
7021 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7022 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7023
7024 // Copy information relevant to the elaborated type.
7025 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7026 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7027 NewTL.setQualifierLoc(QualifierLoc);
7028 } else if (isa<DependentTemplateSpecializationType>(Result)) {
7029 DependentTemplateSpecializationTypeLoc SpecTL
7030 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
7031 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7032 SpecTL.setQualifierLoc(QualifierLoc);
7033 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7034 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7035 SpecTL.setLAngleLoc(TL.getLAngleLoc());
7036 SpecTL.setRAngleLoc(TL.getRAngleLoc());
7037 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7038 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7039 } else {
7040 TemplateSpecializationTypeLoc SpecTL
7041 = TLB.push<TemplateSpecializationTypeLoc>(Result);
7042 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7043 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7044 SpecTL.setLAngleLoc(TL.getLAngleLoc());
7045 SpecTL.setRAngleLoc(TL.getRAngleLoc());
7046 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7047 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7048 }
7049 return Result;
7050}
7051
7052template<typename Derived>
7053QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
7054 PackExpansionTypeLoc TL) {
7055 QualType Pattern
7056 = getDerived().TransformType(TLB, TL.getPatternLoc());
7057 if (Pattern.isNull())
7058 return QualType();
7059
7060 QualType Result = TL.getType();
7061 if (getDerived().AlwaysRebuild() ||
7062 Pattern != TL.getPatternLoc().getType()) {
7063 Result = getDerived().RebuildPackExpansionType(Pattern,
7064 TL.getPatternLoc().getSourceRange(),
7065 TL.getEllipsisLoc(),
7066 TL.getTypePtr()->getNumExpansions());
7067 if (Result.isNull())
7068 return QualType();
7069 }
7070
7071 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
7072 NewT.setEllipsisLoc(TL.getEllipsisLoc());
7073 return Result;
7074}
7075
7076template<typename Derived>
7077QualType
7078TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
7079 ObjCInterfaceTypeLoc TL) {
7080 // ObjCInterfaceType is never dependent.
7081 TLB.pushFullCopy(TL);
7082 return TL.getType();
7083}
7084
7085template<typename Derived>
7086QualType
7087TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
7088 ObjCTypeParamTypeLoc TL) {
7089 const ObjCTypeParamType *T = TL.getTypePtr();
7090 ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
7091 getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
7092 if (!OTP)
7093 return QualType();
7094
7095 QualType Result = TL.getType();
7096 if (getDerived().AlwaysRebuild() ||
7097 OTP != T->getDecl()) {
7098 Result = getDerived().RebuildObjCTypeParamType(OTP,
7099 TL.getProtocolLAngleLoc(),
7100 llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
7101 TL.getNumProtocols()),
7102 TL.getProtocolLocs(),
7103 TL.getProtocolRAngleLoc());
7104 if (Result.isNull())
7105 return QualType();
7106 }
7107
7108 ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
7109 if (TL.getNumProtocols()) {
7110 NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7111 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7112 NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
7113 NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7114 }
7115 return Result;
7116}
7117
7118template<typename Derived>
7119QualType
7120TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
7121 ObjCObjectTypeLoc TL) {
7122 // Transform base type.
7123 QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
7124 if (BaseType.isNull())
7125 return QualType();
7126
7127 bool AnyChanged = BaseType != TL.getBaseLoc().getType();
7128
7129 // Transform type arguments.
7130 SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
7131 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
7132 TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
7133 TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
7134 QualType TypeArg = TypeArgInfo->getType();
7135 if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
7136 AnyChanged = true;
7137
7138 // We have a pack expansion. Instantiate it.
7139 const auto *PackExpansion = PackExpansionLoc.getType()
7140 ->castAs<PackExpansionType>();
7141 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7142 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
7143 Unexpanded);
7144 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", 7144, __extension__ __PRETTY_FUNCTION__
))
;
7145
7146 // Determine whether the set of unexpanded parameter packs can
7147 // and should be expanded.
7148 TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
7149 bool Expand = false;
7150 bool RetainExpansion = false;
7151 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
7152 if (getDerived().TryExpandParameterPacks(
7153 PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
7154 Unexpanded, Expand, RetainExpansion, NumExpansions))
7155 return QualType();
7156
7157 if (!Expand) {
7158 // We can't expand this pack expansion into separate arguments yet;
7159 // just substitute into the pattern and create a new pack expansion
7160 // type.
7161 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7162
7163 TypeLocBuilder TypeArgBuilder;
7164 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7165 QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
7166 PatternLoc);
7167 if (NewPatternType.isNull())
7168 return QualType();
7169
7170 QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
7171 NewPatternType, NumExpansions);
7172 auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
7173 NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
7174 NewTypeArgInfos.push_back(
7175 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
7176 continue;
7177 }
7178
7179 // Substitute into the pack expansion pattern for each slice of the
7180 // pack.
7181 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
7182 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
7183
7184 TypeLocBuilder TypeArgBuilder;
7185 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7186
7187 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
7188 PatternLoc);
7189 if (NewTypeArg.isNull())
7190 return QualType();
7191
7192 NewTypeArgInfos.push_back(
7193 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7194 }
7195
7196 continue;
7197 }
7198
7199 TypeLocBuilder TypeArgBuilder;
7200 TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
7201 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
7202 if (NewTypeArg.isNull())
7203 return QualType();
7204
7205 // If nothing changed, just keep the old TypeSourceInfo.
7206 if (NewTypeArg == TypeArg) {
7207 NewTypeArgInfos.push_back(TypeArgInfo);
7208 continue;
7209 }
7210
7211 NewTypeArgInfos.push_back(
7212 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7213 AnyChanged = true;
7214 }
7215
7216 QualType Result = TL.getType();
7217 if (getDerived().AlwaysRebuild() || AnyChanged) {
7218 // Rebuild the type.
7219 Result = getDerived().RebuildObjCObjectType(
7220 BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
7221 TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
7222 llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7223 TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7224
7225 if (Result.isNull())
7226 return QualType();
7227 }
7228
7229 ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
7230 NewT.setHasBaseTypeAsWritten(true);
7231 NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
7232 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
7233 NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
7234 NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
7235 NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7236 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7237 NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
7238 NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7239 return Result;
7240}
7241
7242template<typename Derived>
7243QualType
7244TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
7245 ObjCObjectPointerTypeLoc TL) {
7246 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
7247 if (PointeeType.isNull())
7248 return QualType();
7249
7250 QualType Result = TL.getType();
7251 if (getDerived().AlwaysRebuild() ||
7252 PointeeType != TL.getPointeeLoc().getType()) {
7253 Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
7254 TL.getStarLoc());
7255 if (Result.isNull())
7256 return QualType();
7257 }
7258
7259 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
7260 NewT.setStarLoc(TL.getStarLoc());
7261 return Result;
7262}
7263
7264//===----------------------------------------------------------------------===//
7265// Statement transformation
7266//===----------------------------------------------------------------------===//
7267template<typename Derived>
7268StmtResult
7269TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
7270 return S;
7271}
7272
7273template<typename Derived>
7274StmtResult
7275TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
7276 return getDerived().TransformCompoundStmt(S, false);
7277}
7278
7279template<typename Derived>
7280StmtResult
7281TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
7282 bool IsStmtExpr) {
7283 Sema::CompoundScopeRAII CompoundScope(getSema());
7284
7285 const Stmt *ExprResult = S->getStmtExprResult();
7286 bool SubStmtInvalid = false;
7287 bool SubStmtChanged = false;
7288 SmallVector<Stmt*, 8> Statements;
7289 for (auto *B : S->body()) {
7290 StmtResult Result = getDerived().TransformStmt(
7291 B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
7292
7293 if (Result.isInvalid()) {
7294 // Immediately fail if this was a DeclStmt, since it's very
7295 // likely that this will cause problems for future statements.
7296 if (isa<DeclStmt>(B))
7297 return StmtError();
7298
7299 // Otherwise, just keep processing substatements and fail later.
7300 SubStmtInvalid = true;
7301 continue;
7302 }
7303
7304 SubStmtChanged = SubStmtChanged || Result.get() != B;
7305 Statements.push_back(Result.getAs<Stmt>());
7306 }
7307
7308 if (SubStmtInvalid)
7309 return StmtError();
7310
7311 if (!getDerived().AlwaysRebuild() &&
7312 !SubStmtChanged)
7313 return S;
7314
7315 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
7316 Statements,
7317 S->getRBracLoc(),
7318 IsStmtExpr);
7319}
7320
7321template<typename Derived>
7322StmtResult
7323TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
7324 ExprResult LHS, RHS;
7325 {
7326 EnterExpressionEvaluationContext Unevaluated(
7327 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7328
7329 // Transform the left-hand case value.
7330 LHS = getDerived().TransformExpr(S->getLHS());
7331 LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
7332 if (LHS.isInvalid())
7333 return StmtError();
7334
7335 // Transform the right-hand case value (for the GNU case-range extension).
7336 RHS = getDerived().TransformExpr(S->getRHS());
7337 RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
7338 if (RHS.isInvalid())
7339 return StmtError();
7340 }
7341
7342 // Build the case statement.
7343 // Case statements are always rebuilt so that they will attached to their
7344 // transformed switch statement.
7345 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
7346 LHS.get(),
7347 S->getEllipsisLoc(),
7348 RHS.get(),
7349 S->getColonLoc());
7350 if (Case.isInvalid())
7351 return StmtError();
7352
7353 // Transform the statement following the case
7354 StmtResult SubStmt =
7355 getDerived().TransformStmt(S->getSubStmt());
7356 if (SubStmt.isInvalid())
7357 return StmtError();
7358
7359 // Attach the body to the case statement
7360 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
7361}
7362
7363template <typename Derived>
7364StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
7365 // Transform the statement following the default case
7366 StmtResult SubStmt =
7367 getDerived().TransformStmt(S->getSubStmt());
7368 if (SubStmt.isInvalid())
7369 return StmtError();
7370
7371 // Default statements are always rebuilt
7372 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
7373 SubStmt.get());
7374}
7375
7376template<typename Derived>
7377StmtResult
7378TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
7379 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7380 if (SubStmt.isInvalid())
7381 return StmtError();
7382
7383 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
7384 S->getDecl());
7385 if (!LD)
7386 return StmtError();
7387
7388 // If we're transforming "in-place" (we're not creating new local
7389 // declarations), assume we're replacing the old label statement
7390 // and clear out the reference to it.
7391 if (LD == S->getDecl())
7392 S->getDecl()->setStmt(nullptr);
7393
7394 // FIXME: Pass the real colon location in.
7395 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
7396 cast<LabelDecl>(LD), SourceLocation(),
7397 SubStmt.get());
7398}
7399
7400template <typename Derived>
7401const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
7402 if (!R)
7403 return R;
7404
7405 switch (R->getKind()) {
7406// Transform attributes with a pragma spelling by calling TransformXXXAttr.
7407#define ATTR(X)
7408#define PRAGMA_SPELLING_ATTR(X) \
7409 case attr::X: \
7410 return getDerived().Transform##X##Attr(cast<X##Attr>(R));
7411#include "clang/Basic/AttrList.inc"
7412 default:
7413 return R;
7414 }
7415}
7416
7417template <typename Derived>
7418StmtResult
7419TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
7420 StmtDiscardKind SDK) {
7421 bool AttrsChanged = false;
7422 SmallVector<const Attr *, 1> Attrs;
7423
7424 // Visit attributes and keep track if any are transformed.
7425 for (const auto *I : S->getAttrs()) {
7426 const Attr *R = getDerived().TransformAttr(I);
7427 AttrsChanged |= (I != R);
7428 if (R)
7429 Attrs.push_back(R);
7430 }
7431
7432 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7433 if (SubStmt.isInvalid())
7434 return StmtError();
7435
7436 if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
7437 return S;
7438
7439 // If transforming the attributes failed for all of the attributes in the
7440 // statement, don't make an AttributedStmt without attributes.
7441 if (Attrs.empty())
7442 return SubStmt;
7443
7444 return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
7445 SubStmt.get());
7446}
7447
7448template<typename Derived>
7449StmtResult
7450TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
7451 // Transform the initialization statement
7452 StmtResult Init = getDerived().TransformStmt(S->getInit());
7453 if (Init.isInvalid())
7454 return StmtError();
7455
7456 Sema::ConditionResult Cond;
7457 if (!S->isConsteval()) {
7458 // Transform the condition
7459 Cond = getDerived().TransformCondition(
7460 S->getIfLoc(), S->getConditionVariable(), S->getCond(),
7461 S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
7462 : Sema::ConditionKind::Boolean);
7463 if (Cond.isInvalid())
7464 return StmtError();
7465 }
7466
7467 // If this is a constexpr if, determine which arm we should instantiate.
7468 llvm::Optional<bool> ConstexprConditionValue;
7469 if (S->isConstexpr())
7470 ConstexprConditionValue = Cond.getKnownValue();
7471
7472 // Transform the "then" branch.
7473 StmtResult Then;
7474 if (!ConstexprConditionValue || *ConstexprConditionValue) {
7475 Then = getDerived().TransformStmt(S->getThen());
7476 if (Then.isInvalid())
7477 return StmtError();
7478 } else {
7479 Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
7480 }
7481
7482 // Transform the "else" branch.
7483 StmtResult Else;
7484 if (!ConstexprConditionValue || !*ConstexprConditionValue) {
7485 Else = getDerived().TransformStmt(S->getElse());
7486 if (Else.isInvalid())
7487 return StmtError();
7488 }
7489
7490 if (!getDerived().AlwaysRebuild() &&
7491 Init.get() == S->getInit() &&
7492 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7493 Then.get() == S->getThen() &&
7494 Else.get() == S->getElse())
7495 return S;
7496
7497 return getDerived().RebuildIfStmt(
7498 S->getIfLoc(), S->getStatementKind(), S->getLParenLoc(), Cond,
7499 S->getRParenLoc(), Init.get(), Then.get(), S->getElseLoc(), Else.get());
7500}
7501
7502template<typename Derived>
7503StmtResult
7504TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
7505 // Transform the initialization statement
7506 StmtResult Init = getDerived().TransformStmt(S->getInit());
7507 if (Init.isInvalid())
7508 return StmtError();
7509
7510 // Transform the condition.
7511 Sema::ConditionResult Cond = getDerived().TransformCondition(
7512 S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7513 Sema::ConditionKind::Switch);
7514 if (Cond.isInvalid())
7515 return StmtError();
7516
7517 // Rebuild the switch statement.
7518 StmtResult Switch =
7519 getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), S->getLParenLoc(),
7520 Init.get(), Cond, S->getRParenLoc());
7521 if (Switch.isInvalid())
7522 return StmtError();
7523
7524 // Transform the body of the switch statement.
7525 StmtResult Body = getDerived().TransformStmt(S->getBody());
7526 if (Body.isInvalid())
7527 return StmtError();
7528
7529 // Complete the switch statement.
7530 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7531 Body.get());
7532}
7533
7534template<typename Derived>
7535StmtResult
7536TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7537 // Transform the condition
7538 Sema::ConditionResult Cond = getDerived().TransformCondition(
7539 S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7540 Sema::ConditionKind::Boolean);
7541 if (Cond.isInvalid())
7542 return StmtError();
7543
7544 // Transform the body
7545 StmtResult Body = getDerived().TransformStmt(S->getBody());
7546 if (Body.isInvalid())
7547 return StmtError();
7548
7549 if (!getDerived().AlwaysRebuild() &&
7550 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7551 Body.get() == S->getBody())
7552 return Owned(S);
7553
7554 return getDerived().RebuildWhileStmt(S->getWhileLoc(), S->getLParenLoc(),
7555 Cond, S->getRParenLoc(), Body.get());
7556}
7557
7558template<typename Derived>
7559StmtResult
7560TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7561 // Transform the body
7562 StmtResult Body = getDerived().TransformStmt(S->getBody());
7563 if (Body.isInvalid())
7564 return StmtError();
7565
7566 // Transform the condition
7567 ExprResult Cond = getDerived().TransformExpr(S->getCond());
7568 if (Cond.isInvalid())
7569 return StmtError();
7570
7571 if (!getDerived().AlwaysRebuild() &&
7572 Cond.get() == S->getCond() &&
7573 Body.get() == S->getBody())
7574 return S;
7575
7576 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7577 /*FIXME:*/S->getWhileLoc(), Cond.get(),
7578 S->getRParenLoc());
7579}
7580
7581template<typename Derived>
7582StmtResult
7583TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7584 if (getSema().getLangOpts().OpenMP)
7585 getSema().startOpenMPLoop();
7586
7587 // Transform the initialization statement
7588 StmtResult Init = getDerived().TransformStmt(S->getInit());
7589 if (Init.isInvalid())
7590 return StmtError();
7591
7592 // In OpenMP loop region loop control variable must be captured and be
7593 // private. Perform analysis of first part (if any).
7594 if (getSema().getLangOpts().OpenMP && Init.isUsable())
7595 getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7596
7597 // Transform the condition
7598 Sema::ConditionResult Cond = getDerived().TransformCondition(
7599 S->getForLoc(), S->getConditionVariable(), S->getCond(),
7600 Sema::ConditionKind::Boolean);
7601 if (Cond.isInvalid())
7602 return StmtError();
7603
7604 // Transform the increment
7605 ExprResult Inc = getDerived().TransformExpr(S->getInc());
7606 if (Inc.isInvalid())
7607 return StmtError();
7608
7609 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7610 if (S->getInc() && !FullInc.get())
7611 return StmtError();
7612
7613 // Transform the body
7614 StmtResult Body = getDerived().TransformStmt(S->getBody());
7615 if (Body.isInvalid())
7616 return StmtError();
7617
7618 if (!getDerived().AlwaysRebuild() &&
7619 Init.get() == S->getInit() &&
7620 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7621 Inc.get() == S->getInc() &&
7622 Body.get() == S->getBody())
7623 return S;
7624
7625 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7626 Init.get(), Cond, FullInc,
7627 S->getRParenLoc(), Body.get());
7628}
7629
7630template<typename Derived>
7631StmtResult
7632TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7633 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7634 S->getLabel());
7635 if (!LD)
7636 return StmtError();
7637
7638 // Goto statements must always be rebuilt, to resolve the label.
7639 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7640 cast<LabelDecl>(LD));
7641}
7642
7643template<typename Derived>
7644StmtResult
7645TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7646 ExprResult Target = getDerived().TransformExpr(S->getTarget());
7647 if (Target.isInvalid())
7648 return StmtError();
7649 Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7650
7651 if (!getDerived().AlwaysRebuild() &&
7652 Target.get() == S->getTarget())
7653 return S;
7654
7655 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7656 Target.get());
7657}
7658
7659template<typename Derived>
7660StmtResult
7661TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7662 return S;
7663}
7664
7665template<typename Derived>
7666StmtResult
7667TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7668 return S;
7669}
7670
7671template<typename Derived>
7672StmtResult
7673TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7674 ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7675 /*NotCopyInit*/false);
7676 if (Result.isInvalid())
7677 return StmtError();
7678
7679 // FIXME: We always rebuild the return statement because there is no way
7680 // to tell whether the return type of the function has changed.
7681 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7682}
7683
7684template<typename Derived>
7685StmtResult
7686TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7687 bool DeclChanged = false;
7688 SmallVector<Decl *, 4> Decls;
7689 for (auto *D : S->decls()) {
7690 Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7691 if (!Transformed)
7692 return StmtError();
7693
7694 if (Transformed != D)
7695 DeclChanged = true;
7696
7697 Decls.push_back(Transformed);
7698 }
7699
7700 if (!getDerived().AlwaysRebuild() && !DeclChanged)
7701 return S;
7702
7703 return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7704}
7705
7706template<typename Derived>
7707StmtResult
7708TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7709
7710 SmallVector<Expr*, 8> Constraints;
7711 SmallVector<Expr*, 8> Exprs;
7712 SmallVector<IdentifierInfo *, 4> Names;
7713
7714 ExprResult AsmString;
7715 SmallVector<Expr*, 8> Clobbers;
7716
7717 bool ExprsChanged = false;
7718
7719 // Go through the outputs.
7720 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7721 Names.push_back(S->getOutputIdentifier(I));
7722
7723 // No need to transform the constraint literal.
7724 Constraints.push_back(S->getOutputConstraintLiteral(I));
7725
7726 // Transform the output expr.
7727 Expr *OutputExpr = S->getOutputExpr(I);
7728 ExprResult Result = getDerived().TransformExpr(OutputExpr);
7729 if (Result.isInvalid())
7730 return StmtError();
7731
7732 ExprsChanged |= Result.get() != OutputExpr;
7733
7734 Exprs.push_back(Result.get());
7735 }
7736
7737 // Go through the inputs.
7738 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7739 Names.push_back(S->getInputIdentifier(I));
7740
7741 // No need to transform the constraint literal.
7742 Constraints.push_back(S->getInputConstraintLiteral(I));
7743
7744 // Transform the input expr.
7745 Expr *InputExpr = S->getInputExpr(I);
7746 ExprResult Result = getDerived().TransformExpr(InputExpr);
7747 if (Result.isInvalid())
7748 return StmtError();
7749
7750 ExprsChanged |= Result.get() != InputExpr;
7751
7752 Exprs.push_back(Result.get());
7753 }
7754
7755 // Go through the Labels.
7756 for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7757 Names.push_back(S->getLabelIdentifier(I));
7758
7759 ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7760 if (Result.isInvalid())
7761 return StmtError();
7762 ExprsChanged |= Result.get() != S->getLabelExpr(I);
7763 Exprs.push_back(Result.get());
7764 }
7765 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7766 return S;
7767
7768 // Go through the clobbers.
7769 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7770 Clobbers.push_back(S->getClobberStringLiteral(I));
7771
7772 // No need to transform the asm string literal.
7773 AsmString = S->getAsmString();
7774 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7775 S->isVolatile(), S->getNumOutputs(),
7776 S->getNumInputs(), Names.data(),
7777 Constraints, Exprs, AsmString.get(),
7778 Clobbers, S->getNumLabels(),
7779 S->getRParenLoc());
7780}
7781
7782template<typename Derived>
7783StmtResult
7784TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7785 ArrayRef<Token> AsmToks =
7786 llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
7787
7788 bool HadError = false, HadChange = false;
7789
7790 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7791 SmallVector<Expr*, 8> TransformedExprs;
7792 TransformedExprs.reserve(SrcExprs.size());
7793 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7794 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7795 if (!Result.isUsable()) {
7796 HadError = true;
7797 } else {
7798 HadChange |= (Result.get() != SrcExprs[i]);
7799 TransformedExprs.push_back(Result.get());
7800 }
7801 }
7802
7803 if (HadError) return StmtError();
7804 if (!HadChange && !getDerived().AlwaysRebuild())
7805 return Owned(S);
7806
7807 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7808 AsmToks, S->getAsmString(),
7809 S->getNumOutputs(), S->getNumInputs(),
7810 S->getAllConstraints(), S->getClobbers(),
7811 TransformedExprs, S->getEndLoc());
7812}
7813
7814// C++ Coroutines TS
7815
7816template<typename Derived>
7817StmtResult
7818TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7819 auto *ScopeInfo = SemaRef.getCurFunction();
7820 auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7821 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", 7825, __extension__ __PRETTY_FUNCTION__
))
7822 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", 7825, __extension__ __PRETTY_FUNCTION__
))
7823 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", 7825, __extension__ __PRETTY_FUNCTION__
))
7824 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", 7825, __extension__ __PRETTY_FUNCTION__
))
7825 "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", 7825, __extension__ __PRETTY_FUNCTION__
))
;
7826
7827 // Set that we have (possibly-invalid) suspend points before we do anything
7828 // that may fail.
7829 ScopeInfo->setNeedsCoroutineSuspends(false);
7830
7831 // We re-build the coroutine promise object (and the coroutine parameters its
7832 // type and constructor depend on) based on the types used in our current
7833 // function. We must do so, and set it on the current FunctionScopeInfo,
7834 // before attempting to transform the other parts of the coroutine body
7835 // statement, such as the implicit suspend statements (because those
7836 // statements reference the FunctionScopeInfo::CoroutinePromise).
7837 if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7838 return StmtError();
7839 auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7840 if (!Promise)
7841 return StmtError();
7842 getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7843 ScopeInfo->CoroutinePromise = Promise;
7844
7845 // Transform the implicit coroutine statements constructed using dependent
7846 // types during the previous parse: initial and final suspensions, the return
7847 // object, and others. We also transform the coroutine function's body.
7848 StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7849 if (InitSuspend.isInvalid())
7850 return StmtError();
7851 StmtResult FinalSuspend =
7852 getDerived().TransformStmt(S->getFinalSuspendStmt());
7853 if (FinalSuspend.isInvalid() ||
7854 !SemaRef.checkFinalSuspendNoThrow(FinalSuspend.get()))
7855 return StmtError();
7856 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7857 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", 7857, __extension__ __PRETTY_FUNCTION__
))
;
7858
7859 StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7860 if (BodyRes.isInvalid())
7861 return StmtError();
7862
7863 CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7864 if (Builder.isInvalid())
7865 return StmtError();
7866
7867 Expr *ReturnObject = S->getReturnValueInit();
7868 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", 7868, __extension__ __PRETTY_FUNCTION__
))
;
7869 ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7870 /*NoCopyInit*/ false);
7871 if (Res.isInvalid())
7872 return StmtError();
7873 Builder.ReturnValue = Res.get();
7874
7875 // If during the previous parse the coroutine still had a dependent promise
7876 // statement, we may need to build some implicit coroutine statements
7877 // (such as exception and fallthrough handlers) for the first time.
7878 if (S->hasDependentPromiseType()) {
7879 // We can only build these statements, however, if the current promise type
7880 // is not dependent.
7881 if (!Promise->getType()->isDependentType()) {
7882 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", 7884, __extension__ __PRETTY_FUNCTION__
))
7883 !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", 7884, __extension__ __PRETTY_FUNCTION__
))
7884 "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", 7884, __extension__ __PRETTY_FUNCTION__
))
;
7885 if (!Builder.buildDependentStatements())
7886 return StmtError();
7887 }
7888 } else {
7889 if (auto *OnFallthrough = S->getFallthroughHandler()) {
7890 StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7891 if (Res.isInvalid())
7892 return StmtError();
7893 Builder.OnFallthrough = Res.get();
7894 }
7895
7896 if (auto *OnException = S->getExceptionHandler()) {
7897 StmtResult Res = getDerived().TransformStmt(OnException);
7898 if (Res.isInvalid())
7899 return StmtError();
7900 Builder.OnException = Res.get();
7901 }
7902
7903 if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7904 StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7905 if (Res.isInvalid())
7906 return StmtError();
7907 Builder.ReturnStmtOnAllocFailure = Res.get();
7908 }
7909
7910 // Transform any additional statements we may have already built
7911 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", 7912, __extension__ __PRETTY_FUNCTION__
))
7912 "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", 7912, __extension__ __PRETTY_FUNCTION__
))
;
7913 ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7914 if (AllocRes.isInvalid())
7915 return StmtError();
7916 Builder.Allocate = AllocRes.get();
7917
7918 ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7919 if (DeallocRes.isInvalid())
7920 return StmtError();
7921 Builder.Deallocate = DeallocRes.get();
7922
7923 if (auto *ReturnStmt = S->getReturnStmt()) {
7924 StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7925 if (Res.isInvalid())
7926 return StmtError();
7927 Builder.ReturnStmt = Res.get();
7928 }
7929 }
7930
7931 return getDerived().RebuildCoroutineBodyStmt(Builder);
7932}
7933
7934template<typename Derived>
7935StmtResult
7936TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7937 ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7938 /*NotCopyInit*/false);
7939 if (Result.isInvalid())
7940 return StmtError();
7941
7942 // Always rebuild; we don't know if this needs to be injected into a new
7943 // context or if the promise type has changed.
7944 return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7945 S->isImplicit());
7946}
7947
7948template<typename Derived>
7949ExprResult
7950TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7951 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7952 /*NotCopyInit*/false);
7953 if (Result.isInvalid())
7954 return ExprError();
7955
7956 // Always rebuild; we don't know if this needs to be injected into a new
7957 // context or if the promise type has changed.
7958 return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
7959 E->isImplicit());
7960}
7961
7962template <typename Derived>
7963ExprResult
7964TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7965 ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7966 /*NotCopyInit*/ false);
7967 if (OperandResult.isInvalid())
7968 return ExprError();
7969
7970 ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7971 E->getOperatorCoawaitLookup());
7972
7973 if (LookupResult.isInvalid())
7974 return ExprError();
7975
7976 // Always rebuild; we don't know if this needs to be injected into a new
7977 // context or if the promise type has changed.
7978 return getDerived().RebuildDependentCoawaitExpr(
7979 E->getKeywordLoc(), OperandResult.get(),
7980 cast<UnresolvedLookupExpr>(LookupResult.get()));
7981}
7982
7983template<typename Derived>
7984ExprResult
7985TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7986 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7987 /*NotCopyInit*/false);
7988 if (Result.isInvalid())
7989 return ExprError();
7990
7991 // Always rebuild; we don't know if this needs to be injected into a new
7992 // context or if the promise type has changed.
7993 return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7994}
7995
7996// Objective-C Statements.
7997
7998template<typename Derived>
7999StmtResult
8000TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
8001 // Transform the body of the @try.
8002 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
8003 if (TryBody.isInvalid())
8004 return StmtError();
8005
8006 // Transform the @catch statements (if present).
8007 bool AnyCatchChanged = false;
8008 SmallVector<Stmt*, 8> CatchStmts;
8009 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
8010 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
8011 if (Catch.isInvalid())
8012 return StmtError();
8013 if (Catch.get() != S->getCatchStmt(I))
8014 AnyCatchChanged = true;
8015 CatchStmts.push_back(Catch.get());
8016 }
8017
8018 // Transform the @finally statement (if present).
8019 StmtResult Finally;
8020 if (S->getFinallyStmt()) {
8021 Finally = getDerived().TransformStmt(S->getFinallyStmt());
8022 if (Finally.isInvalid())
8023 return StmtError();
8024 }
8025
8026 // If nothing changed, just retain this statement.
8027 if (!getDerived().AlwaysRebuild() &&
8028 TryBody.get() == S->getTryBody() &&
8029 !AnyCatchChanged &&
8030 Finally.get() == S->getFinallyStmt())
8031 return S;
8032
8033 // Build a new statement.
8034 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
8035 CatchStmts, Finally.get());
8036}
8037
8038template<typename Derived>
8039StmtResult
8040TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
8041 // Transform the @catch parameter, if there is one.
8042 VarDecl *Var = nullptr;
8043 if (VarDecl *FromVar = S->getCatchParamDecl()) {
8044 TypeSourceInfo *TSInfo = nullptr;
8045 if (FromVar->getTypeSourceInfo()) {
8046 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
8047 if (!TSInfo)
8048 return StmtError();
8049 }
8050
8051 QualType T;
8052 if (TSInfo)
8053 T = TSInfo->getType();
8054 else {
8055 T = getDerived().TransformType(FromVar->getType());
8056 if (T.isNull())
8057 return StmtError();
8058 }
8059
8060 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
8061 if (!Var)
8062 return StmtError();
8063 }
8064
8065 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
8066 if (Body.isInvalid())
8067 return StmtError();
8068
8069 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
8070 S->getRParenLoc(),
8071 Var, Body.get());
8072}
8073
8074template<typename Derived>
8075StmtResult
8076TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
8077 // Transform the body.
8078 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
8079 if (Body.isInvalid())
8080 return StmtError();
8081
8082 // If nothing changed, just retain this statement.
8083 if (!getDerived().AlwaysRebuild() &&
8084 Body.get() == S->getFinallyBody())
8085 return S;
8086
8087 // Build a new statement.
8088 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
8089 Body.get());
8090}
8091
8092template<typename Derived>
8093StmtResult
8094TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
8095 ExprResult Operand;
8096 if (S->getThrowExpr()) {
8097 Operand = getDerived().TransformExpr(S->getThrowExpr());
8098 if (Operand.isInvalid())
8099 return StmtError();
8100 }
8101
8102 if (!getDerived().AlwaysRebuild() &&
8103 Operand.get() == S->getThrowExpr())
8104 return S;
8105
8106 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
8107}
8108
8109template<typename Derived>
8110StmtResult
8111TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
8112 ObjCAtSynchronizedStmt *S) {
8113 // Transform the object we are locking.
8114 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
8115 if (Object.isInvalid())
8116 return StmtError();
8117 Object =
8118 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
8119 Object.get());
8120 if (Object.isInvalid())
8121 return StmtError();
8122
8123 // Transform the body.
8124 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
8125 if (Body.isInvalid())
8126 return StmtError();
8127
8128 // If nothing change, just retain the current statement.
8129 if (!getDerived().AlwaysRebuild() &&
8130 Object.get() == S->getSynchExpr() &&
8131 Body.get() == S->getSynchBody())
8132 return S;
8133
8134 // Build a new statement.
8135 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
8136 Object.get(), Body.get());
8137}
8138
8139template<typename Derived>
8140StmtResult
8141TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
8142 ObjCAutoreleasePoolStmt *S) {
8143 // Transform the body.
8144 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
8145 if (Body.isInvalid())
8146 return StmtError();
8147
8148 // If nothing changed, just retain this statement.
8149 if (!getDerived().AlwaysRebuild() &&
8150 Body.get() == S->getSubStmt())
8151 return S;
8152
8153 // Build a new statement.
8154 return getDerived().RebuildObjCAutoreleasePoolStmt(
8155 S->getAtLoc(), Body.get());
8156}
8157
8158template<typename Derived>
8159StmtResult
8160TreeTransform<Derived>::TransformObjCForCollectionStmt(
8161 ObjCForCollectionStmt *S) {
8162 // Transform the element statement.
8163 StmtResult Element =
8164 getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
8165 if (Element.isInvalid())
8166 return StmtError();
8167
8168 // Transform the collection expression.
8169 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
8170 if (Collection.isInvalid())
8171 return StmtError();
8172
8173 // Transform the body.
8174 StmtResult Body = getDerived().TransformStmt(S->getBody());
8175 if (Body.isInvalid())
8176 return StmtError();
8177
8178 // If nothing changed, just retain this statement.
8179 if (!getDerived().AlwaysRebuild() &&
8180 Element.get() == S->getElement() &&
8181 Collection.get() == S->getCollection() &&
8182 Body.get() == S->getBody())
8183 return S;
8184
8185 // Build a new statement.
8186 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
8187 Element.get(),
8188 Collection.get(),
8189 S->getRParenLoc(),
8190 Body.get());
8191}
8192
8193template <typename Derived>
8194StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
8195 // Transform the exception declaration, if any.
8196 VarDecl *Var = nullptr;
8197 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
8198 TypeSourceInfo *T =
8199 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
8200 if (!T)
8201 return StmtError();
8202
8203 Var = getDerived().RebuildExceptionDecl(
8204 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
8205 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
8206 if (!Var || Var->isInvalidDecl())
8207 return StmtError();
8208 }
8209
8210 // Transform the actual exception handler.
8211 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
8212 if (Handler.isInvalid())
8213 return StmtError();
8214
8215 if (!getDerived().AlwaysRebuild() && !Var &&
8216 Handler.get() == S->getHandlerBlock())
8217 return S;
8218
8219 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
8220}
8221
8222template <typename Derived>
8223StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
8224 // Transform the try block itself.
8225 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8226 if (TryBlock.isInvalid())
8227 return StmtError();
8228
8229 // Transform the handlers.
8230 bool HandlerChanged = false;
8231 SmallVector<Stmt *, 8> Handlers;
8232 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
8233 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
8234 if (Handler.isInvalid())
8235 return StmtError();
8236
8237 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
8238 Handlers.push_back(Handler.getAs<Stmt>());
8239 }
8240
8241 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8242 !HandlerChanged)
8243 return S;
8244
8245 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
8246 Handlers);
8247}
8248
8249template<typename Derived>
8250StmtResult
8251TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
8252 StmtResult Init =
8253 S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
8254 if (Init.isInvalid())
8255 return StmtError();
8256
8257 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
8258 if (Range.isInvalid())
8259 return StmtError();
8260
8261 StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
8262 if (Begin.isInvalid())
8263 return StmtError();
8264 StmtResult End = getDerived().TransformStmt(S->getEndStmt());
8265 if (End.isInvalid())
8266 return StmtError();
8267
8268 ExprResult Cond = getDerived().TransformExpr(S->getCond());
8269 if (Cond.isInvalid())
8270 return StmtError();
8271 if (Cond.get())
8272 Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
8273 if (Cond.isInvalid())
8274 return StmtError();
8275 if (Cond.get())
8276 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
8277
8278 ExprResult Inc = getDerived().TransformExpr(S->getInc());
8279 if (Inc.isInvalid())
8280 return StmtError();
8281 if (Inc.get())
8282 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
8283
8284 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
8285 if (LoopVar.isInvalid())
8286 return StmtError();
8287
8288 StmtResult NewStmt = S;
8289 if (getDerived().AlwaysRebuild() ||
8290 Init.get() != S->getInit() ||
8291 Range.get() != S->getRangeStmt() ||
8292 Begin.get() != S->getBeginStmt() ||
8293 End.get() != S->getEndStmt() ||
8294 Cond.get() != S->getCond() ||
8295 Inc.get() != S->getInc() ||
8296 LoopVar.get() != S->getLoopVarStmt()) {
8297 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8298 S->getCoawaitLoc(), Init.get(),
8299 S->getColonLoc(), Range.get(),
8300 Begin.get(), End.get(),
8301 Cond.get(),
8302 Inc.get(), LoopVar.get(),
8303 S->getRParenLoc());
8304 if (NewStmt.isInvalid() && LoopVar.get() != S->getLoopVarStmt()) {
8305 // Might not have attached any initializer to the loop variable.
8306 getSema().ActOnInitializerError(
8307 cast<DeclStmt>(LoopVar.get())->getSingleDecl());
8308 return StmtError();
8309 }
8310 }
8311
8312 StmtResult Body = getDerived().TransformStmt(S->getBody());
8313 if (Body.isInvalid())
8314 return StmtError();
8315
8316 // Body has changed but we didn't rebuild the for-range statement. Rebuild
8317 // it now so we have a new statement to attach the body to.
8318 if (Body.get() != S->getBody() && NewStmt.get() == S) {
8319 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8320 S->getCoawaitLoc(), Init.get(),
8321 S->getColonLoc(), Range.get(),
8322 Begin.get(), End.get(),
8323 Cond.get(),
8324 Inc.get(), LoopVar.get(),
8325 S->getRParenLoc());
8326 if (NewStmt.isInvalid())
8327 return StmtError();
8328 }
8329
8330 if (NewStmt.get() == S)
8331 return S;
8332
8333 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
8334}
8335
8336template<typename Derived>
8337StmtResult
8338TreeTransform<Derived>::TransformMSDependentExistsStmt(
8339 MSDependentExistsStmt *S) {
8340 // Transform the nested-name-specifier, if any.
8341 NestedNameSpecifierLoc QualifierLoc;
8342 if (S->getQualifierLoc()) {
8343 QualifierLoc
8344 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
8345 if (!QualifierLoc)
8346 return StmtError();
8347 }
8348
8349 // Transform the declaration name.
8350 DeclarationNameInfo NameInfo = S->getNameInfo();
8351 if (NameInfo.getName()) {
8352 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8353 if (!NameInfo.getName())
8354 return StmtError();
8355 }
8356
8357 // Check whether anything changed.
8358 if (!getDerived().AlwaysRebuild() &&
8359 QualifierLoc == S->getQualifierLoc() &&
8360 NameInfo.getName() == S->getNameInfo().getName())
8361 return S;
8362
8363 // Determine whether this name exists, if we can.
8364 CXXScopeSpec SS;
8365 SS.Adopt(QualifierLoc);
8366 bool Dependent = false;
8367 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
8368 case Sema::IER_Exists:
8369 if (S->isIfExists())
8370 break;
8371
8372 return new (getSema().Context) NullStmt(S->getKeywordLoc());
8373
8374 case Sema::IER_DoesNotExist:
8375 if (S->isIfNotExists())
8376 break;
8377
8378 return new (getSema().Context) NullStmt(S->getKeywordLoc());
8379
8380 case Sema::IER_Dependent:
8381 Dependent = true;
8382 break;
8383
8384 case Sema::IER_Error:
8385 return StmtError();
8386 }
8387
8388 // We need to continue with the instantiation, so do so now.
8389 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
8390 if (SubStmt.isInvalid())
8391 return StmtError();
8392
8393 // If we have resolved the name, just transform to the substatement.
8394 if (!Dependent)
8395 return SubStmt;
8396
8397 // The name is still dependent, so build a dependent expression again.
8398 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
8399 S->isIfExists(),
8400 QualifierLoc,
8401 NameInfo,
8402 SubStmt.get());
8403}
8404
8405template<typename Derived>
8406ExprResult
8407TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
8408 NestedNameSpecifierLoc QualifierLoc;
8409 if (E->getQualifierLoc()) {
8410 QualifierLoc
8411 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8412 if (!QualifierLoc)
8413 return ExprError();
8414 }
8415
8416 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
8417 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
8418 if (!PD)
8419 return ExprError();
8420
8421 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8422 if (Base.isInvalid())
8423 return ExprError();
8424
8425 return new (SemaRef.getASTContext())
8426 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
8427 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
8428 QualifierLoc, E->getMemberLoc());
8429}
8430
8431template <typename Derived>
8432ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
8433 MSPropertySubscriptExpr *E) {
8434 auto BaseRes = getDerived().TransformExpr(E->getBase());
8435 if (BaseRes.isInvalid())
8436 return ExprError();
8437 auto IdxRes = getDerived().TransformExpr(E->getIdx());
8438 if (IdxRes.isInvalid())
8439 return ExprError();
8440
8441 if (!getDerived().AlwaysRebuild() &&
8442 BaseRes.get() == E->getBase() &&
8443 IdxRes.get() == E->getIdx())
8444 return E;
8445
8446 return getDerived().RebuildArraySubscriptExpr(
8447 BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
8448}
8449
8450template <typename Derived>
8451StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
8452 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8453 if (TryBlock.isInvalid())
8454 return StmtError();
8455
8456 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
8457 if (Handler.isInvalid())
8458 return StmtError();
8459
8460 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8461 Handler.get() == S->getHandler())
8462 return S;
8463
8464 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
8465 TryBlock.get(), Handler.get());
8466}
8467
8468template <typename Derived>
8469StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
8470 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8471 if (Block.isInvalid())
8472 return StmtError();
8473
8474 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
8475}
8476
8477template <typename Derived>
8478StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
8479 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
8480 if (FilterExpr.isInvalid())
8481 return StmtError();
8482
8483 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8484 if (Block.isInvalid())
8485 return StmtError();
8486
8487 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
8488 Block.get());
8489}
8490
8491template <typename Derived>
8492StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
8493 if (isa<SEHFinallyStmt>(Handler))
8494 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
8495 else
8496 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
8497}
8498
8499template<typename Derived>
8500StmtResult
8501TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
8502 return S;
8503}
8504
8505//===----------------------------------------------------------------------===//
8506// OpenMP directive transformation
8507//===----------------------------------------------------------------------===//
8508
8509template <typename Derived>
8510StmtResult
8511TreeTransform<Derived>::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
8512 // OMPCanonicalLoops are eliminated during transformation, since they will be
8513 // recomputed by semantic analysis of the associated OMPLoopBasedDirective
8514 // after transformation.
8515 return getDerived().TransformStmt(L->getLoopStmt());
8516}
8517
8518template <typename Derived>
8519StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
8520 OMPExecutableDirective *D) {
8521
8522 // Transform the clauses
8523 llvm::SmallVector<OMPClause *, 16> TClauses;
8524 ArrayRef<OMPClause *> Clauses = D->clauses();
8525 TClauses.reserve(Clauses.size());
8526 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8527 I != E; ++I) {
8528 if (*I) {
8529 getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8530 OMPClause *Clause = getDerived().TransformOMPClause(*I);
8531 getDerived().getSema().EndOpenMPClause();
8532 if (Clause)
8533 TClauses.push_back(Clause);
8534 } else {
8535 TClauses.push_back(nullptr);
8536 }
8537 }
8538 StmtResult AssociatedStmt;
8539 if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8540 getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8541 /*CurScope=*/nullptr);
8542 StmtResult Body;
8543 {
8544 Sema::CompoundScopeRAII CompoundScope(getSema());
8545 Stmt *CS;
8546 if (D->getDirectiveKind() == OMPD_atomic ||
8547 D->getDirectiveKind() == OMPD_critical ||
8548 D->getDirectiveKind() == OMPD_section ||
8549 D->getDirectiveKind() == OMPD_master)
8550 CS = D->getAssociatedStmt();
8551 else
8552 CS = D->getRawStmt();
8553 Body = getDerived().TransformStmt(CS);
8554 if (Body.isUsable() && isOpenMPLoopDirective(D->getDirectiveKind()) &&
8555 getSema().getLangOpts().OpenMPIRBuilder)
8556 Body = getDerived().RebuildOMPCanonicalLoop(Body.get());
8557 }
8558 AssociatedStmt =
8559 getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8560 if (AssociatedStmt.isInvalid()) {
8561 return StmtError();
8562 }
8563 }
8564 if (TClauses.size() != Clauses.size()) {
8565 return StmtError();
8566 }
8567
8568 // Transform directive name for 'omp critical' directive.
8569 DeclarationNameInfo DirName;
8570 if (D->getDirectiveKind() == OMPD_critical) {
8571 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8572 DirName = getDerived().TransformDeclarationNameInfo(DirName);
8573 }
8574 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8575 if (D->getDirectiveKind() == OMPD_cancellation_point) {
8576 CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8577 } else if (D->getDirectiveKind() == OMPD_cancel) {
8578 CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8579 }
8580
8581 return getDerived().RebuildOMPExecutableDirective(
8582 D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8583 AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
8584}
8585
8586template <typename Derived>
8587StmtResult
8588TreeTransform<Derived>::TransformOMPMetaDirective(OMPMetaDirective *D) {
8589 // TODO: Fix This
8590 SemaRef.Diag(D->getBeginLoc(), diag::err_omp_instantiation_not_supported)
8591 << getOpenMPDirectiveName(D->getDirectiveKind());
8592 return StmtError();
8593}
8594
8595template <typename Derived>
8596StmtResult
8597TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8598 DeclarationNameInfo DirName;
8599 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8600 D->getBeginLoc());
8601 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8602 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8603 return Res;
8604}
8605
8606template <typename Derived>
8607StmtResult
8608TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8609 DeclarationNameInfo DirName;
8610 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8611 D->getBeginLoc());
8612 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8613 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8614 return Res;
8615}
8616
8617template <typename Derived>
8618StmtResult
8619TreeTransform<Derived>::TransformOMPTileDirective(OMPTileDirective *D) {
8620 DeclarationNameInfo DirName;
8621 getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8622 nullptr, D->getBeginLoc());
8623 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8624 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8625 return Res;
8626}
8627
8628template <typename Derived>
8629StmtResult
8630TreeTransform<Derived>::TransformOMPUnrollDirective(OMPUnrollDirective *D) {
8631 DeclarationNameInfo DirName;
8632 getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8633 nullptr, D->getBeginLoc());
8634 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8635 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8636 return Res;
8637}
8638
8639template <typename Derived>
8640StmtResult
8641TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8642 DeclarationNameInfo DirName;
8643 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8644 D->getBeginLoc());
8645 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8646 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8647 return Res;
8648}
8649
8650template <typename Derived>
8651StmtResult
8652TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8653 DeclarationNameInfo DirName;
8654 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8655 D->getBeginLoc());
8656 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8657 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8658 return Res;
8659}
8660
8661template <typename Derived>
8662StmtResult
8663TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8664 DeclarationNameInfo DirName;
8665 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8666 D->getBeginLoc());
8667 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8668 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8669 return Res;
8670}
8671
8672template <typename Derived>
8673StmtResult
8674TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8675 DeclarationNameInfo DirName;
8676 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8677 D->getBeginLoc());
8678 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8679 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8680 return Res;
8681}
8682
8683template <typename Derived>
8684StmtResult
8685TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8686 DeclarationNameInfo DirName;
8687 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8688 D->getBeginLoc());
8689 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8690 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8691 return Res;
8692}
8693
8694template <typename Derived>
8695StmtResult
8696TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8697 DeclarationNameInfo DirName;
8698 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8699 D->getBeginLoc());
8700 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8701 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8702 return Res;
8703}
8704
8705template <typename Derived>
8706StmtResult
8707TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8708 getDerived().getSema().StartOpenMPDSABlock(
8709 OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8710 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8711 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8712 return Res;
8713}
8714
8715template <typename Derived>
8716StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8717 OMPParallelForDirective *D) {
8718 DeclarationNameInfo DirName;
8719 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8720 nullptr, D->getBeginLoc());
8721 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8722 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8723 return Res;
8724}
8725
8726template <typename Derived>
8727StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8728 OMPParallelForSimdDirective *D) {
8729 DeclarationNameInfo DirName;
8730 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8731 nullptr, D->getBeginLoc());
8732 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8733 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8734 return Res;
8735}
8736
8737template <typename Derived>
8738StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
8739 OMPParallelMasterDirective *D) {
8740 DeclarationNameInfo DirName;
8741 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
8742 nullptr, D->getBeginLoc());
8743 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8744 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8745 return Res;
8746}
8747
8748template <typename Derived>
8749StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8750 OMPParallelSectionsDirective *D) {
8751 DeclarationNameInfo DirName;
8752 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8753 nullptr, D->getBeginLoc());
8754 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8755 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8756 return Res;
8757}
8758
8759template <typename Derived>
8760StmtResult
8761TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8762 DeclarationNameInfo DirName;
8763 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8764 D->getBeginLoc());
8765 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8766 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8767 return Res;
8768}
8769
8770template <typename Derived>
8771StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8772 OMPTaskyieldDirective *D) {
8773 DeclarationNameInfo DirName;
8774 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8775 D->getBeginLoc());
8776 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8777 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8778 return Res;
8779}
8780
8781template <typename Derived>
8782StmtResult
8783TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8784 DeclarationNameInfo DirName;
8785 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8786 D->getBeginLoc());
8787 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8788 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8789 return Res;
8790}
8791
8792template <typename Derived>
8793StmtResult
8794TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8795 DeclarationNameInfo DirName;
8796 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, 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 TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8805 OMPTaskgroupDirective *D) {
8806 DeclarationNameInfo DirName;
8807 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, 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>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8817 DeclarationNameInfo DirName;
8818 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8819 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>::TransformOMPDepobjDirective(OMPDepobjDirective *D) {
8828 DeclarationNameInfo DirName;
8829 getDerived().getSema().StartOpenMPDSABlock(OMPD_depobj, DirName, nullptr,
8830 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>::TransformOMPScanDirective(OMPScanDirective *D) {
8839 DeclarationNameInfo DirName;
8840 getDerived().getSema().StartOpenMPDSABlock(OMPD_scan, 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>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8850 DeclarationNameInfo DirName;
8851 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, 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>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8861 DeclarationNameInfo DirName;
8862 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, 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>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8872 DeclarationNameInfo DirName;
8873 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, 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 TreeTransform<Derived>::TransformOMPTargetDataDirective(
8882 OMPTargetDataDirective *D) {
8883 DeclarationNameInfo DirName;
8884 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, 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 TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8893 OMPTargetEnterDataDirective *D) {
8894 DeclarationNameInfo DirName;
8895 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8896 nullptr, D->getBeginLoc());
8897 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8898 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8899 return Res;
8900}
8901
8902template <typename Derived>
8903StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8904 OMPTargetExitDataDirective *D) {
8905 DeclarationNameInfo DirName;
8906 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8907 nullptr, D->getBeginLoc());
8908 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8909 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8910 return Res;
8911}
8912
8913template <typename Derived>
8914StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8915 OMPTargetParallelDirective *D) {
8916 DeclarationNameInfo DirName;
8917 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8918 nullptr, D->getBeginLoc());
8919 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8920 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8921 return Res;
8922}
8923
8924template <typename Derived>
8925StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8926 OMPTargetParallelForDirective *D) {
8927 DeclarationNameInfo DirName;
8928 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8929 nullptr, D->getBeginLoc());
8930 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8931 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8932 return Res;
8933}
8934
8935template <typename Derived>
8936StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8937 OMPTargetUpdateDirective *D) {
8938 DeclarationNameInfo DirName;
8939 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8940 nullptr, D->getBeginLoc());
8941 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8942 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8943 return Res;
8944}
8945
8946template <typename Derived>
8947StmtResult
8948TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8949 DeclarationNameInfo DirName;
8950 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8951 D->getBeginLoc());
8952 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8953 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8954 return Res;
8955}
8956
8957template <typename Derived>
8958StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8959 OMPCancellationPointDirective *D) {
8960 DeclarationNameInfo DirName;
8961 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
8962 nullptr, D->getBeginLoc());
8963 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8964 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8965 return Res;
8966}
8967
8968template <typename Derived>
8969StmtResult
8970TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8971 DeclarationNameInfo DirName;
8972 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
8973 D->getBeginLoc());
8974 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8975 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8976 return Res;
8977}
8978
8979template <typename Derived>
8980StmtResult
8981TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8982 DeclarationNameInfo DirName;
8983 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8984 D->getBeginLoc());
8985 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8986 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8987 return Res;
8988}
8989
8990template <typename Derived>
8991StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
8992 OMPTaskLoopSimdDirective *D) {
8993 DeclarationNameInfo DirName;
8994 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
8995 nullptr, D->getBeginLoc());
8996 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8997 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8998 return Res;
8999}
9000
9001template <typename Derived>
9002StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
9003 OMPMasterTaskLoopDirective *D) {
9004 DeclarationNameInfo DirName;
9005 getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
9006 nullptr, D->getBeginLoc());
9007 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9008 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9009 return Res;
9010}
9011
9012template <typename Derived>
9013StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
9014 OMPMasterTaskLoopSimdDirective *D) {
9015 DeclarationNameInfo DirName;
9016 getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
9017 nullptr, D->getBeginLoc());
9018 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9019 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9020 return Res;
9021}
9022
9023template <typename Derived>
9024StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
9025 OMPParallelMasterTaskLoopDirective *D) {
9026 DeclarationNameInfo DirName;
9027 getDerived().getSema().StartOpenMPDSABlock(
9028 OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
9029 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9030 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9031 return Res;
9032}
9033
9034template <typename Derived>
9035StmtResult
9036TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
9037 OMPParallelMasterTaskLoopSimdDirective *D) {
9038 DeclarationNameInfo DirName;
9039 getDerived().getSema().StartOpenMPDSABlock(
9040 OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9041 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9042 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9043 return Res;
9044}
9045
9046template <typename Derived>
9047StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
9048 OMPDistributeDirective *D) {
9049 DeclarationNameInfo DirName;
9050 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
9051 D->getBeginLoc());
9052 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9053 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9054 return Res;
9055}
9056
9057template <typename Derived>
9058StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
9059 OMPDistributeParallelForDirective *D) {
9060 DeclarationNameInfo DirName;
9061 getDerived().getSema().StartOpenMPDSABlock(
9062 OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9063 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9064 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9065 return Res;
9066}
9067
9068template <typename Derived>
9069StmtResult
9070TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
9071 OMPDistributeParallelForSimdDirective *D) {
9072 DeclarationNameInfo DirName;
9073 getDerived().getSema().StartOpenMPDSABlock(
9074 OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9075 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9076 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9077 return Res;
9078}
9079
9080template <typename Derived>
9081StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
9082 OMPDistributeSimdDirective *D) {
9083 DeclarationNameInfo DirName;
9084 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
9085 nullptr, D->getBeginLoc());
9086 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9087 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9088 return Res;
9089}
9090
9091template <typename Derived>
9092StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
9093 OMPTargetParallelForSimdDirective *D) {
9094 DeclarationNameInfo DirName;
9095 getDerived().getSema().StartOpenMPDSABlock(
9096 OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9097 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9098 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9099 return Res;
9100}
9101
9102template <typename Derived>
9103StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
9104 OMPTargetSimdDirective *D) {
9105 DeclarationNameInfo DirName;
9106 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
9107 D->getBeginLoc());
9108 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9109 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9110 return Res;
9111}
9112
9113template <typename Derived>
9114StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
9115 OMPTeamsDistributeDirective *D) {
9116 DeclarationNameInfo DirName;
9117 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
9118 nullptr, D->getBeginLoc());
9119 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9120 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9121 return Res;
9122}
9123
9124template <typename Derived>
9125StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
9126 OMPTeamsDistributeSimdDirective *D) {
9127 DeclarationNameInfo DirName;
9128 getDerived().getSema().StartOpenMPDSABlock(
9129 OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9130 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9131 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9132 return Res;
9133}
9134
9135template <typename Derived>
9136StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
9137 OMPTeamsDistributeParallelForSimdDirective *D) {
9138 DeclarationNameInfo DirName;
9139 getDerived().getSema().StartOpenMPDSABlock(
9140 OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
9141 D->getBeginLoc());
9142 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9143 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9144 return Res;
9145}
9146
9147template <typename Derived>
9148StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
9149 OMPTeamsDistributeParallelForDirective *D) {
9150 DeclarationNameInfo DirName;
9151 getDerived().getSema().StartOpenMPDSABlock(
9152 OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9153 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9154 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9155 return Res;
9156}
9157
9158template <typename Derived>
9159StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
9160 OMPTargetTeamsDirective *D) {
9161 DeclarationNameInfo DirName;
9162 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
9163 nullptr, D->getBeginLoc());
9164 auto Res = getDerived().TransformOMPExecutableDirective(D);
9165 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9166 return Res;
9167}
9168
9169template <typename Derived>
9170StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
9171 OMPTargetTeamsDistributeDirective *D) {
9172 DeclarationNameInfo DirName;
9173 getDerived().getSema().StartOpenMPDSABlock(
9174 OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
9175 auto Res = getDerived().TransformOMPExecutableDirective(D);
9176 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9177 return Res;
9178}
9179
9180template <typename Derived>
9181StmtResult
9182TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
9183 OMPTargetTeamsDistributeParallelForDirective *D) {
9184 DeclarationNameInfo DirName;
9185 getDerived().getSema().StartOpenMPDSABlock(
9186 OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
9187 D->getBeginLoc());
9188 auto Res = getDerived().TransformOMPExecutableDirective(D);
9189 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9190 return Res;
9191}
9192
9193template <typename Derived>
9194StmtResult TreeTransform<Derived>::
9195 TransformOMPTargetTeamsDistributeParallelForSimdDirective(
9196 OMPTargetTeamsDistributeParallelForSimdDirective *D) {
9197 DeclarationNameInfo DirName;
9198 getDerived().getSema().StartOpenMPDSABlock(
9199 OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
9200 D->getBeginLoc());
9201 auto Res = getDerived().TransformOMPExecutableDirective(D);
9202 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9203 return Res;
9204}
9205
9206template <typename Derived>
9207StmtResult
9208TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
9209 OMPTargetTeamsDistributeSimdDirective *D) {
9210 DeclarationNameInfo DirName;
9211 getDerived().getSema().StartOpenMPDSABlock(
9212 OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9213 auto Res = getDerived().TransformOMPExecutableDirective(D);
9214 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9215 return Res;
9216}
9217
9218template <typename Derived>
9219StmtResult
9220TreeTransform<Derived>::TransformOMPInteropDirective(OMPInteropDirective *D) {
9221 DeclarationNameInfo DirName;
9222 getDerived().getSema().StartOpenMPDSABlock(OMPD_interop, DirName, nullptr,
9223 D->getBeginLoc());
9224 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9225 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9226 return Res;
9227}
9228
9229template <typename Derived>
9230StmtResult
9231TreeTransform<Derived>::TransformOMPDispatchDirective(OMPDispatchDirective *D) {
9232 DeclarationNameInfo DirName;
9233 getDerived().getSema().StartOpenMPDSABlock(OMPD_dispatch, DirName, nullptr,
9234 D->getBeginLoc());
9235 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9236 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9237 return Res;
9238}
9239
9240template <typename Derived>
9241StmtResult
9242TreeTransform<Derived>::TransformOMPMaskedDirective(OMPMaskedDirective *D) {
9243 DeclarationNameInfo DirName;
9244 getDerived().getSema().StartOpenMPDSABlock(OMPD_masked, DirName, nullptr,
9245 D->getBeginLoc());
9246 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9247 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9248 return Res;
9249}
9250
9251template <typename Derived>
9252StmtResult TreeTransform<Derived>::TransformOMPGenericLoopDirective(
9253 OMPGenericLoopDirective *D) {
9254 DeclarationNameInfo DirName;
9255 getDerived().getSema().StartOpenMPDSABlock(OMPD_loop, DirName, nullptr,
9256 D->getBeginLoc());
9257 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9258 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9259 return Res;
9260}
9261
9262template <typename Derived>
9263StmtResult TreeTransform<Derived>::TransformOMPTeamsGenericLoopDirective(
9264 OMPTeamsGenericLoopDirective *D) {
9265 DeclarationNameInfo DirName;
9266 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_loop, DirName, nullptr,
9267 D->getBeginLoc());
9268 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9269 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9270 return Res;
9271}
9272
9273template <typename Derived>
9274StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsGenericLoopDirective(
9275 OMPTargetTeamsGenericLoopDirective *D) {
9276 DeclarationNameInfo DirName;
9277 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams_loop, DirName,
9278 nullptr, D->getBeginLoc());
9279 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9280 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9281 return Res;
9282}
9283
9284template <typename Derived>
9285StmtResult TreeTransform<Derived>::TransformOMPParallelGenericLoopDirective(
9286 OMPParallelGenericLoopDirective *D) {
9287 DeclarationNameInfo DirName;
9288 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_loop, DirName,
9289 nullptr, D->getBeginLoc());
9290 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9291 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9292 return Res;
9293}
9294
9295template <typename Derived>
9296StmtResult
9297TreeTransform<Derived>::TransformOMPTargetParallelGenericLoopDirective(
9298 OMPTargetParallelGenericLoopDirective *D) {
9299 DeclarationNameInfo DirName;
9300 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_loop, DirName,
9301 nullptr, D->getBeginLoc());
9302 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9303 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9304 return Res;
9305}
9306
9307//===----------------------------------------------------------------------===//
9308// OpenMP clause transformation
9309//===----------------------------------------------------------------------===//
9310template <typename Derived>
9311OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
9312 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9313 if (Cond.isInvalid())
9314 return nullptr;
9315 return getDerived().RebuildOMPIfClause(
9316 C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
9317 C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
9318}
9319
9320template <typename Derived>
9321OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
9322 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9323 if (Cond.isInvalid())
9324 return nullptr;
9325 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
9326 C->getLParenLoc(), C->getEndLoc());
9327}
9328
9329template <typename Derived>
9330OMPClause *
9331TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
9332 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
9333 if (NumThreads.isInvalid())
9334 return nullptr;
9335 return getDerived().RebuildOMPNumThreadsClause(
9336 NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9337}
9338
9339template <typename Derived>
9340OMPClause *
9341TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
9342 ExprResult E = getDerived().TransformExpr(C->getSafelen());
9343 if (E.isInvalid())
9344 return nullptr;
9345 return getDerived().RebuildOMPSafelenClause(
9346 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9347}
9348
9349template <typename Derived>
9350OMPClause *
9351TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
9352 ExprResult E = getDerived().TransformExpr(C->getAllocator());
9353 if (E.isInvalid())
9354 return nullptr;
9355 return getDerived().RebuildOMPAllocatorClause(
9356 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9357}
9358
9359template <typename Derived>
9360OMPClause *
9361TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
9362 ExprResult E = getDerived().TransformExpr(C->getSimdlen());
9363 if (E.isInvalid())
9364 return nullptr;
9365 return getDerived().RebuildOMPSimdlenClause(
9366 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9367}
9368
9369template <typename Derived>
9370OMPClause *TreeTransform<Derived>::TransformOMPSizesClause(OMPSizesClause *C) {
9371 SmallVector<Expr *, 4> TransformedSizes;
9372 TransformedSizes.reserve(C->getNumSizes());
9373 bool Changed = false;
9374 for (Expr *E : C->getSizesRefs()) {
9375 if (!E) {
9376 TransformedSizes.push_back(nullptr);
9377 continue;
9378 }
9379
9380 ExprResult T = getDerived().TransformExpr(E);
9381 if (T.isInvalid())
9382 return nullptr;
9383 if (E != T.get())
9384 Changed = true;
9385 TransformedSizes.push_back(T.get());
9386 }
9387
9388 if (!Changed && !getDerived().AlwaysRebuild())
9389 return C;
9390 return RebuildOMPSizesClause(TransformedSizes, C->getBeginLoc(),
9391 C->getLParenLoc(), C->getEndLoc());
9392}
9393
9394template <typename Derived>
9395OMPClause *TreeTransform<Derived>::TransformOMPFullClause(OMPFullClause *C) {
9396 if (!getDerived().AlwaysRebuild())
9397 return C;
9398 return RebuildOMPFullClause(C->getBeginLoc(), C->getEndLoc());
9399}
9400
9401template <typename Derived>
9402OMPClause *
9403TreeTransform<Derived>::TransformOMPPartialClause(OMPPartialClause *C) {
9404 ExprResult T = getDerived().TransformExpr(C->getFactor());
9405 if (T.isInvalid())
9406 return nullptr;
9407 Expr *Factor = T.get();
9408 bool Changed = Factor != C->getFactor();
9409
9410 if (!Changed && !getDerived().AlwaysRebuild())
9411 return C;
9412 return RebuildOMPPartialClause(Factor, C->getBeginLoc(), C->getLParenLoc(),
9413 C->getEndLoc());
9414}
9415
9416template <typename Derived>
9417OMPClause *
9418TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
9419 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
9420 if (E.isInvalid())
9421 return nullptr;
9422 return getDerived().RebuildOMPCollapseClause(
9423 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9424}
9425
9426template <typename Derived>
9427OMPClause *
9428TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
9429 return getDerived().RebuildOMPDefaultClause(
9430 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
9431 C->getLParenLoc(), C->getEndLoc());
9432}
9433
9434template <typename Derived>
9435OMPClause *
9436TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
9437 return getDerived().RebuildOMPProcBindClause(
9438 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
9439 C->getLParenLoc(), C->getEndLoc());
9440}
9441
9442template <typename Derived>
9443OMPClause *
9444TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
9445 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9446 if (E.isInvalid())
9447 return nullptr;
9448 return getDerived().RebuildOMPScheduleClause(
9449 C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
9450 C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9451 C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
9452 C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9453}
9454
9455template <typename Derived>
9456OMPClause *
9457TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
9458 ExprResult E;
9459 if (auto *Num = C->getNumForLoops()) {
9460 E = getDerived().TransformExpr(Num);
9461 if (E.isInvalid())
9462 return nullptr;
9463 }
9464 return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
9465 C->getLParenLoc(), E.get());
9466}
9467
9468template <typename Derived>
9469OMPClause *
9470TreeTransform<Derived>::TransformOMPDetachClause(OMPDetachClause *C) {
9471 ExprResult E;
9472 if (Expr *Evt = C->getEventHandler()) {
9473 E = getDerived().TransformExpr(Evt);
9474 if (E.isInvalid())
9475 return nullptr;
9476 }
9477 return getDerived().RebuildOMPDetachClause(E.get(), C->getBeginLoc(),
9478 C->getLParenLoc(), C->getEndLoc());
9479}
9480
9481template <typename Derived>
9482OMPClause *
9483TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
9484 // No need to rebuild this clause, no template-dependent parameters.
9485 return C;
9486}
9487
9488template <typename Derived>
9489OMPClause *
9490TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
9491 // No need to rebuild this clause, no template-dependent parameters.
9492 return C;
9493}
9494
9495template <typename Derived>
9496OMPClause *
9497TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
9498 // No need to rebuild this clause, no template-dependent parameters.
9499 return C;
9500}
9501
9502template <typename Derived>
9503OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
9504 // No need to rebuild this clause, no template-dependent parameters.
9505 return C;
9506}
9507
9508template <typename Derived>
9509OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
9510 // No need to rebuild this clause, no template-dependent parameters.
9511 return C;
9512}
9513
9514template <typename Derived>
9515OMPClause *
9516TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
9517 // No need to rebuild this clause, no template-dependent parameters.
9518 return C;
9519}
9520
9521template <typename Derived>
9522OMPClause *
9523TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
9524 // No need to rebuild this clause, no template-dependent parameters.
9525 return C;
9526}
9527
9528template <typename Derived>
9529OMPClause *
9530TreeTransform<Derived>::TransformOMPCompareClause(OMPCompareClause *C) {
9531 // No need to rebuild this clause, no template-dependent parameters.
9532 return C;
9533}
9534
9535template <typename Derived>
9536OMPClause *
9537TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
9538 // No need to rebuild this clause, no template-dependent parameters.
9539 return C;
9540}
9541
9542template <typename Derived>
9543OMPClause *
9544TreeTransform<Derived>::TransformOMPAcqRelClause(OMPAcqRelClause *C) {
9545 // No need to rebuild this clause, no template-dependent parameters.
9546 return C;
9547}
9548
9549template <typename Derived>
9550OMPClause *
9551TreeTransform<Derived>::TransformOMPAcquireClause(OMPAcquireClause *C) {
9552 // No need to rebuild this clause, no template-dependent parameters.
9553 return C;
9554}
9555
9556template <typename Derived>
9557OMPClause *
9558TreeTransform<Derived>::TransformOMPReleaseClause(OMPReleaseClause *C) {
9559 // No need to rebuild this clause, no template-dependent parameters.
9560 return C;
9561}
9562
9563template <typename Derived>
9564OMPClause *
9565TreeTransform<Derived>::TransformOMPRelaxedClause(OMPRelaxedClause *C) {
9566 // No need to rebuild this clause, no template-dependent parameters.
9567 return C;
9568}
9569
9570template <typename Derived>
9571OMPClause *
9572TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
9573 // No need to rebuild this clause, no template-dependent parameters.
9574 return C;
9575}
9576
9577template <typename Derived>
9578OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
9579 // No need to rebuild this clause, no template-dependent parameters.
9580 return C;
9581}
9582
9583template <typename Derived>
9584OMPClause *
9585TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
9586 // No need to rebuild this clause, no template-dependent parameters.
9587 return C;
9588}
9589
9590template <typename Derived>
9591OMPClause *TreeTransform<Derived>::TransformOMPInitClause(OMPInitClause *C) {
9592 ExprResult IVR = getDerived().TransformExpr(C->getInteropVar());
9593 if (IVR.isInvalid())
9594 return nullptr;
9595
9596 llvm::SmallVector<Expr *, 8> PrefExprs;
9597 PrefExprs.reserve(C->varlist_size() - 1);
9598 for (Expr *E : llvm::drop_begin(C->varlists())) {
9599 ExprResult ER = getDerived().TransformExpr(cast<Expr>(E));
9600 if (ER.isInvalid())
9601 return nullptr;
9602 PrefExprs.push_back(ER.get());
9603 }
9604 return getDerived().RebuildOMPInitClause(
9605 IVR.get(), PrefExprs, C->getIsTarget(), C->getIsTargetSync(),
9606 C->getBeginLoc(), C->getLParenLoc(), C->getVarLoc(), C->getEndLoc());
9607}
9608
9609template <typename Derived>
9610OMPClause *TreeTransform<Derived>::TransformOMPUseClause(OMPUseClause *C) {
9611 ExprResult ER = getDerived().TransformExpr(C->getInteropVar());
9612 if (ER.isInvalid())
9613 return nullptr;
9614 return getDerived().RebuildOMPUseClause(ER.get(), C->getBeginLoc(),
9615 C->getLParenLoc(), C->getVarLoc(),
9616 C->getEndLoc());
9617}
9618
9619template <typename Derived>
9620OMPClause *
9621TreeTransform<Derived>::TransformOMPDestroyClause(OMPDestroyClause *C) {
9622 ExprResult ER;
9623 if (Expr *IV = C->getInteropVar()) {
9624 ER = getDerived().TransformExpr(IV);
9625 if (ER.isInvalid())
9626 return nullptr;
9627 }
9628 return getDerived().RebuildOMPDestroyClause(ER.get(), C->getBeginLoc(),
9629 C->getLParenLoc(), C->getVarLoc(),
9630 C->getEndLoc());
9631}
9632
9633template <typename Derived>
9634OMPClause *
9635TreeTransform<Derived>::TransformOMPNovariantsClause(OMPNovariantsClause *C) {
9636 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9637 if (Cond.isInvalid())
9638 return nullptr;
9639 return getDerived().RebuildOMPNovariantsClause(
9640 Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9641}
9642
9643template <typename Derived>
9644OMPClause *
9645TreeTransform<Derived>::TransformOMPNocontextClause(OMPNocontextClause *C) {
9646 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9647 if (Cond.isInvalid())
9648 return nullptr;
9649 return getDerived().RebuildOMPNocontextClause(
9650 Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9651}
9652
9653template <typename Derived>
9654OMPClause *
9655TreeTransform<Derived>::TransformOMPFilterClause(OMPFilterClause *C) {
9656 ExprResult ThreadID = getDerived().TransformExpr(C->getThreadID());
9657 if (ThreadID.isInvalid())
9658 return nullptr;
9659 return getDerived().RebuildOMPFilterClause(ThreadID.get(), C->getBeginLoc(),
9660 C->getLParenLoc(), C->getEndLoc());
9661}
9662
9663template <typename Derived>
9664OMPClause *TreeTransform<Derived>::TransformOMPAlignClause(OMPAlignClause *C) {
9665 ExprResult E = getDerived().TransformExpr(C->getAlignment());
9666 if (E.isInvalid())
9667 return nullptr;
9668 return getDerived().RebuildOMPAlignClause(E.get(), C->getBeginLoc(),
9669 C->getLParenLoc(), C->getEndLoc());
9670}
9671
9672template <typename Derived>
9673OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
9674 OMPUnifiedAddressClause *C) {
9675 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", 9675)
;
9676}
9677
9678template <typename Derived>
9679OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
9680 OMPUnifiedSharedMemoryClause *C) {
9681 llvm_unreachable(::llvm::llvm_unreachable_internal("unified_shared_memory clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9682)
9682 "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", 9682)
;
9683}
9684
9685template <typename Derived>
9686OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
9687 OMPReverseOffloadClause *C) {
9688 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", 9688)
;
9689}
9690
9691template <typename Derived>
9692OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
9693 OMPDynamicAllocatorsClause *C) {
9694 llvm_unreachable(::llvm::llvm_unreachable_internal("dynamic_allocators clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9695)
9695 "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", 9695)
;
9696}
9697
9698template <typename Derived>
9699OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
9700 OMPAtomicDefaultMemOrderClause *C) {
9701 llvm_unreachable(::llvm::llvm_unreachable_internal("atomic_default_mem_order clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9702)
9702 "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", 9702)
;
9703}
9704
9705template <typename Derived>
9706OMPClause *
9707TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
9708 llvm::SmallVector<Expr *, 16> Vars;
9709 Vars.reserve(C->varlist_size());
9710 for (auto *VE : C->varlists()) {
9711 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9712 if (EVar.isInvalid())
9713 return nullptr;
9714 Vars.push_back(EVar.get());
9715 }
9716 return getDerived().RebuildOMPPrivateClause(
9717 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9718}
9719
9720template <typename Derived>
9721OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
9722 OMPFirstprivateClause *C) {
9723 llvm::SmallVector<Expr *, 16> Vars;
9724 Vars.reserve(C->varlist_size());
9725 for (auto *VE : C->varlists()) {
9726 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9727 if (EVar.isInvalid())
9728 return nullptr;
9729 Vars.push_back(EVar.get());
9730 }
9731 return getDerived().RebuildOMPFirstprivateClause(
9732 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9733}
9734
9735template <typename Derived>
9736OMPClause *
9737TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
9738 llvm::SmallVector<Expr *, 16> Vars;
9739 Vars.reserve(C->varlist_size());
9740 for (auto *VE : C->varlists()) {
9741 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9742 if (EVar.isInvalid())
9743 return nullptr;
9744 Vars.push_back(EVar.get());
9745 }
9746 return getDerived().RebuildOMPLastprivateClause(
9747 Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
9748 C->getLParenLoc(), C->getEndLoc());
9749}
9750
9751template <typename Derived>
9752OMPClause *
9753TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
9754 llvm::SmallVector<Expr *, 16> Vars;
9755 Vars.reserve(C->varlist_size());
9756 for (auto *VE : C->varlists()) {
9757 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9758 if (EVar.isInvalid())
9759 return nullptr;
9760 Vars.push_back(EVar.get());
9761 }
9762 return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
9763 C->getLParenLoc(), C->getEndLoc());
9764}
9765
9766template <typename Derived>
9767OMPClause *
9768TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
9769 llvm::SmallVector<Expr *, 16> Vars;
9770 Vars.reserve(C->varlist_size());
9771 for (auto *VE : C->varlists()) {
9772 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9773 if (EVar.isInvalid())
9774 return nullptr;
9775 Vars.push_back(EVar.get());
9776 }
9777 CXXScopeSpec ReductionIdScopeSpec;
9778 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9779
9780 DeclarationNameInfo NameInfo = C->getNameInfo();
9781 if (NameInfo.getName()) {
9782 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9783 if (!NameInfo.getName())
9784 return nullptr;
9785 }
9786 // Build a list of all UDR decls with the same names ranged by the Scopes.
9787 // The Scope boundary is a duplication of the previous decl.
9788 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9789 for (auto *E : C->reduction_ops()) {
9790 // Transform all the decls.
9791 if (E) {
9792 auto *ULE = cast<UnresolvedLookupExpr>(E);
9793 UnresolvedSet<8> Decls;
9794 for (auto *D : ULE->decls()) {
9795 NamedDecl *InstD =
9796 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9797 Decls.addDecl(InstD, InstD->getAccess());
9798 }
9799 UnresolvedReductions.push_back(
9800 UnresolvedLookupExpr::Create(
9801 SemaRef.Context, /*NamingClass=*/nullptr,
9802 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
9803 NameInfo, /*ADL=*/true, ULE->isOverloaded(),
9804 Decls.begin(), Decls.end()));
9805 } else
9806 UnresolvedReductions.push_back(nullptr);
9807 }
9808 return getDerived().RebuildOMPReductionClause(
9809 Vars, C->getModifier(), C->getBeginLoc(), C->getLParenLoc(),
9810 C->getModifierLoc(), C->getColonLoc(), C->getEndLoc(),
9811 ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9812}
9813
9814template <typename Derived>
9815OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
9816 OMPTaskReductionClause *C) {
9817 llvm::SmallVector<Expr *, 16> Vars;
9818 Vars.reserve(C->varlist_size());
9819 for (auto *VE : C->varlists()) {
9820 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9821 if (EVar.isInvalid())
9822 return nullptr;
9823 Vars.push_back(EVar.get());
9824 }
9825 CXXScopeSpec ReductionIdScopeSpec;
9826 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9827
9828 DeclarationNameInfo NameInfo = C->getNameInfo();
9829 if (NameInfo.getName()) {
9830 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9831 if (!NameInfo.getName())
9832 return nullptr;
9833 }
9834 // Build a list of all UDR decls with the same names ranged by the Scopes.
9835 // The Scope boundary is a duplication of the previous decl.
9836 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9837 for (auto *E : C->reduction_ops()) {
9838 // Transform all the decls.
9839 if (E) {
9840 auto *ULE = cast<UnresolvedLookupExpr>(E);
9841 UnresolvedSet<8> Decls;
9842 for (auto *D : ULE->decls()) {
9843 NamedDecl *InstD =
9844 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9845 Decls.addDecl(InstD, InstD->getAccess());
9846 }
9847 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
9848 SemaRef.Context, /*NamingClass=*/nullptr,
9849 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
9850 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9851 } else
9852 UnresolvedReductions.push_back(nullptr);
9853 }
9854 return getDerived().RebuildOMPTaskReductionClause(
9855 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9856 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9857}
9858
9859template <typename Derived>
9860OMPClause *
9861TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
9862 llvm::SmallVector<Expr *, 16> Vars;
9863 Vars.reserve(C->varlist_size());
9864 for (auto *VE : C->varlists()) {
9865 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9866 if (EVar.isInvalid())
9867 return nullptr;
9868 Vars.push_back(EVar.get());
9869 }
9870 CXXScopeSpec ReductionIdScopeSpec;
9871 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9872
9873 DeclarationNameInfo NameInfo = C->getNameInfo();
9874 if (NameInfo.getName()) {
9875 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9876 if (!NameInfo.getName())
9877 return nullptr;
9878 }
9879 // Build a list of all UDR decls with the same names ranged by the Scopes.
9880 // The Scope boundary is a duplication of the previous decl.
9881 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9882 for (auto *E : C->reduction_ops()) {
9883 // Transform all the decls.
9884 if (E) {
9885 auto *ULE = cast<UnresolvedLookupExpr>(E);
9886 UnresolvedSet<8> Decls;
9887 for (auto *D : ULE->decls()) {
9888 NamedDecl *InstD =
9889 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9890 Decls.addDecl(InstD, InstD->getAccess());
9891 }
9892 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
9893 SemaRef.Context, /*NamingClass=*/nullptr,
9894 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
9895 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9896 } else
9897 UnresolvedReductions.push_back(nullptr);
9898 }
9899 return getDerived().RebuildOMPInReductionClause(
9900 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9901 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9902}
9903
9904template <typename Derived>
9905OMPClause *
9906TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
9907 llvm::SmallVector<Expr *, 16> Vars;
9908 Vars.reserve(C->varlist_size());
9909 for (auto *VE : C->varlists()) {
9910 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9911 if (EVar.isInvalid())
9912 return nullptr;
9913 Vars.push_back(EVar.get());
9914 }
9915 ExprResult Step = getDerived().TransformExpr(C->getStep());
9916 if (Step.isInvalid())
9917 return nullptr;
9918 return getDerived().RebuildOMPLinearClause(
9919 Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
9920 C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
9921}
9922
9923template <typename Derived>
9924OMPClause *
9925TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
9926 llvm::SmallVector<Expr *, 16> Vars;
9927 Vars.reserve(C->varlist_size());
9928 for (auto *VE : C->varlists()) {
9929 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9930 if (EVar.isInvalid())
9931 return nullptr;
9932 Vars.push_back(EVar.get());
9933 }
9934 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
9935 if (Alignment.isInvalid())
9936 return nullptr;
9937 return getDerived().RebuildOMPAlignedClause(
9938 Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
9939 C->getColonLoc(), C->getEndLoc());
9940}
9941
9942template <typename Derived>
9943OMPClause *
9944TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
9945 llvm::SmallVector<Expr *, 16> Vars;
9946 Vars.reserve(C->varlist_size());
9947 for (auto *VE : C->varlists()) {
9948 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9949 if (EVar.isInvalid())
9950 return nullptr;
9951 Vars.push_back(EVar.get());
9952 }
9953 return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
9954 C->getLParenLoc(), C->getEndLoc());
9955}
9956
9957template <typename Derived>
9958OMPClause *
9959TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
9960 llvm::SmallVector<Expr *, 16> Vars;
9961 Vars.reserve(C->varlist_size());
9962 for (auto *VE : C->varlists()) {
9963 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9964 if (EVar.isInvalid())
9965 return nullptr;
9966 Vars.push_back(EVar.get());
9967 }
9968 return getDerived().RebuildOMPCopyprivateClause(
9969 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9970}
9971
9972template <typename Derived>
9973OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
9974 llvm::SmallVector<Expr *, 16> Vars;
9975 Vars.reserve(C->varlist_size());
9976 for (auto *VE : C->varlists()) {
9977 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9978 if (EVar.isInvalid())
9979 return nullptr;
9980 Vars.push_back(EVar.get());
9981 }
9982 return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
9983 C->getLParenLoc(), C->getEndLoc());
9984}
9985
9986template <typename Derived>
9987OMPClause *
9988TreeTransform<Derived>::TransformOMPDepobjClause(OMPDepobjClause *C) {
9989 ExprResult E = getDerived().TransformExpr(C->getDepobj());
9990 if (E.isInvalid())
9991 return nullptr;
9992 return getDerived().RebuildOMPDepobjClause(E.get(), C->getBeginLoc(),
9993 C->getLParenLoc(), C->getEndLoc());
9994}
9995
9996template <typename Derived>
9997OMPClause *
9998TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
9999 llvm::SmallVector<Expr *, 16> Vars;
10000 Expr *DepModifier = C->getModifier();
10001 if (DepModifier) {
10002 ExprResult DepModRes = getDerived().TransformExpr(DepModifier);
10003 if (DepModRes.isInvalid())
10004 return nullptr;
10005 DepModifier = DepModRes.get();
10006 }
10007 Vars.reserve(C->varlist_size());
10008 for (auto *VE : C->varlists()) {
10009 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10010 if (EVar.isInvalid())
10011 return nullptr;
10012 Vars.push_back(EVar.get());
10013 }
10014 return getDerived().RebuildOMPDependClause(
10015 DepModifier, C->getDependencyKind(), C->getDependencyLoc(),
10016 C->getColonLoc(), Vars, C->getBeginLoc(), C->getLParenLoc(),
10017 C->getEndLoc());
10018}
10019
10020template <typename Derived>
10021OMPClause *
10022TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
10023 ExprResult E = getDerived().TransformExpr(C->getDevice());
10024 if (E.isInvalid())
10025 return nullptr;
10026 return getDerived().RebuildOMPDeviceClause(
10027 C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10028 C->getModifierLoc(), C->getEndLoc());
10029}
10030
10031template <typename Derived, class T>
10032bool transformOMPMappableExprListClause(
10033 TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
10034 llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
10035 DeclarationNameInfo &MapperIdInfo,
10036 llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
10037 // Transform expressions in the list.
10038 Vars.reserve(C->varlist_size());
10039 for (auto *VE : C->varlists()) {
10040 ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
10041 if (EVar.isInvalid())
10042 return true;
10043 Vars.push_back(EVar.get());
10044 }
10045 // Transform mapper scope specifier and identifier.
10046 NestedNameSpecifierLoc QualifierLoc;
10047 if (C->getMapperQualifierLoc()) {
10048 QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
10049 C->getMapperQualifierLoc());
10050 if (!QualifierLoc)
10051 return true;
10052 }
10053 MapperIdScopeSpec.Adopt(QualifierLoc);
10054 MapperIdInfo = C->getMapperIdInfo();
10055 if (MapperIdInfo.getName()) {
10056 MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
10057 if (!MapperIdInfo.getName())
10058 return true;
10059 }
10060 // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
10061 // the previous user-defined mapper lookup in dependent environment.
10062 for (auto *E : C->mapperlists()) {
10063 // Transform all the decls.
10064 if (E) {
10065 auto *ULE = cast<UnresolvedLookupExpr>(E);
10066 UnresolvedSet<8> Decls;
10067 for (auto *D : ULE->decls()) {
10068 NamedDecl *InstD =
10069 cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
10070 Decls.addDecl(InstD, InstD->getAccess());
10071 }
10072 UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
10073 TT.getSema().Context, /*NamingClass=*/nullptr,
10074 MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
10075 MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
10076 Decls.end()));
10077 } else {
10078 UnresolvedMappers.push_back(nullptr);
10079 }
10080 }
10081 return false;
10082}
10083
10084template <typename Derived>
10085OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
10086 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10087 llvm::SmallVector<Expr *, 16> Vars;
10088 CXXScopeSpec MapperIdScopeSpec;
10089 DeclarationNameInfo MapperIdInfo;
10090 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10091 if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
10092 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10093 return nullptr;
10094 return getDerived().RebuildOMPMapClause(
10095 C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
10096 MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
10097 C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10098}
10099
10100template <typename Derived>
10101OMPClause *
10102TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
10103 Expr *Allocator = C->getAllocator();
10104 if (Allocator) {
10105 ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
10106 if (AllocatorRes.isInvalid())
10107 return nullptr;
10108 Allocator = AllocatorRes.get();
10109 }
10110 llvm::SmallVector<Expr *, 16> Vars;
10111 Vars.reserve(C->varlist_size());
10112 for (auto *VE : C->varlists()) {
10113 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10114 if (EVar.isInvalid())
10115 return nullptr;
10116 Vars.push_back(EVar.get());
10117 }
10118 return getDerived().RebuildOMPAllocateClause(
10119 Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10120 C->getEndLoc());
10121}
10122
10123template <typename Derived>
10124OMPClause *
10125TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
10126 ExprResult E = getDerived().TransformExpr(C->getNumTeams());
10127 if (E.isInvalid())
10128 return nullptr;
10129 return getDerived().RebuildOMPNumTeamsClause(
10130 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10131}
10132
10133template <typename Derived>
10134OMPClause *
10135TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
10136 ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
10137 if (E.isInvalid())
10138 return nullptr;
10139 return getDerived().RebuildOMPThreadLimitClause(
10140 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10141}
10142
10143template <typename Derived>
10144OMPClause *
10145TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
10146 ExprResult E = getDerived().TransformExpr(C->getPriority());
10147 if (E.isInvalid())
10148 return nullptr;
10149 return getDerived().RebuildOMPPriorityClause(
10150 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10151}
10152
10153template <typename Derived>
10154OMPClause *
10155TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
10156 ExprResult E = getDerived().TransformExpr(C->getGrainsize());
10157 if (E.isInvalid())
10158 return nullptr;
10159 return getDerived().RebuildOMPGrainsizeClause(
10160 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10161}
10162
10163template <typename Derived>
10164OMPClause *
10165TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
10166 ExprResult E = getDerived().TransformExpr(C->getNumTasks());
10167 if (E.isInvalid())
10168 return nullptr;
10169 return getDerived().RebuildOMPNumTasksClause(
10170 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10171}
10172
10173template <typename Derived>
10174OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
10175 ExprResult E = getDerived().TransformExpr(C->getHint());
10176 if (E.isInvalid())
10177 return nullptr;
10178 return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
10179 C->getLParenLoc(), C->getEndLoc());
10180}
10181
10182template <typename Derived>
10183OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
10184 OMPDistScheduleClause *C) {
10185 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
10186 if (E.isInvalid())
10187 return nullptr;
10188 return getDerived().RebuildOMPDistScheduleClause(
10189 C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10190 C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
10191}
10192
10193template <typename Derived>
10194OMPClause *
10195TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
10196 // Rebuild Defaultmap Clause since we need to invoke the checking of
10197 // defaultmap(none:variable-category) after template initialization.
10198 return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
10199 C->getDefaultmapKind(),
10200 C->getBeginLoc(),
10201 C->getLParenLoc(),
10202 C->getDefaultmapModifierLoc(),
10203 C->getDefaultmapKindLoc(),
10204 C->getEndLoc());
10205}
10206
10207template <typename Derived>
10208OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
10209 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10210 llvm::SmallVector<Expr *, 16> Vars;
10211 CXXScopeSpec MapperIdScopeSpec;
10212 DeclarationNameInfo MapperIdInfo;
10213 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10214 if (transformOMPMappableExprListClause<Derived, OMPToClause>(
10215 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10216 return nullptr;
10217 return getDerived().RebuildOMPToClause(
10218 C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10219 MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10220}
10221
10222template <typename Derived>
10223OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
10224 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10225 llvm::SmallVector<Expr *, 16> Vars;
10226 CXXScopeSpec MapperIdScopeSpec;
10227 DeclarationNameInfo MapperIdInfo;
10228 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10229 if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
10230 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10231 return nullptr;
10232 return getDerived().RebuildOMPFromClause(
10233 C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10234 MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10235}
10236
10237template <typename Derived>
10238OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
10239 OMPUseDevicePtrClause *C) {
10240 llvm::SmallVector<Expr *, 16> Vars;
10241 Vars.reserve(C->varlist_size());
10242 for (auto *VE : C->varlists()) {
10243 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10244 if (EVar.isInvalid())
10245 return nullptr;
10246 Vars.push_back(EVar.get());
10247 }
10248 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10249 return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
10250}
10251
10252template <typename Derived>
10253OMPClause *TreeTransform<Derived>::TransformOMPUseDeviceAddrClause(
10254 OMPUseDeviceAddrClause *C) {
10255 llvm::SmallVector<Expr *, 16> Vars;
10256 Vars.reserve(C->varlist_size());
10257 for (auto *VE : C->varlists()) {
10258 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10259 if (EVar.isInvalid())
10260 return nullptr;
10261 Vars.push_back(EVar.get());
10262 }
10263 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10264 return getDerived().RebuildOMPUseDeviceAddrClause(Vars, Locs);
10265}
10266
10267template <typename Derived>
10268OMPClause *
10269TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
10270 llvm::SmallVector<Expr *, 16> Vars;
10271 Vars.reserve(C->varlist_size());
10272 for (auto *VE : C->varlists()) {
10273 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10274 if (EVar.isInvalid())
10275 return nullptr;
10276 Vars.push_back(EVar.get());
10277 }
10278 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10279 return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
10280}
10281
10282template <typename Derived>
10283OMPClause *TreeTransform<Derived>::TransformOMPHasDeviceAddrClause(
10284 OMPHasDeviceAddrClause *C) {
10285 llvm::SmallVector<Expr *, 16> Vars;
10286 Vars.reserve(C->varlist_size());
10287 for (auto *VE : C->varlists()) {
10288 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10289 if (EVar.isInvalid())
10290 return nullptr;
10291 Vars.push_back(EVar.get());
10292 }
10293 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10294 return getDerived().RebuildOMPHasDeviceAddrClause(Vars, Locs);
10295}
10296
10297template <typename Derived>
10298OMPClause *
10299TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
10300 llvm::SmallVector<Expr *, 16> Vars;
10301 Vars.reserve(C->varlist_size());
10302 for (auto *VE : C->varlists()) {
10303 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10304 if (EVar.isInvalid())
10305 return nullptr;
10306 Vars.push_back(EVar.get());
10307 }
10308 return getDerived().RebuildOMPNontemporalClause(
10309 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10310}
10311
10312template <typename Derived>
10313OMPClause *
10314TreeTransform<Derived>::TransformOMPInclusiveClause(OMPInclusiveClause *C) {
10315 llvm::SmallVector<Expr *, 16> Vars;
10316 Vars.reserve(C->varlist_size());
10317 for (auto *VE : C->varlists()) {
10318 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10319 if (EVar.isInvalid())
10320 return nullptr;
10321 Vars.push_back(EVar.get());
10322 }
10323 return getDerived().RebuildOMPInclusiveClause(
10324 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10325}
10326
10327template <typename Derived>
10328OMPClause *
10329TreeTransform<Derived>::TransformOMPExclusiveClause(OMPExclusiveClause *C) {
10330 llvm::SmallVector<Expr *, 16> Vars;
10331 Vars.reserve(C->varlist_size());
10332 for (auto *VE : C->varlists()) {
10333 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10334 if (EVar.isInvalid())
10335 return nullptr;
10336 Vars.push_back(EVar.get());
10337 }
10338 return getDerived().RebuildOMPExclusiveClause(
10339 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10340}
10341
10342template <typename Derived>
10343OMPClause *TreeTransform<Derived>::TransformOMPUsesAllocatorsClause(
10344 OMPUsesAllocatorsClause *C) {
10345 SmallVector<Sema::UsesAllocatorsData, 16> Data;
10346 Data.reserve(C->getNumberOfAllocators());
10347 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
10348 OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
10349 ExprResult Allocator = getDerived().TransformExpr(D.Allocator);
10350 if (Allocator.isInvalid())
10351 continue;
10352 ExprResult AllocatorTraits;
10353 if (Expr *AT = D.AllocatorTraits) {
10354 AllocatorTraits = getDerived().TransformExpr(AT);
10355 if (AllocatorTraits.isInvalid())
10356 continue;
10357 }
10358 Sema::UsesAllocatorsData &NewD = Data.emplace_back();
10359 NewD.Allocator = Allocator.get();
10360 NewD.AllocatorTraits = AllocatorTraits.get();
10361 NewD.LParenLoc = D.LParenLoc;
10362 NewD.RParenLoc = D.RParenLoc;
10363 }
10364 return getDerived().RebuildOMPUsesAllocatorsClause(
10365 Data, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10366}
10367
10368template <typename Derived>
10369OMPClause *
10370TreeTransform<Derived>::TransformOMPAffinityClause(OMPAffinityClause *C) {
10371 SmallVector<Expr *, 4> Locators;
10372 Locators.reserve(C->varlist_size());
10373 ExprResult ModifierRes;
10374 if (Expr *Modifier = C->getModifier()) {
10375 ModifierRes = getDerived().TransformExpr(Modifier);
10376 if (ModifierRes.isInvalid())
10377 return nullptr;
10378 }
10379 for (Expr *E : C->varlists()) {
10380 ExprResult Locator = getDerived().TransformExpr(E);
10381 if (Locator.isInvalid())
10382 continue;
10383 Locators.push_back(Locator.get());
10384 }
10385 return getDerived().RebuildOMPAffinityClause(
10386 C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(), C->getEndLoc(),
10387 ModifierRes.get(), Locators);
10388}
10389
10390template <typename Derived>
10391OMPClause *TreeTransform<Derived>::TransformOMPOrderClause(OMPOrderClause *C) {
10392 return getDerived().RebuildOMPOrderClause(C->getKind(), C->getKindKwLoc(),
10393 C->getBeginLoc(), C->getLParenLoc(),
10394 C->getEndLoc());
10395}
10396
10397template <typename Derived>
10398OMPClause *TreeTransform<Derived>::TransformOMPBindClause(OMPBindClause *C) {
10399 return getDerived().RebuildOMPBindClause(
10400 C->getBindKind(), C->getBindKindLoc(), C->getBeginLoc(),
10401 C->getLParenLoc(), C->getEndLoc());
10402}
10403
10404//===----------------------------------------------------------------------===//
10405// Expression transformation
10406//===----------------------------------------------------------------------===//
10407template<typename Derived>
10408ExprResult
10409TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
10410 return TransformExpr(E->getSubExpr());
10411}
10412
10413template <typename Derived>
10414ExprResult TreeTransform<Derived>::TransformSYCLUniqueStableNameExpr(
10415 SYCLUniqueStableNameExpr *E) {
10416 if (!E->isTypeDependent())
10417 return E;
10418
10419 TypeSourceInfo *NewT = getDerived().TransformType(E->getTypeSourceInfo());
10420
10421 if (!NewT)
10422 return ExprError();
10423
10424 if (!getDerived().AlwaysRebuild() && E->getTypeSourceInfo() == NewT)
10425 return E;
10426
10427 return getDerived().RebuildSYCLUniqueStableNameExpr(
10428 E->getLocation(), E->getLParenLocation(), E->getRParenLocation(), NewT);
10429}
10430
10431template<typename Derived>
10432ExprResult
10433TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
10434 if (!E->isTypeDependent())
10435 return E;
10436
10437 return getDerived().RebuildPredefinedExpr(E->getLocation(),
10438 E->getIdentKind());
10439}
10440
10441template<typename Derived>
10442ExprResult
10443TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
10444 NestedNameSpecifierLoc QualifierLoc;
10445 if (E->getQualifierLoc()) {
10446 QualifierLoc
10447 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10448 if (!QualifierLoc)
10449 return ExprError();
10450 }
10451
10452 ValueDecl *ND
10453 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
10454 E->getDecl()));
10455 if (!ND)
10456 return ExprError();
10457
10458 NamedDecl *Found = ND;
10459 if (E->getFoundDecl() != E->getDecl()) {
10460 Found = cast_or_null<NamedDecl>(
10461 getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
10462 if (!Found)
10463 return ExprError();
10464 }
10465
10466 DeclarationNameInfo NameInfo = E->getNameInfo();
10467 if (NameInfo.getName()) {
10468 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10469 if (!NameInfo.getName())
10470 return ExprError();
10471 }
10472
10473 if (!getDerived().AlwaysRebuild() &&
10474 QualifierLoc == E->getQualifierLoc() &&
10475 ND == E->getDecl() &&
10476 Found == E->getFoundDecl() &&
10477 NameInfo.getName() == E->getDecl()->getDeclName() &&
10478 !E->hasExplicitTemplateArgs()) {
10479
10480 // Mark it referenced in the new context regardless.
10481 // FIXME: this is a bit instantiation-specific.
10482 SemaRef.MarkDeclRefReferenced(E);
10483
10484 return E;
10485 }
10486
10487 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
10488 if (E->hasExplicitTemplateArgs()) {
10489 TemplateArgs = &TransArgs;
10490 TransArgs.setLAngleLoc(E->getLAngleLoc());
10491 TransArgs.setRAngleLoc(E->getRAngleLoc());
10492 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10493 E->getNumTemplateArgs(),
10494 TransArgs))
10495 return ExprError();
10496 }
10497
10498 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
10499 Found, TemplateArgs);
10500}
10501
10502template<typename Derived>
10503ExprResult
10504TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
10505 return E;
10506}
10507
10508template <typename Derived>
10509ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
10510 FixedPointLiteral *E) {
10511 return E;
10512}
10513
10514template<typename Derived>
10515ExprResult
10516TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
10517 return E;
10518}
10519
10520template<typename Derived>
10521ExprResult
10522TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
10523 return E;
10524}
10525
10526template<typename Derived>
10527ExprResult
10528TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
10529 return E;
10530}
10531
10532template<typename Derived>
10533ExprResult
10534TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
10535 return E;
10536}
10537
10538template<typename Derived>
10539ExprResult
10540TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
10541 return getDerived().TransformCallExpr(E);
10542}
10543
10544template<typename Derived>
10545ExprResult
10546TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
10547 ExprResult ControllingExpr =
10548 getDerived().TransformExpr(E->getControllingExpr());
10549 if (ControllingExpr.isInvalid())
10550 return ExprError();
10551
10552 SmallVector<Expr *, 4> AssocExprs;
10553 SmallVector<TypeSourceInfo *, 4> AssocTypes;
10554 for (const GenericSelectionExpr::Association Assoc : E->associations()) {
10555 TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
10556 if (TSI) {
10557 TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
10558 if (!AssocType)
10559 return ExprError();
10560 AssocTypes.push_back(AssocType);
10561 } else {
10562 AssocTypes.push_back(nullptr);
10563 }
10564
10565 ExprResult AssocExpr =
10566 getDerived().TransformExpr(Assoc.getAssociationExpr());
10567 if (AssocExpr.isInvalid())
10568 return ExprError();
10569 AssocExprs.push_back(AssocExpr.get());
10570 }
10571
10572 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
10573 E->getDefaultLoc(),
10574 E->getRParenLoc(),
10575 ControllingExpr.get(),
10576 AssocTypes,
10577 AssocExprs);
10578}
10579
10580template<typename Derived>
10581ExprResult
10582TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
10583 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10584 if (SubExpr.isInvalid())
10585 return ExprError();
10586
10587 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10588 return E;
10589
10590 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
10591 E->getRParen());
10592}
10593
10594/// The operand of a unary address-of operator has special rules: it's
10595/// allowed to refer to a non-static member of a class even if there's no 'this'
10596/// object available.
10597template<typename Derived>
10598ExprResult
10599TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
10600 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
10601 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
10602 else
10603 return getDerived().TransformExpr(E);
10604}
10605
10606template<typename Derived>
10607ExprResult
10608TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
10609 ExprResult SubExpr;
10610 if (E->getOpcode() == UO_AddrOf)
10611 SubExpr = TransformAddressOfOperand(E->getSubExpr());
10612 else
10613 SubExpr = TransformExpr(E->getSubExpr());
10614 if (SubExpr.isInvalid())
10615 return ExprError();
10616
10617 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10618 return E;
10619
10620 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
10621 E->getOpcode(),
10622 SubExpr.get());
10623}
10624
10625template<typename Derived>
10626ExprResult
10627TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
10628 // Transform the type.
10629 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10630 if (!Type)
10631 return ExprError();
10632
10633 // Transform all of the components into components similar to what the
10634 // parser uses.
10635 // FIXME: It would be slightly more efficient in the non-dependent case to
10636 // just map FieldDecls, rather than requiring the rebuilder to look for
10637 // the fields again. However, __builtin_offsetof is rare enough in
10638 // template code that we don't care.
10639 bool ExprChanged = false;
10640 typedef Sema::OffsetOfComponent Component;
10641 SmallVector<Component, 4> Components;
10642 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
10643 const OffsetOfNode &ON = E->getComponent(I);
10644 Component Comp;
10645 Comp.isBrackets = true;
10646 Comp.LocStart = ON.getSourceRange().getBegin();
10647 Comp.LocEnd = ON.getSourceRange().getEnd();
10648 switch (ON.getKind()) {
10649 case OffsetOfNode::Array: {
10650 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
10651 ExprResult Index = getDerived().TransformExpr(FromIndex);
10652 if (Index.isInvalid())
10653 return ExprError();
10654
10655 ExprChanged = ExprChanged || Index.get() != FromIndex;
10656 Comp.isBrackets = true;
10657 Comp.U.E = Index.get();
10658 break;
10659 }
10660
10661 case OffsetOfNode::Field:
10662 case OffsetOfNode::Identifier:
10663 Comp.isBrackets = false;
10664 Comp.U.IdentInfo = ON.getFieldName();
10665 if (!Comp.U.IdentInfo)
10666 continue;
10667
10668 break;
10669
10670 case OffsetOfNode::Base:
10671 // Will be recomputed during the rebuild.
10672 continue;
10673 }
10674
10675 Components.push_back(Comp);
10676 }
10677
10678 // If nothing changed, retain the existing expression.
10679 if (!getDerived().AlwaysRebuild() &&
10680 Type == E->getTypeSourceInfo() &&
10681 !ExprChanged)
10682 return E;
10683
10684 // Build a new offsetof expression.
10685 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
10686 Components, E->getRParenLoc());
10687}
10688
10689template<typename Derived>
10690ExprResult
10691TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
10692 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", 10693, __extension__ __PRETTY_FUNCTION__
))
10693 "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", 10693, __extension__ __PRETTY_FUNCTION__
))
;
10694 return E;
10695}
10696
10697template<typename Derived>
10698ExprResult
10699TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
10700 return E;
10701}
10702
10703template <typename Derived>
10704ExprResult TreeTransform<Derived>::TransformRecoveryExpr(RecoveryExpr *E) {
10705 llvm::SmallVector<Expr *, 8> Children;
10706 bool Changed = false;
10707 for (Expr *C : E->subExpressions()) {
10708 ExprResult NewC = getDerived().TransformExpr(C);
10709 if (NewC.isInvalid())
10710 return ExprError();
10711 Children.push_back(NewC.get());
10712
10713 Changed |= NewC.get() != C;
10714 }
10715 if (!getDerived().AlwaysRebuild() && !Changed)
10716 return E;
10717 return getDerived().RebuildRecoveryExpr(E->getBeginLoc(), E->getEndLoc(),
10718 Children, E->getType());
10719}
10720
10721template<typename Derived>
10722ExprResult
10723TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
10724 // Rebuild the syntactic form. The original syntactic form has
10725 // opaque-value expressions in it, so strip those away and rebuild
10726 // the result. This is a really awful way of doing this, but the
10727 // better solution (rebuilding the semantic expressions and
10728 // rebinding OVEs as necessary) doesn't work; we'd need
10729 // TreeTransform to not strip away implicit conversions.
10730 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
10731 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
10732 if (result.isInvalid()) return ExprError();
10733
10734 // If that gives us a pseudo-object result back, the pseudo-object
10735 // expression must have been an lvalue-to-rvalue conversion which we
10736 // should reapply.
10737 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
10738 result = SemaRef.checkPseudoObjectRValue(result.get());
10739
10740 return result;
10741}
10742
10743template<typename Derived>
10744ExprResult
10745TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
10746 UnaryExprOrTypeTraitExpr *E) {
10747 if (E->isArgumentType()) {
10748 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
10749
10750 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
10751 if (!NewT)
10752 return ExprError();
10753
10754 if (!getDerived().AlwaysRebuild() && OldT == NewT)
10755 return E;
10756
10757 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
10758 E->getKind(),
10759 E->getSourceRange());
10760 }
10761
10762 // C++0x [expr.sizeof]p1:
10763 // The operand is either an expression, which is an unevaluated operand
10764 // [...]
10765 EnterExpressionEvaluationContext Unevaluated(
10766 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10767 Sema::ReuseLambdaContextDecl);
10768
10769 // Try to recover if we have something like sizeof(T::X) where X is a type.
10770 // Notably, there must be *exactly* one set of parens if X is a type.
10771 TypeSourceInfo *RecoveryTSI = nullptr;
10772 ExprResult SubExpr;
10773 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
10774 if (auto *DRE =
10775 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
10776 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
10777 PE, DRE, false, &RecoveryTSI);
10778 else
10779 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
10780
10781 if (RecoveryTSI) {
10782 return getDerived().RebuildUnaryExprOrTypeTrait(
10783 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
10784 } else if (SubExpr.isInvalid())
10785 return ExprError();
10786
10787 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
10788 return E;
10789
10790 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
10791 E->getOperatorLoc(),
10792 E->getKind(),
10793 E->getSourceRange());
10794}
10795
10796template<typename Derived>
10797ExprResult
10798TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
10799 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10800 if (LHS.isInvalid())
10801 return ExprError();
10802
10803 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10804 if (RHS.isInvalid())
10805 return ExprError();
10806
10807
10808 if (!getDerived().AlwaysRebuild() &&
10809 LHS.get() == E->getLHS() &&
10810 RHS.get() == E->getRHS())
10811 return E;
10812
10813 return getDerived().RebuildArraySubscriptExpr(
10814 LHS.get(),
10815 /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
10816}
10817
10818template <typename Derived>
10819ExprResult
10820TreeTransform<Derived>::TransformMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
10821 ExprResult Base = getDerived().TransformExpr(E->getBase());
10822 if (Base.isInvalid())
10823 return ExprError();
10824
10825 ExprResult RowIdx = getDerived().TransformExpr(E->getRowIdx());
10826 if (RowIdx.isInvalid())
10827 return ExprError();
10828
10829 ExprResult ColumnIdx = getDerived().TransformExpr(E->getColumnIdx());
10830 if (ColumnIdx.isInvalid())
10831 return ExprError();
10832
10833 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
10834 RowIdx.get() == E->getRowIdx() && ColumnIdx.get() == E->getColumnIdx())
10835 return E;
10836
10837 return getDerived().RebuildMatrixSubscriptExpr(
10838 Base.get(), RowIdx.get(), ColumnIdx.get(), E->getRBracketLoc());
10839}
10840
10841template <typename Derived>
10842ExprResult
10843TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
10844 ExprResult Base = getDerived().TransformExpr(E->getBase());
10845 if (Base.isInvalid())
10846 return ExprError();
10847
10848 ExprResult LowerBound;
10849 if (E->getLowerBound()) {
10850 LowerBound = getDerived().TransformExpr(E->getLowerBound());
10851 if (LowerBound.isInvalid())
10852 return ExprError();
10853 }
10854
10855 ExprResult Length;
10856 if (E->getLength()) {
10857 Length = getDerived().TransformExpr(E->getLength());
10858 if (Length.isInvalid())
10859 return ExprError();
10860 }
10861
10862 ExprResult Stride;
10863 if (Expr *Str = E->getStride()) {
10864 Stride = getDerived().TransformExpr(Str);
10865 if (Stride.isInvalid())
10866 return ExprError();
10867 }
10868
10869 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
10870 LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
10871 return E;
10872
10873 return getDerived().RebuildOMPArraySectionExpr(
10874 Base.get(), E->getBase()->getEndLoc(), LowerBound.get(),
10875 E->getColonLocFirst(), E->getColonLocSecond(), Length.get(), Stride.get(),
10876 E->getRBracketLoc());
10877}
10878
10879template <typename Derived>
10880ExprResult
10881TreeTransform<Derived>::TransformOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
10882 ExprResult Base = getDerived().TransformExpr(E->getBase());
10883 if (Base.isInvalid())
10884 return ExprError();
10885
10886 SmallVector<Expr *, 4> Dims;
10887 bool ErrorFound = false;
10888 for (Expr *Dim : E->getDimensions()) {
10889 ExprResult DimRes = getDerived().TransformExpr(Dim);
10890 if (DimRes.isInvalid()) {
10891 ErrorFound = true;
10892 continue;
10893 }
10894 Dims.push_back(DimRes.get());
10895 }
10896
10897 if (ErrorFound)
10898 return ExprError();
10899 return getDerived().RebuildOMPArrayShapingExpr(Base.get(), E->getLParenLoc(),
10900 E->getRParenLoc(), Dims,
10901 E->getBracketsRanges());
10902}
10903
10904template <typename Derived>
10905ExprResult
10906TreeTransform<Derived>::TransformOMPIteratorExpr(OMPIteratorExpr *E) {
10907 unsigned NumIterators = E->numOfIterators();
10908 SmallVector<Sema::OMPIteratorData, 4> Data(NumIterators);
10909
10910 bool ErrorFound = false;
10911 bool NeedToRebuild = getDerived().AlwaysRebuild();
10912 for (unsigned I = 0; I < NumIterators; ++I) {
10913 auto *D = cast<VarDecl>(E->getIteratorDecl(I));
10914 Data[I].DeclIdent = D->getIdentifier();
10915 Data[I].DeclIdentLoc = D->getLocation();
10916 if (D->getLocation() == D->getBeginLoc()) {
10917 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", 10918, __extension__ __PRETTY_FUNCTION__
))
10918 "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", 10918, __extension__ __PRETTY_FUNCTION__
))
;
10919 } else {
10920 TypeSourceInfo *TSI = getDerived().TransformType(D->getTypeSourceInfo());
10921 QualType DeclTy = getDerived().TransformType(D->getType());
10922 Data[I].Type = SemaRef.CreateParsedType(DeclTy, TSI);
10923 }
10924 OMPIteratorExpr::IteratorRange Range = E->getIteratorRange(I);
10925 ExprResult Begin = getDerived().TransformExpr(Range.Begin);
10926 ExprResult End = getDerived().TransformExpr(Range.End);
10927 ExprResult Step = getDerived().TransformExpr(Range.Step);
10928 ErrorFound = ErrorFound ||
10929 !(!D->getTypeSourceInfo() || (Data[I].Type.getAsOpaquePtr() &&
10930 !Data[I].Type.get().isNull())) ||
10931 Begin.isInvalid() || End.isInvalid() || Step.isInvalid();
10932 if (ErrorFound)
10933 continue;
10934 Data[I].Range.Begin = Begin.get();
10935 Data[I].Range.End = End.get();
10936 Data[I].Range.Step = Step.get();
10937 Data[I].AssignLoc = E->getAssignLoc(I);
10938 Data[I].ColonLoc = E->getColonLoc(I);
10939 Data[I].SecColonLoc = E->getSecondColonLoc(I);
10940 NeedToRebuild =
10941 NeedToRebuild ||
10942 (D->getTypeSourceInfo() && Data[I].Type.get().getTypePtrOrNull() !=
10943 D->getType().getTypePtrOrNull()) ||
10944 Range.Begin != Data[I].Range.Begin || Range.End != Data[I].Range.End ||
10945 Range.Step != Data[I].Range.Step;
10946 }
10947 if (ErrorFound)
10948 return ExprError();
10949 if (!NeedToRebuild)
10950 return E;
10951
10952 ExprResult Res = getDerived().RebuildOMPIteratorExpr(
10953 E->getIteratorKwLoc(), E->getLParenLoc(), E->getRParenLoc(), Data);
10954 if (!Res.isUsable())
10955 return Res;
10956 auto *IE = cast<OMPIteratorExpr>(Res.get());
10957 for (unsigned I = 0; I < NumIterators; ++I)
10958 getDerived().transformedLocalDecl(E->getIteratorDecl(I),
10959 IE->getIteratorDecl(I));
10960 return Res;
10961}
10962
10963template<typename Derived>
10964ExprResult
10965TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
10966 // Transform the callee.
10967 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10968 if (Callee.isInvalid())
10969 return ExprError();
10970
10971 // Transform arguments.
10972 bool ArgChanged = false;
10973 SmallVector<Expr*, 8> Args;
10974 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10975 &ArgChanged))
10976 return ExprError();
10977
10978 if (!getDerived().AlwaysRebuild() &&
10979 Callee.get() == E->getCallee() &&
10980 !ArgChanged)
10981 return SemaRef.MaybeBindToTemporary(E);
10982
10983 // FIXME: Wrong source location information for the '('.
10984 SourceLocation FakeLParenLoc
10985 = ((Expr *)Callee.get())->getSourceRange().getBegin();
10986
10987 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
10988 if (E->hasStoredFPFeatures()) {
10989 FPOptionsOverride NewOverrides = E->getFPFeatures();
10990 getSema().CurFPFeatures =
10991 NewOverrides.applyOverrides(getSema().getLangOpts());
10992 getSema().FpPragmaStack.CurrentValue = NewOverrides;
10993 }
10994
10995 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10996 Args,
10997 E->getRParenLoc());
10998}
10999
11000template<typename Derived>
11001ExprResult
11002TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
11003 ExprResult Base = getDerived().TransformExpr(E->getBase());
11004 if (Base.isInvalid())
11005 return ExprError();
11006
11007 NestedNameSpecifierLoc QualifierLoc;
11008 if (E->hasQualifier()) {
11009 QualifierLoc
11010 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11011
11012 if (!QualifierLoc)
11013 return ExprError();
11014 }
11015 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11016
11017 ValueDecl *Member
11018 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
11019 E->getMemberDecl()));
11020 if (!Member)
11021 return ExprError();
11022
11023 NamedDecl *FoundDecl = E->getFoundDecl();
11024 if (FoundDecl == E->getMemberDecl()) {
11025 FoundDecl = Member;
11026 } else {
11027 FoundDecl = cast_or_null<NamedDecl>(
11028 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
11029 if (!FoundDecl)
11030 return ExprError();
11031 }
11032
11033 if (!getDerived().AlwaysRebuild() &&
11034 Base.get() == E->getBase() &&
11035 QualifierLoc == E->getQualifierLoc() &&
11036 Member == E->getMemberDecl() &&
11037 FoundDecl == E->getFoundDecl() &&
11038 !E->hasExplicitTemplateArgs()) {
11039
11040 // Mark it referenced in the new context regardless.
11041 // FIXME: this is a bit instantiation-specific.
11042 SemaRef.MarkMemberReferenced(E);
11043
11044 return E;
11045 }
11046
11047 TemplateArgumentListInfo TransArgs;
11048 if (E->hasExplicitTemplateArgs()) {
11049 TransArgs.setLAngleLoc(E->getLAngleLoc());
11050 TransArgs.setRAngleLoc(E->getRAngleLoc());
11051 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11052 E->getNumTemplateArgs(),
11053 TransArgs))
11054 return ExprError();
11055 }
11056
11057 // FIXME: Bogus source location for the operator
11058 SourceLocation FakeOperatorLoc =
11059 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
11060
11061 // FIXME: to do this check properly, we will need to preserve the
11062 // first-qualifier-in-scope here, just in case we had a dependent
11063 // base (and therefore couldn't do the check) and a
11064 // nested-name-qualifier (and therefore could do the lookup).
11065 NamedDecl *FirstQualifierInScope = nullptr;
11066 DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
11067 if (MemberNameInfo.getName()) {
11068 MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
11069 if (!MemberNameInfo.getName())
11070 return ExprError();
11071 }
11072
11073 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
11074 E->isArrow(),
11075 QualifierLoc,
11076 TemplateKWLoc,
11077 MemberNameInfo,
11078 Member,
11079 FoundDecl,
11080 (E->hasExplicitTemplateArgs()
11081 ? &TransArgs : nullptr),
11082 FirstQualifierInScope);
11083}
11084
11085template<typename Derived>
11086ExprResult
11087TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
11088 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11089 if (LHS.isInvalid())
11090 return ExprError();
11091
11092 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11093 if (RHS.isInvalid())
11094 return ExprError();
11095
11096 if (!getDerived().AlwaysRebuild() &&
11097 LHS.get() == E->getLHS() &&
11098 RHS.get() == E->getRHS())
11099 return E;
11100
11101 if (E->isCompoundAssignmentOp())
11102 // FPFeatures has already been established from trailing storage
11103 return getDerived().RebuildBinaryOperator(
11104 E->getOperatorLoc(), E->getOpcode(), LHS.get(), RHS.get());
11105 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11106 FPOptionsOverride NewOverrides(E->getFPFeatures(getSema().getLangOpts()));
11107 getSema().CurFPFeatures =
11108 NewOverrides.applyOverrides(getSema().getLangOpts());
11109 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11110 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
11111 LHS.get(), RHS.get());
11112}
11113
11114template <typename Derived>
11115ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
11116 CXXRewrittenBinaryOperator *E) {
11117 CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
11118
11119 ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
11120 if (LHS.isInvalid())
11121 return ExprError();
11122
11123 ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
11124 if (RHS.isInvalid())
11125 return ExprError();
11126
11127 // Extract the already-resolved callee declarations so that we can restrict
11128 // ourselves to using them as the unqualified lookup results when rebuilding.
11129 UnresolvedSet<2> UnqualLookups;
11130 bool ChangedAnyLookups = false;
11131 Expr *PossibleBinOps[] = {E->getSemanticForm(),
11132 const_cast<Expr *>(Decomp.InnerBinOp)};
11133 for (Expr *PossibleBinOp : PossibleBinOps) {
11134 auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
11135 if (!Op)
11136 continue;
11137 auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
11138 if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
11139 continue;
11140
11141 // Transform the callee in case we built a call to a local extern
11142 // declaration.
11143 NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
11144 E->getOperatorLoc(), Callee->getFoundDecl()));
11145 if (!Found)
11146 return ExprError();
11147 if (Found != Callee->getFoundDecl())
11148 ChangedAnyLookups = true;
11149 UnqualLookups.addDecl(Found);
11150 }
11151
11152 if (!getDerived().AlwaysRebuild() && !ChangedAnyLookups &&
11153 LHS.get() == Decomp.LHS && RHS.get() == Decomp.RHS) {
11154 // Mark all functions used in the rewrite as referenced. Note that when
11155 // a < b is rewritten to (a <=> b) < 0, both the <=> and the < might be
11156 // function calls, and/or there might be a user-defined conversion sequence
11157 // applied to the operands of the <.
11158 // FIXME: this is a bit instantiation-specific.
11159 const Expr *StopAt[] = {Decomp.LHS, Decomp.RHS};
11160 SemaRef.MarkDeclarationsReferencedInExpr(E, false, StopAt);
11161 return E;
11162 }
11163
11164 return getDerived().RebuildCXXRewrittenBinaryOperator(
11165 E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
11166}
11167
11168template<typename Derived>
11169ExprResult
11170TreeTransform<Derived>::TransformCompoundAssignOperator(
11171 CompoundAssignOperator *E) {
11172 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11173 FPOptionsOverride NewOverrides(E->getFPFeatures(getSema().getLangOpts()));
11174 getSema().CurFPFeatures =
11175 NewOverrides.applyOverrides(getSema().getLangOpts());
11176 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11177 return getDerived().TransformBinaryOperator(E);
11178}
11179
11180template<typename Derived>
11181ExprResult TreeTransform<Derived>::
11182TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
11183 // Just rebuild the common and RHS expressions and see whether we
11184 // get any changes.
11185
11186 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
11187 if (commonExpr.isInvalid())
11188 return ExprError();
11189
11190 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
11191 if (rhs.isInvalid())
11192 return ExprError();
11193
11194 if (!getDerived().AlwaysRebuild() &&
11195 commonExpr.get() == e->getCommon() &&
11196 rhs.get() == e->getFalseExpr())
11197 return e;
11198
11199 return getDerived().RebuildConditionalOperator(commonExpr.get(),
11200 e->getQuestionLoc(),
11201 nullptr,
11202 e->getColonLoc(),
11203 rhs.get());
11204}
11205
11206template<typename Derived>
11207ExprResult
11208TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
11209 ExprResult Cond = getDerived().TransformExpr(E->getCond());
11210 if (Cond.isInvalid())
11211 return ExprError();
11212
11213 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11214 if (LHS.isInvalid())
11215 return ExprError();
11216
11217 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11218 if (RHS.isInvalid())
11219 return ExprError();
11220
11221 if (!getDerived().AlwaysRebuild() &&
11222 Cond.get() == E->getCond() &&
11223 LHS.get() == E->getLHS() &&
11224 RHS.get() == E->getRHS())
11225 return E;
11226
11227 return getDerived().RebuildConditionalOperator(Cond.get(),
11228 E->getQuestionLoc(),
11229 LHS.get(),
11230 E->getColonLoc(),
11231 RHS.get());
11232}
11233
11234template<typename Derived>
11235ExprResult
11236TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
11237 // Implicit casts are eliminated during transformation, since they
11238 // will be recomputed by semantic analysis after transformation.
11239 return getDerived().TransformExpr(E->getSubExprAsWritten());
11240}
11241
11242template<typename Derived>
11243ExprResult
11244TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
11245 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11246 if (!Type)
11247 return ExprError();
11248
11249 ExprResult SubExpr
11250 = getDerived().TransformExpr(E->getSubExprAsWritten());
11251 if (SubExpr.isInvalid())
11252 return ExprError();
11253
11254 if (!getDerived().AlwaysRebuild() &&
11255 Type == E->getTypeInfoAsWritten() &&
11256 SubExpr.get() == E->getSubExpr())
11257 return E;
11258
11259 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
11260 Type,
11261 E->getRParenLoc(),
11262 SubExpr.get());
11263}
11264
11265template<typename Derived>
11266ExprResult
11267TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
11268 TypeSourceInfo *OldT = E->getTypeSourceInfo();
11269 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11270 if (!NewT)
11271 return ExprError();
11272
11273 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
11274 if (Init.isInvalid())
11275 return ExprError();
11276
11277 if (!getDerived().AlwaysRebuild() &&
11278 OldT == NewT &&
11279 Init.get() == E->getInitializer())
11280 return SemaRef.MaybeBindToTemporary(E);
11281
11282 // Note: the expression type doesn't necessarily match the
11283 // type-as-written, but that's okay, because it should always be
11284 // derivable from the initializer.
11285
11286 return getDerived().RebuildCompoundLiteralExpr(
11287 E->getLParenLoc(), NewT,
11288 /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
11289}
11290
11291template<typename Derived>
11292ExprResult
11293TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
11294 ExprResult Base = getDerived().TransformExpr(E->getBase());
11295 if (Base.isInvalid())
11296 return ExprError();
11297
11298 if (!getDerived().AlwaysRebuild() &&
11299 Base.get() == E->getBase())
11300 return E;
11301
11302 // FIXME: Bad source location
11303 SourceLocation FakeOperatorLoc =
11304 SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
11305 return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
11306 E->getAccessorLoc(),
11307 E->getAccessor());
11308}
11309
11310template<typename Derived>
11311ExprResult
11312TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
11313 if (InitListExpr *Syntactic = E->getSyntacticForm())
11314 E = Syntactic;
11315
11316 bool InitChanged = false;
11317
11318 EnterExpressionEvaluationContext Context(
11319 getSema(), EnterExpressionEvaluationContext::InitList);
11320
11321 SmallVector<Expr*, 4> Inits;
11322 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
11323 Inits, &InitChanged))
11324 return ExprError();
11325
11326 if (!getDerived().AlwaysRebuild() && !InitChanged) {
11327 // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
11328 // in some cases. We can't reuse it in general, because the syntactic and
11329 // semantic forms are linked, and we can't know that semantic form will
11330 // match even if the syntactic form does.
11331 }
11332
11333 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
11334 E->getRBraceLoc());
11335}
11336
11337template<typename Derived>
11338ExprResult
11339TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
11340 Designation Desig;
11341
11342 // transform the initializer value
11343 ExprResult Init = getDerived().TransformExpr(E->getInit());
11344 if (Init.isInvalid())
11345 return ExprError();
11346
11347 // transform the designators.
11348 SmallVector<Expr*, 4> ArrayExprs;
11349 bool ExprChanged = false;
11350 for (const DesignatedInitExpr::Designator &D : E->designators()) {
11351 if (D.isFieldDesignator()) {
11352 Desig.AddDesignator(Designator::getField(D.getFieldName(),
11353 D.getDotLoc(),
11354 D.getFieldLoc()));
11355 if (D.getField()) {
11356 FieldDecl *Field = cast_or_null<FieldDecl>(
11357 getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
11358 if (Field != D.getField())
11359 // Rebuild the expression when the transformed FieldDecl is
11360 // different to the already assigned FieldDecl.
11361 ExprChanged = true;
11362 } else {
11363 // Ensure that the designator expression is rebuilt when there isn't
11364 // a resolved FieldDecl in the designator as we don't want to assign
11365 // a FieldDecl to a pattern designator that will be instantiated again.
11366 ExprChanged = true;
11367 }
11368 continue;
11369 }
11370
11371 if (D.isArrayDesignator()) {
11372 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
11373 if (Index.isInvalid())
11374 return ExprError();
11375
11376 Desig.AddDesignator(
11377 Designator::getArray(Index.get(), D.getLBracketLoc()));
11378
11379 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
11380 ArrayExprs.push_back(Index.get());
11381 continue;
11382 }
11383
11384 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", 11384, __extension__ __PRETTY_FUNCTION__
))
;
11385 ExprResult Start
11386 = getDerived().TransformExpr(E->getArrayRangeStart(D));
11387 if (Start.isInvalid())
11388 return ExprError();
11389
11390 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
11391 if (End.isInvalid())
11392 return ExprError();
11393
11394 Desig.AddDesignator(Designator::getArrayRange(Start.get(),
11395 End.get(),
11396 D.getLBracketLoc(),
11397 D.getEllipsisLoc()));
11398
11399 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
11400 End.get() != E->getArrayRangeEnd(D);
11401
11402 ArrayExprs.push_back(Start.get());
11403 ArrayExprs.push_back(End.get());
11404 }
11405
11406 if (!getDerived().AlwaysRebuild() &&
11407 Init.get() == E->getInit() &&
11408 !ExprChanged)
11409 return E;
11410
11411 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
11412 E->getEqualOrColonLoc(),
11413 E->usesGNUSyntax(), Init.get());
11414}
11415
11416// Seems that if TransformInitListExpr() only works on the syntactic form of an
11417// InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
11418template<typename Derived>
11419ExprResult
11420TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
11421 DesignatedInitUpdateExpr *E) {
11422 llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "::llvm::llvm_unreachable_internal("Unexpected DesignatedInitUpdateExpr in syntactic form of "
"initializer", "clang/lib/Sema/TreeTransform.h", 11423)
11423 "initializer")::llvm::llvm_unreachable_internal("Unexpected DesignatedInitUpdateExpr in syntactic form of "
"initializer", "clang/lib/Sema/TreeTransform.h", 11423)
;
11424 return ExprError();
11425}
11426
11427template<typename Derived>
11428ExprResult
11429TreeTransform<Derived>::TransformNoInitExpr(
11430 NoInitExpr *E) {
11431 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", 11431)
;
11432 return ExprError();
11433}
11434
11435template<typename Derived>
11436ExprResult
11437TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
11438 llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer")::llvm::llvm_unreachable_internal("Unexpected ArrayInitLoopExpr outside of initializer"
, "clang/lib/Sema/TreeTransform.h", 11438)
;
11439 return ExprError();
11440}
11441
11442template<typename Derived>
11443ExprResult
11444TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
11445 llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer")::llvm::llvm_unreachable_internal("Unexpected ArrayInitIndexExpr outside of initializer"
, "clang/lib/Sema/TreeTransform.h", 11445)
;
11446 return ExprError();
11447}
11448
11449template<typename Derived>
11450ExprResult
11451TreeTransform<Derived>::TransformImplicitValueInitExpr(
11452 ImplicitValueInitExpr *E) {
11453 TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
11454
11455 // FIXME: Will we ever have proper type location here? Will we actually
11456 // need to transform the type?
11457 QualType T = getDerived().TransformType(E->getType());
11458 if (T.isNull())
11459 return ExprError();
11460
11461 if (!getDerived().AlwaysRebuild() &&
11462 T == E->getType())
11463 return E;
11464
11465 return getDerived().RebuildImplicitValueInitExpr(T);
11466}
11467
11468template<typename Derived>
11469ExprResult
11470TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
11471 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
11472 if (!TInfo)
11473 return ExprError();
11474
11475 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11476 if (SubExpr.isInvalid())
11477 return ExprError();
11478
11479 if (!getDerived().AlwaysRebuild() &&
11480 TInfo == E->getWrittenTypeInfo() &&
11481 SubExpr.get() == E->getSubExpr())
11482 return E;
11483
11484 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
11485 TInfo, E->getRParenLoc());
11486}
11487
11488template<typename Derived>
11489ExprResult
11490TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
11491 bool ArgumentChanged = false;
11492 SmallVector<Expr*, 4> Inits;
11493 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
11494 &ArgumentChanged))
11495 return ExprError();
11496
11497 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
11498 Inits,
11499 E->getRParenLoc());
11500}
11501
11502/// Transform an address-of-label expression.
11503///
11504/// By default, the transformation of an address-of-label expression always
11505/// rebuilds the expression, so that the label identifier can be resolved to
11506/// the corresponding label statement by semantic analysis.
11507template<typename Derived>
11508ExprResult
11509TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
11510 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
11511 E->getLabel());
11512 if (!LD)
11513 return ExprError();
11514
11515 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
11516 cast<LabelDecl>(LD));
11517}
11518
11519template<typename Derived>
11520ExprResult
11521TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
11522 SemaRef.ActOnStartStmtExpr();
11523 StmtResult SubStmt
11524 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
11525 if (SubStmt.isInvalid()) {
11526 SemaRef.ActOnStmtExprError();
11527 return ExprError();
11528 }
11529
11530 unsigned OldDepth = E->getTemplateDepth();
11531 unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
11532
11533 if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
11534 SubStmt.get() == E->getSubStmt()) {
11535 // Calling this an 'error' is unintuitive, but it does the right thing.
11536 SemaRef.ActOnStmtExprError();
11537 return SemaRef.MaybeBindToTemporary(E);
11538 }
11539
11540 return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
11541 E->getRParenLoc(), NewDepth);
11542}
11543
11544template<typename Derived>
11545ExprResult
11546TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
11547 ExprResult Cond = getDerived().TransformExpr(E->getCond());
11548 if (Cond.isInvalid())
11549 return ExprError();
11550
11551 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11552 if (LHS.isInvalid())
11553 return ExprError();
11554
11555 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11556 if (RHS.isInvalid())
11557 return ExprError();
11558
11559 if (!getDerived().AlwaysRebuild() &&
11560 Cond.get() == E->getCond() &&
11561 LHS.get() == E->getLHS() &&
11562 RHS.get() == E->getRHS())
11563 return E;
11564
11565 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
11566 Cond.get(), LHS.get(), RHS.get(),
11567 E->getRParenLoc());
11568}
11569
11570template<typename Derived>
11571ExprResult
11572TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
11573 return E;
11574}
11575
11576template<typename Derived>
11577ExprResult
11578TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11579 switch (E->getOperator()) {
3
Control jumps to 'case OO_Subscript:' at line 11586
11580 case OO_New:
11581 case OO_Delete:
11582 case OO_Array_New:
11583 case OO_Array_Delete:
11584 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", 11584)
;
11585
11586 case OO_Subscript:
11587 case OO_Call: {
11588 // This is a call to an object's operator().
11589 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", 11589, __extension__ __PRETTY_FUNCTION__
))
;
4
Assuming the condition is true
5
'?' condition is true
11590
11591 // Transform the object itself.
11592 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
11593 if (Object.isInvalid())
6
Assuming the condition is false
7
Taking false branch
11594 return ExprError();
11595
11596 // FIXME: Poor location information
11597 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
11598 static_cast<Expr *>(Object.get())->getEndLoc());
11599
11600 // Transform the call arguments.
11601 SmallVector<Expr*, 8> Args;
11602 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
8
Taking false branch
11603 Args))
11604 return ExprError();
11605
11606 if (E->getOperator() == OO_Subscript)
9
Taking true branch
11607 return getDerived().RebuildCxxSubscriptExpr(Object.get(), FakeLParenLoc,
10
Calling 'TreeTransform::RebuildCxxSubscriptExpr'
11608 Args, E->getEndLoc());
11609
11610 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
11611 E->getEndLoc());
11612 }
11613
11614#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
11615 case OO_##Name: \
11616 break;
11617
11618#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
11619#include "clang/Basic/OperatorKinds.def"
11620
11621 case OO_Conditional:
11622 llvm_unreachable("conditional operator is not actually overloadable")::llvm::llvm_unreachable_internal("conditional operator is not actually overloadable"
, "clang/lib/Sema/TreeTransform.h", 11622)
;
11623
11624 case OO_None:
11625 case NUM_OVERLOADED_OPERATORS:
11626 llvm_unreachable("not an overloaded operator?")::llvm::llvm_unreachable_internal("not an overloaded operator?"
, "clang/lib/Sema/TreeTransform.h", 11626)
;
11627 }
11628
11629 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11630 if (Callee.isInvalid())
11631 return ExprError();
11632
11633 ExprResult First;
11634 if (E->getOperator() == OO_Amp)
11635 First = getDerived().TransformAddressOfOperand(E->getArg(0));
11636 else
11637 First = getDerived().TransformExpr(E->getArg(0));
11638 if (First.isInvalid())
11639 return ExprError();
11640
11641 ExprResult Second;
11642 if (E->getNumArgs() == 2) {
11643 Second = getDerived().TransformExpr(E->getArg(1));
11644 if (Second.isInvalid())
11645 return ExprError();
11646 }
11647
11648 if (!getDerived().AlwaysRebuild() &&
11649 Callee.get() == E->getCallee() &&
11650 First.get() == E->getArg(0) &&
11651 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
11652 return SemaRef.MaybeBindToTemporary(E);
11653
11654 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11655 FPOptionsOverride NewOverrides(E->getFPFeatures());
11656 getSema().CurFPFeatures =
11657 NewOverrides.applyOverrides(getSema().getLangOpts());
11658 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11659
11660 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
11661 E->getOperatorLoc(),
11662 Callee.get(),
11663 First.get(),
11664 Second.get());
11665}
11666
11667template<typename Derived>
11668ExprResult
11669TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
11670 return getDerived().TransformCallExpr(E);
11671}
11672
11673template <typename Derived>
11674ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
11675 bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
11676 getSema().CurContext != E->getParentContext();
11677
11678 if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
11679 return E;
11680
11681 return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
11682 E->getBeginLoc(), E->getEndLoc(),
11683 getSema().CurContext);
11684}
11685
11686template<typename Derived>
11687ExprResult
11688TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
11689 // Transform the callee.
11690 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11691 if (Callee.isInvalid())
11692 return ExprError();
11693
11694 // Transform exec config.
11695 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
11696 if (EC.isInvalid())
11697 return ExprError();
11698
11699 // Transform arguments.
11700 bool ArgChanged = false;
11701 SmallVector<Expr*, 8> Args;
11702 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11703 &ArgChanged))
11704 return ExprError();
11705
11706 if (!getDerived().AlwaysRebuild() &&
11707 Callee.get() == E->getCallee() &&
11708 !ArgChanged)
11709 return SemaRef.MaybeBindToTemporary(E);
11710
11711 // FIXME: Wrong source location information for the '('.
11712 SourceLocation FakeLParenLoc
11713 = ((Expr *)Callee.get())->getSourceRange().getBegin();
11714 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11715 Args,
11716 E->getRParenLoc(), EC.get());
11717}
11718
11719template<typename Derived>
11720ExprResult
11721TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
11722 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11723 if (!Type)
11724 return ExprError();
11725
11726 ExprResult SubExpr
11727 = getDerived().TransformExpr(E->getSubExprAsWritten());
11728 if (SubExpr.isInvalid())
11729 return ExprError();
11730
11731 if (!getDerived().AlwaysRebuild() &&
11732 Type == E->getTypeInfoAsWritten() &&
11733 SubExpr.get() == E->getSubExpr())
11734 return E;
11735 return getDerived().RebuildCXXNamedCastExpr(
11736 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
11737 Type, E->getAngleBrackets().getEnd(),
11738 // FIXME. this should be '(' location
11739 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
11740}
11741
11742template<typename Derived>
11743ExprResult
11744TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
11745 TypeSourceInfo *TSI =
11746 getDerived().TransformType(BCE->getTypeInfoAsWritten());
11747 if (!TSI)
11748 return ExprError();
11749
11750 ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
11751 if (Sub.isInvalid())
11752 return ExprError();
11753
11754 return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
11755 Sub.get(), BCE->getEndLoc());
11756}
11757
11758template<typename Derived>
11759ExprResult
11760TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
11761 return getDerived().TransformCXXNamedCastExpr(E);
11762}
11763
11764template<typename Derived>
11765ExprResult
11766TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
11767 return getDerived().TransformCXXNamedCastExpr(E);
11768}
11769
11770template<typename Derived>
11771ExprResult
11772TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
11773 CXXReinterpretCastExpr *E) {
11774 return getDerived().TransformCXXNamedCastExpr(E);
11775}
11776
11777template<typename Derived>
11778ExprResult
11779TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
11780 return getDerived().TransformCXXNamedCastExpr(E);
11781}
11782
11783template<typename Derived>
11784ExprResult
11785TreeTransform<Derived>::TransformCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
11786 return getDerived().TransformCXXNamedCastExpr(E);
11787}
11788
11789template<typename Derived>
11790ExprResult
11791TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
11792 CXXFunctionalCastExpr *E) {
11793 TypeSourceInfo *Type =
11794 getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
11795 if (!Type)
11796 return ExprError();
11797
11798 ExprResult SubExpr
11799 = getDerived().TransformExpr(E->getSubExprAsWritten());
11800 if (SubExpr.isInvalid())
11801 return ExprError();
11802
11803 if (!getDerived().AlwaysRebuild() &&
11804 Type == E->getTypeInfoAsWritten() &&
11805 SubExpr.get() == E->getSubExpr())
11806 return E;
11807
11808 return getDerived().RebuildCXXFunctionalCastExpr(Type,
11809 E->getLParenLoc(),
11810 SubExpr.get(),
11811 E->getRParenLoc(),
11812 E->isListInitialization());
11813}
11814
11815template<typename Derived>
11816ExprResult
11817TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
11818 if (E->isTypeOperand()) {
11819 TypeSourceInfo *TInfo
11820 = getDerived().TransformType(E->getTypeOperandSourceInfo());
11821 if (!TInfo)
11822 return ExprError();
11823
11824 if (!getDerived().AlwaysRebuild() &&
11825 TInfo == E->getTypeOperandSourceInfo())
11826 return E;
11827
11828 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
11829 TInfo, E->getEndLoc());
11830 }
11831
11832 // Typeid's operand is an unevaluated context, unless it's a polymorphic
11833 // type. We must not unilaterally enter unevaluated context here, as then
11834 // semantic processing can re-transform an already transformed operand.
11835 Expr *Op = E->getExprOperand();
11836 auto EvalCtx = Sema::ExpressionEvaluationContext::Unevaluated;
11837 if (E->isGLValue())
11838 if (auto *RecordT = Op->getType()->getAs<RecordType>())
11839 if (cast<CXXRecordDecl>(RecordT->getDecl())->isPolymorphic())
11840 EvalCtx = SemaRef.ExprEvalContexts.back().Context;
11841
11842 EnterExpressionEvaluationContext Unevaluated(SemaRef, EvalCtx,
11843 Sema::ReuseLambdaContextDecl);
11844
11845 ExprResult SubExpr = getDerived().TransformExpr(Op);
11846 if (SubExpr.isInvalid())
11847 return ExprError();
11848
11849 if (!getDerived().AlwaysRebuild() &&
11850 SubExpr.get() == E->getExprOperand())
11851 return E;
11852
11853 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
11854 SubExpr.get(), E->getEndLoc());
11855}
11856
11857template<typename Derived>
11858ExprResult
11859TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
11860 if (E->isTypeOperand()) {
11861 TypeSourceInfo *TInfo
11862 = getDerived().TransformType(E->getTypeOperandSourceInfo());
11863 if (!TInfo)
11864 return ExprError();
11865
11866 if (!getDerived().AlwaysRebuild() &&
11867 TInfo == E->getTypeOperandSourceInfo())
11868 return E;
11869
11870 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
11871 TInfo, E->getEndLoc());
11872 }
11873
11874 EnterExpressionEvaluationContext Unevaluated(
11875 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11876
11877 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
11878 if (SubExpr.isInvalid())
11879 return ExprError();
11880
11881 if (!getDerived().AlwaysRebuild() &&
11882 SubExpr.get() == E->getExprOperand())
11883 return E;
11884
11885 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
11886 SubExpr.get(), E->getEndLoc());
11887}
11888
11889template<typename Derived>
11890ExprResult
11891TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
11892 return E;
11893}
11894
11895template<typename Derived>
11896ExprResult
11897TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
11898 CXXNullPtrLiteralExpr *E) {
11899 return E;
11900}
11901
11902template<typename Derived>
11903ExprResult
11904TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
11905 QualType T = getSema().getCurrentThisType();
11906
11907 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
11908 // Mark it referenced in the new context regardless.
11909 // FIXME: this is a bit instantiation-specific.
11910 getSema().MarkThisReferenced(E);
11911 return E;
11912 }
11913
11914 return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
11915}
11916
11917template<typename Derived>
11918ExprResult
11919TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
11920 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11921 if (SubExpr.isInvalid())
11922 return ExprError();
11923
11924 if (!getDerived().AlwaysRebuild() &&
11925 SubExpr.get() == E->getSubExpr())
11926 return E;
11927
11928 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
11929 E->isThrownVariableInScope());
11930}
11931
11932template<typename Derived>
11933ExprResult
11934TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11935 ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
11936 getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
11937 if (!Param)
11938 return ExprError();
11939
11940 if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
11941 E->getUsedContext() == SemaRef.CurContext)
11942 return E;
11943
11944 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
11945}
11946
11947template<typename Derived>
11948ExprResult
11949TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
11950 FieldDecl *Field = cast_or_null<FieldDecl>(
11951 getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
11952 if (!Field)
11953 return ExprError();
11954
11955 if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
11956 E->getUsedContext() == SemaRef.CurContext)
11957 return E;
11958
11959 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
11960}
11961
11962template<typename Derived>
11963ExprResult
11964TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
11965 CXXScalarValueInitExpr *E) {
11966 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
11967 if (!T)
11968 return ExprError();
11969
11970 if (!getDerived().AlwaysRebuild() &&
11971 T == E->getTypeSourceInfo())
11972 return E;
11973
11974 return getDerived().RebuildCXXScalarValueInitExpr(T,
11975 /*FIXME:*/T->getTypeLoc().getEndLoc(),
11976 E->getRParenLoc());
11977}
11978
11979template<typename Derived>
11980ExprResult
11981TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
11982 // Transform the type that we're allocating
11983 TypeSourceInfo *AllocTypeInfo =
11984 getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
11985 if (!AllocTypeInfo)
11986 return ExprError();
11987
11988 // Transform the size of the array we're allocating (if any).
11989 Optional<Expr *> ArraySize;
11990 if (E->isArray()) {
11991 ExprResult NewArraySize;
11992 if (Optional<Expr *> OldArraySize = E->getArraySize()) {
11993 NewArraySize = getDerived().TransformExpr(*OldArraySize);
11994 if (NewArraySize.isInvalid())
11995 return ExprError();
11996 }
11997 ArraySize = NewArraySize.get();
11998 }
11999
12000 // Transform the placement arguments (if any).
12001 bool ArgumentChanged = false;
12002 SmallVector<Expr*, 8> PlacementArgs;
12003 if (getDerived().TransformExprs(E->getPlacementArgs(),
12004 E->getNumPlacementArgs(), true,
12005 PlacementArgs, &ArgumentChanged))
12006 return ExprError();
12007
12008 // Transform the initializer (if any).
12009 Expr *OldInit = E->getInitializer();
12010 ExprResult NewInit;
12011 if (OldInit)
12012 NewInit = getDerived().TransformInitializer(OldInit, true);
12013 if (NewInit.isInvalid())
12014 return ExprError();
12015
12016 // Transform new operator and delete operator.
12017 FunctionDecl *OperatorNew = nullptr;
12018 if (E->getOperatorNew()) {
12019 OperatorNew = cast_or_null<FunctionDecl>(
12020 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
12021 if (!OperatorNew)
12022 return ExprError();
12023 }
12024
12025 FunctionDecl *OperatorDelete = nullptr;
12026 if (E->getOperatorDelete()) {
12027 OperatorDelete = cast_or_null<FunctionDecl>(
12028 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12029 if (!OperatorDelete)
12030 return ExprError();
12031 }
12032
12033 if (!getDerived().AlwaysRebuild() &&
12034 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
12035 ArraySize == E->getArraySize() &&
12036 NewInit.get() == OldInit &&
12037 OperatorNew == E->getOperatorNew() &&
12038 OperatorDelete == E->getOperatorDelete() &&
12039 !ArgumentChanged) {
12040 // Mark any declarations we need as referenced.
12041 // FIXME: instantiation-specific.
12042 if (OperatorNew)
12043 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
12044 if (OperatorDelete)
12045 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12046
12047 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
12048 QualType ElementType
12049 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
12050 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
12051 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
12052 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
12053 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
12054 }
12055 }
12056 }
12057
12058 return E;
12059 }
12060
12061 QualType AllocType = AllocTypeInfo->getType();
12062 if (!ArraySize) {
12063 // If no array size was specified, but the new expression was
12064 // instantiated with an array type (e.g., "new T" where T is
12065 // instantiated with "int[4]"), extract the outer bound from the
12066 // array type as our array size. We do this with constant and
12067 // dependently-sized array types.
12068 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
12069 if (!ArrayT) {
12070 // Do nothing
12071 } else if (const ConstantArrayType *ConsArrayT
12072 = dyn_cast<ConstantArrayType>(ArrayT)) {
12073 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
12074 SemaRef.Context.getSizeType(),
12075 /*FIXME:*/ E->getBeginLoc());
12076 AllocType = ConsArrayT->getElementType();
12077 } else if (const DependentSizedArrayType *DepArrayT
12078 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
12079 if (DepArrayT->getSizeExpr()) {
12080 ArraySize = DepArrayT->getSizeExpr();
12081 AllocType = DepArrayT->getElementType();
12082 }
12083 }
12084 }
12085
12086 return getDerived().RebuildCXXNewExpr(
12087 E->getBeginLoc(), E->isGlobalNew(),
12088 /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
12089 /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
12090 AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
12091}
12092
12093template<typename Derived>
12094ExprResult
12095TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
12096 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
12097 if (Operand.isInvalid())
12098 return ExprError();
12099
12100 // Transform the delete operator, if known.
12101 FunctionDecl *OperatorDelete = nullptr;
12102 if (E->getOperatorDelete()) {
12103 OperatorDelete = cast_or_null<FunctionDecl>(
12104 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12105 if (!OperatorDelete)
12106 return ExprError();
12107 }
12108
12109 if (!getDerived().AlwaysRebuild() &&
12110 Operand.get() == E->getArgument() &&
12111 OperatorDelete == E->getOperatorDelete()) {
12112 // Mark any declarations we need as referenced.
12113 // FIXME: instantiation-specific.
12114 if (OperatorDelete)
12115 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12116
12117 if (!E->getArgument()->isTypeDependent()) {
12118 QualType Destroyed = SemaRef.Context.getBaseElementType(
12119 E->getDestroyedType());
12120 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12121 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12122 SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
12123 SemaRef.LookupDestructor(Record));
12124 }
12125 }
12126
12127 return E;
12128 }
12129
12130 return getDerived().RebuildCXXDeleteExpr(
12131 E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
12132}
12133
12134template<typename Derived>
12135ExprResult
12136TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
12137 CXXPseudoDestructorExpr *E) {
12138 ExprResult Base = getDerived().TransformExpr(E->getBase());
12139 if (Base.isInvalid())
12140 return ExprError();
12141
12142 ParsedType ObjectTypePtr;
12143 bool MayBePseudoDestructor = false;
12144 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
12145 E->getOperatorLoc(),
12146 E->isArrow()? tok::arrow : tok::period,
12147 ObjectTypePtr,
12148 MayBePseudoDestructor);
12149 if (Base.isInvalid())
12150 return ExprError();
12151
12152 QualType ObjectType = ObjectTypePtr.get();
12153 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
12154 if (QualifierLoc) {
12155 QualifierLoc
12156 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
12157 if (!QualifierLoc)
12158 return ExprError();
12159 }
12160 CXXScopeSpec SS;
12161 SS.Adopt(QualifierLoc);
12162
12163 PseudoDestructorTypeStorage Destroyed;
12164 if (E->getDestroyedTypeInfo()) {
12165 TypeSourceInfo *DestroyedTypeInfo
12166 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
12167 ObjectType, nullptr, SS);
12168 if (!DestroyedTypeInfo)
12169 return ExprError();
12170 Destroyed = DestroyedTypeInfo;
12171 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
12172 // We aren't likely to be able to resolve the identifier down to a type
12173 // now anyway, so just retain the identifier.
12174 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
12175 E->getDestroyedTypeLoc());
12176 } else {
12177 // Look for a destructor known with the given name.
12178 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
12179 *E->getDestroyedTypeIdentifier(),
12180 E->getDestroyedTypeLoc(),
12181 /*Scope=*/nullptr,
12182 SS, ObjectTypePtr,
12183 false);
12184 if (!T)
12185 return ExprError();
12186
12187 Destroyed
12188 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
12189 E->getDestroyedTypeLoc());
12190 }
12191
12192 TypeSourceInfo *ScopeTypeInfo = nullptr;
12193 if (E->getScopeTypeInfo()) {
12194 CXXScopeSpec EmptySS;
12195 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
12196 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
12197 if (!ScopeTypeInfo)
12198 return ExprError();
12199 }
12200
12201 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
12202 E->getOperatorLoc(),
12203 E->isArrow(),
12204 SS,
12205 ScopeTypeInfo,
12206 E->getColonColonLoc(),
12207 E->getTildeLoc(),
12208 Destroyed);
12209}
12210
12211template <typename Derived>
12212bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
12213 bool RequiresADL,
12214 LookupResult &R) {
12215 // Transform all the decls.
12216 bool AllEmptyPacks = true;
12217 for (auto *OldD : Old->decls()) {
12218 Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
12219 if (!InstD) {
12220 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
12221 // This can happen because of dependent hiding.
12222 if (isa<UsingShadowDecl>(OldD))
12223 continue;
12224 else {
12225 R.clear();
12226 return true;
12227 }
12228 }
12229
12230 // Expand using pack declarations.
12231 NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
12232 ArrayRef<NamedDecl*> Decls = SingleDecl;
12233 if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
12234 Decls = UPD->expansions();
12235
12236 // Expand using declarations.
12237 for (auto *D : Decls) {
12238 if (auto *UD = dyn_cast<UsingDecl>(D)) {
12239 for (auto *SD : UD->shadows())
12240 R.addDecl(SD);
12241 } else {
12242 R.addDecl(D);
12243 }
12244 }
12245
12246 AllEmptyPacks &= Decls.empty();
12247 };
12248
12249 // C++ [temp.res]/8.4.2:
12250 // The program is ill-formed, no diagnostic required, if [...] lookup for
12251 // a name in the template definition found a using-declaration, but the
12252 // lookup in the corresponding scope in the instantiation odoes not find
12253 // any declarations because the using-declaration was a pack expansion and
12254 // the corresponding pack is empty
12255 if (AllEmptyPacks && !RequiresADL) {
12256 getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
12257 << isa<UnresolvedMemberExpr>(Old) << Old->getName();
12258 return true;
12259 }
12260
12261 // Resolve a kind, but don't do any further analysis. If it's
12262 // ambiguous, the callee needs to deal with it.
12263 R.resolveKind();
12264 return false;
12265}
12266
12267template<typename Derived>
12268ExprResult
12269TreeTransform<Derived>::TransformUnresolvedLookupExpr(
12270 UnresolvedLookupExpr *Old) {
12271 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
12272 Sema::LookupOrdinaryName);
12273
12274 // Transform the declaration set.
12275 if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
12276 return ExprError();
12277
12278 // Rebuild the nested-name qualifier, if present.
12279 CXXScopeSpec SS;
12280 if (Old->getQualifierLoc()) {
12281 NestedNameSpecifierLoc QualifierLoc
12282 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12283 if (!QualifierLoc)
12284 return ExprError();
12285
12286 SS.Adopt(QualifierLoc);
12287 }
12288
12289 if (Old->getNamingClass()) {
12290 CXXRecordDecl *NamingClass
12291 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12292 Old->getNameLoc(),
12293 Old->getNamingClass()));
12294 if (!NamingClass) {
12295 R.clear();
12296 return ExprError();
12297 }
12298
12299 R.setNamingClass(NamingClass);
12300 }
12301
12302 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12303
12304 // If we have neither explicit template arguments, nor the template keyword,
12305 // it's a normal declaration name or member reference.
12306 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
12307 NamedDecl *D = R.getAsSingle<NamedDecl>();
12308 // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
12309 // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
12310 // give a good diagnostic.
12311 if (D && D->isCXXInstanceMember()) {
12312 return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12313 /*TemplateArgs=*/nullptr,
12314 /*Scope=*/nullptr);
12315 }
12316
12317 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
12318 }
12319
12320 // If we have template arguments, rebuild them, then rebuild the
12321 // templateid expression.
12322 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
12323 if (Old->hasExplicitTemplateArgs() &&
12324 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12325 Old->getNumTemplateArgs(),
12326 TransArgs)) {
12327 R.clear();
12328 return ExprError();
12329 }
12330
12331 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
12332 Old->requiresADL(), &TransArgs);
12333}
12334
12335template<typename Derived>
12336ExprResult
12337TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
12338 bool ArgChanged = false;
12339 SmallVector<TypeSourceInfo *, 4> Args;
12340 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
12341 TypeSourceInfo *From = E->getArg(I);
12342 TypeLoc FromTL = From->getTypeLoc();
12343 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
12344 TypeLocBuilder TLB;
12345 TLB.reserve(FromTL.getFullDataSize());
12346 QualType To = getDerived().TransformType(TLB, FromTL);
12347 if (To.isNull())
12348 return ExprError();
12349
12350 if (To == From->getType())
12351 Args.push_back(From);
12352 else {
12353 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12354 ArgChanged = true;
12355 }
12356 continue;
12357 }
12358
12359 ArgChanged = true;
12360
12361 // We have a pack expansion. Instantiate it.
12362 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
12363 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
12364 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12365 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
12366
12367 // Determine whether the set of unexpanded parameter packs can and should
12368 // be expanded.
12369 bool Expand = true;
12370 bool RetainExpansion = false;
12371 Optional<unsigned> OrigNumExpansions =
12372 ExpansionTL.getTypePtr()->getNumExpansions();
12373 Optional<unsigned> NumExpansions = OrigNumExpansions;
12374 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
12375 PatternTL.getSourceRange(),
12376 Unexpanded,
12377 Expand, RetainExpansion,
12378 NumExpansions))
12379 return ExprError();
12380
12381 if (!Expand) {
12382 // The transform has determined that we should perform a simple
12383 // transformation on the pack expansion, producing another pack
12384 // expansion.
12385 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12386
12387 TypeLocBuilder TLB;
12388 TLB.reserve(From->getTypeLoc().getFullDataSize());
12389
12390 QualType To = getDerived().TransformType(TLB, PatternTL);
12391 if (To.isNull())
12392 return ExprError();
12393
12394 To = getDerived().RebuildPackExpansionType(To,
12395 PatternTL.getSourceRange(),
12396 ExpansionTL.getEllipsisLoc(),
12397 NumExpansions);
12398 if (To.isNull())
12399 return ExprError();
12400
12401 PackExpansionTypeLoc ToExpansionTL
12402 = TLB.push<PackExpansionTypeLoc>(To);
12403 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12404 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12405 continue;
12406 }
12407
12408 // Expand the pack expansion by substituting for each argument in the
12409 // pack(s).
12410 for (unsigned I = 0; I != *NumExpansions; ++I) {
12411 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
12412 TypeLocBuilder TLB;
12413 TLB.reserve(PatternTL.getFullDataSize());
12414 QualType To = getDerived().TransformType(TLB, PatternTL);
12415 if (To.isNull())
12416 return ExprError();
12417
12418 if (To->containsUnexpandedParameterPack()) {
12419 To = getDerived().RebuildPackExpansionType(To,
12420 PatternTL.getSourceRange(),
12421 ExpansionTL.getEllipsisLoc(),
12422 NumExpansions);
12423 if (To.isNull())
12424 return ExprError();
12425
12426 PackExpansionTypeLoc ToExpansionTL
12427 = TLB.push<PackExpansionTypeLoc>(To);
12428 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12429 }
12430
12431 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12432 }
12433
12434 if (!RetainExpansion)
12435 continue;
12436
12437 // If we're supposed to retain a pack expansion, do so by temporarily
12438 // forgetting the partially-substituted parameter pack.
12439 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12440
12441 TypeLocBuilder TLB;
12442 TLB.reserve(From->getTypeLoc().getFullDataSize());
12443
12444 QualType To = getDerived().TransformType(TLB, PatternTL);
12445 if (To.isNull())
12446 return ExprError();
12447
12448 To = getDerived().RebuildPackExpansionType(To,
12449 PatternTL.getSourceRange(),
12450 ExpansionTL.getEllipsisLoc(),
12451 NumExpansions);
12452 if (To.isNull())
12453 return ExprError();
12454
12455 PackExpansionTypeLoc ToExpansionTL
12456 = TLB.push<PackExpansionTypeLoc>(To);
12457 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12458 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12459 }
12460
12461 if (!getDerived().AlwaysRebuild() && !ArgChanged)
12462 return E;
12463
12464 return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
12465 E->getEndLoc());
12466}
12467
12468template<typename Derived>
12469ExprResult
12470TreeTransform<Derived>::TransformConceptSpecializationExpr(
12471 ConceptSpecializationExpr *E) {
12472 const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
12473 TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
12474 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12475 Old->NumTemplateArgs, TransArgs))
12476 return ExprError();
12477
12478 return getDerived().RebuildConceptSpecializationExpr(
12479 E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
12480 E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
12481 &TransArgs);
12482}
12483
12484template<typename Derived>
12485ExprResult
12486TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
12487 SmallVector<ParmVarDecl*, 4> TransParams;
12488 SmallVector<QualType, 4> TransParamTypes;
12489 Sema::ExtParameterInfoBuilder ExtParamInfos;
12490
12491 // C++2a [expr.prim.req]p2
12492 // Expressions appearing within a requirement-body are unevaluated operands.
12493 EnterExpressionEvaluationContext Ctx(
12494 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12495
12496 RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
12497 getSema().Context, getSema().CurContext,
12498 E->getBody()->getBeginLoc());
12499
12500 Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
12501
12502 if (getDerived().TransformFunctionTypeParams(E->getRequiresKWLoc(),
12503 E->getLocalParameters(),
12504 /*ParamTypes=*/nullptr,
12505 /*ParamInfos=*/nullptr,
12506 TransParamTypes, &TransParams,
12507 ExtParamInfos))
12508 return ExprError();
12509
12510 for (ParmVarDecl *Param : TransParams)
12511 Param->setDeclContext(Body);
12512
12513 SmallVector<concepts::Requirement *, 4> TransReqs;
12514 if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
12515 TransReqs))
12516 return ExprError();
12517
12518 for (concepts::Requirement *Req : TransReqs) {
12519 if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
12520 if (ER->getReturnTypeRequirement().isTypeConstraint()) {
12521 ER->getReturnTypeRequirement()
12522 .getTypeConstraintTemplateParameterList()->getParam(0)
12523 ->setDeclContext(Body);
12524 }
12525 }
12526 }
12527
12528 return getDerived().RebuildRequiresExpr(E->getRequiresKWLoc(), Body,
12529 TransParams, TransReqs,
12530 E->getRBraceLoc());
12531}
12532
12533template<typename Derived>
12534bool TreeTransform<Derived>::TransformRequiresExprRequirements(
12535 ArrayRef<concepts::Requirement *> Reqs,
12536 SmallVectorImpl<concepts::Requirement *> &Transformed) {
12537 for (concepts::Requirement *Req : Reqs) {
12538 concepts::Requirement *TransReq = nullptr;
12539 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
12540 TransReq = getDerived().TransformTypeRequirement(TypeReq);
12541 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
12542 TransReq = getDerived().TransformExprRequirement(ExprReq);
12543 else
12544 TransReq = getDerived().TransformNestedRequirement(
12545 cast<concepts::NestedRequirement>(Req));
12546 if (!TransReq)
12547 return true;
12548 Transformed.push_back(TransReq);
12549 }
12550 return false;
12551}
12552
12553template<typename Derived>
12554concepts::TypeRequirement *
12555TreeTransform<Derived>::TransformTypeRequirement(
12556 concepts::TypeRequirement *Req) {
12557 if (Req->isSubstitutionFailure()) {
12558 if (getDerived().AlwaysRebuild())
12559 return getDerived().RebuildTypeRequirement(
12560 Req->getSubstitutionDiagnostic());
12561 return Req;
12562 }
12563 TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
12564 if (!TransType)
12565 return nullptr;
12566 return getDerived().RebuildTypeRequirement(TransType);
12567}
12568
12569template<typename Derived>
12570concepts::ExprRequirement *
12571TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
12572 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
12573 if (Req->isExprSubstitutionFailure())
12574 TransExpr = Req->getExprSubstitutionDiagnostic();
12575 else {
12576 ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
12577 if (TransExprRes.isUsable() && TransExprRes.get()->hasPlaceholderType())
12578 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
12579 if (TransExprRes.isInvalid())
12580 return nullptr;
12581 TransExpr = TransExprRes.get();
12582 }
12583
12584 llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
12585 const auto &RetReq = Req->getReturnTypeRequirement();
12586 if (RetReq.isEmpty())
12587 TransRetReq.emplace();
12588 else if (RetReq.isSubstitutionFailure())
12589 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
12590 else if (RetReq.isTypeConstraint()) {
12591 TemplateParameterList *OrigTPL =
12592 RetReq.getTypeConstraintTemplateParameterList();
12593 TemplateParameterList *TPL =
12594 getDerived().TransformTemplateParameterList(OrigTPL);
12595 if (!TPL)
12596 return nullptr;
12597 TransRetReq.emplace(TPL);
12598 }
12599 assert(TransRetReq.hasValue() &&(static_cast <bool> (TransRetReq.hasValue() && "All code paths leading here must set TransRetReq"
) ? void (0) : __assert_fail ("TransRetReq.hasValue() && \"All code paths leading here must set TransRetReq\""
, "clang/lib/Sema/TreeTransform.h", 12600, __extension__ __PRETTY_FUNCTION__
))
12600 "All code paths leading here must set TransRetReq")(static_cast <bool> (TransRetReq.hasValue() && "All code paths leading here must set TransRetReq"
) ? void (0) : __assert_fail ("TransRetReq.hasValue() && \"All code paths leading here must set TransRetReq\""
, "clang/lib/Sema/TreeTransform.h", 12600, __extension__ __PRETTY_FUNCTION__
))
;
12601 if (Expr *E = TransExpr.dyn_cast<Expr *>())
12602 return getDerived().RebuildExprRequirement(E, Req->isSimple(),
12603 Req->getNoexceptLoc(),
12604 std::move(*TransRetReq));
12605 return getDerived().RebuildExprRequirement(
12606 TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
12607 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
12608}
12609
12610template<typename Derived>
12611concepts::NestedRequirement *
12612TreeTransform<Derived>::TransformNestedRequirement(
12613 concepts::NestedRequirement *Req) {
12614 if (Req->isSubstitutionFailure()) {
12615 if (getDerived().AlwaysRebuild())
12616 return getDerived().RebuildNestedRequirement(
12617 Req->getSubstitutionDiagnostic());
12618 return Req;
12619 }
12620 ExprResult TransConstraint =
12621 getDerived().TransformExpr(Req->getConstraintExpr());
12622 if (TransConstraint.isInvalid())
12623 return nullptr;
12624 return getDerived().RebuildNestedRequirement(TransConstraint.get());
12625}
12626
12627template<typename Derived>
12628ExprResult
12629TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
12630 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
12631 if (!T)
12632 return ExprError();
12633
12634 if (!getDerived().AlwaysRebuild() &&
12635 T == E->getQueriedTypeSourceInfo())
12636 return E;
12637
12638 ExprResult SubExpr;
12639 {
12640 EnterExpressionEvaluationContext Unevaluated(
12641 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12642 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
12643 if (SubExpr.isInvalid())
12644 return ExprError();
12645
12646 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
12647 return E;
12648 }
12649
12650 return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
12651 SubExpr.get(), E->getEndLoc());
12652}
12653
12654template<typename Derived>
12655ExprResult
12656TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
12657 ExprResult SubExpr;
12658 {
12659 EnterExpressionEvaluationContext Unevaluated(
12660 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12661 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
12662 if (SubExpr.isInvalid())
12663 return ExprError();
12664
12665 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
12666 return E;
12667 }
12668
12669 return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
12670 SubExpr.get(), E->getEndLoc());
12671}
12672
12673template <typename Derived>
12674ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
12675 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
12676 TypeSourceInfo **RecoveryTSI) {
12677 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
12678 DRE, AddrTaken, RecoveryTSI);
12679
12680 // Propagate both errors and recovered types, which return ExprEmpty.
12681 if (!NewDRE.isUsable())
12682 return NewDRE;
12683
12684 // We got an expr, wrap it up in parens.
12685 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
12686 return PE;
12687 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
12688 PE->getRParen());
12689}
12690
12691template <typename Derived>
12692ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12693 DependentScopeDeclRefExpr *E) {
12694 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
12695 nullptr);
12696}
12697
12698template <typename Derived>
12699ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12700 DependentScopeDeclRefExpr *E, bool IsAddressOfOperand,
12701 TypeSourceInfo **RecoveryTSI) {
12702 assert(E->getQualifierLoc())(static_cast <bool> (E->getQualifierLoc()) ? void (0
) : __assert_fail ("E->getQualifierLoc()", "clang/lib/Sema/TreeTransform.h"
, 12702, __extension__ __PRETTY_FUNCTION__))
;
12703 NestedNameSpecifierLoc QualifierLoc =
12704 getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
12705 if (!QualifierLoc)
12706 return ExprError();
12707 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
12708
12709 // TODO: If this is a conversion-function-id, verify that the
12710 // destination type name (if present) resolves the same way after
12711 // instantiation as it did in the local scope.
12712
12713 DeclarationNameInfo NameInfo =
12714 getDerived().TransformDeclarationNameInfo(E->getNameInfo());
12715 if (!NameInfo.getName())
12716 return ExprError();
12717
12718 if (!E->hasExplicitTemplateArgs()) {
12719 if (!getDerived().AlwaysRebuild() && QualifierLoc == E->getQualifierLoc() &&
12720 // Note: it is sufficient to compare the Name component of NameInfo:
12721 // if name has not changed, DNLoc has not changed either.
12722 NameInfo.getName() == E->getDeclName())
12723 return E;
12724
12725 return getDerived().RebuildDependentScopeDeclRefExpr(
12726 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
12727 IsAddressOfOperand, RecoveryTSI);
12728 }
12729
12730 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
12731 if (getDerived().TransformTemplateArguments(
12732 E->getTemplateArgs(), E->getNumTemplateArgs(), TransArgs))
12733 return ExprError();
12734
12735 return getDerived().RebuildDependentScopeDeclRefExpr(
12736 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
12737 RecoveryTSI);
12738}
12739
12740template<typename Derived>
12741ExprResult
12742TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
12743 // CXXConstructExprs other than for list-initialization and
12744 // CXXTemporaryObjectExpr are always implicit, so when we have
12745 // a 1-argument construction we just transform that argument.
12746 if (getDerived().AllowSkippingCXXConstructExpr() &&
12747 ((E->getNumArgs() == 1 ||
12748 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
12749 (!getDerived().DropCallArgument(E->getArg(0))) &&
12750 !E->isListInitialization()))
12751 return getDerived().TransformInitializer(E->getArg(0),
12752 /*DirectInit*/ false);
12753
12754 TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
12755
12756 QualType T = getDerived().TransformType(E->getType());
12757 if (T.isNull())
12758 return ExprError();
12759
12760 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12761 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12762 if (!Constructor)
12763 return ExprError();
12764
12765 bool ArgumentChanged = false;
12766 SmallVector<Expr*, 8> Args;
12767 {
12768 EnterExpressionEvaluationContext Context(
12769 getSema(), EnterExpressionEvaluationContext::InitList,
12770 E->isListInitialization());
12771 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12772 &ArgumentChanged))
12773 return ExprError();
12774 }
12775
12776 if (!getDerived().AlwaysRebuild() &&
12777 T == E->getType() &&
12778 Constructor == E->getConstructor() &&
12779 !ArgumentChanged) {
12780 // Mark the constructor as referenced.
12781 // FIXME: Instantiation-specific
12782 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12783 return E;
12784 }
12785
12786 return getDerived().RebuildCXXConstructExpr(
12787 T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
12788 E->hadMultipleCandidates(), E->isListInitialization(),
12789 E->isStdInitListInitialization(), E->requiresZeroInitialization(),
12790 E->getConstructionKind(), E->getParenOrBraceRange());
12791}
12792
12793template<typename Derived>
12794ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
12795 CXXInheritedCtorInitExpr *E) {
12796 QualType T = getDerived().TransformType(E->getType());
12797 if (T.isNull())
12798 return ExprError();
12799
12800 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12801 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12802 if (!Constructor)
12803 return ExprError();
12804
12805 if (!getDerived().AlwaysRebuild() &&
12806 T == E->getType() &&
12807 Constructor == E->getConstructor()) {
12808 // Mark the constructor as referenced.
12809 // FIXME: Instantiation-specific
12810 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12811 return E;
12812 }
12813
12814 return getDerived().RebuildCXXInheritedCtorInitExpr(
12815 T, E->getLocation(), Constructor,
12816 E->constructsVBase(), E->inheritedFromVBase());
12817}
12818
12819/// Transform a C++ temporary-binding expression.
12820///
12821/// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
12822/// transform the subexpression and return that.
12823template<typename Derived>
12824ExprResult
12825TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12826 if (auto *Dtor = E->getTemporary()->getDestructor())
12827 SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
12828 const_cast<CXXDestructorDecl *>(Dtor));
12829 return getDerived().TransformExpr(E->getSubExpr());
12830}
12831
12832/// Transform a C++ expression that contains cleanups that should
12833/// be run after the expression is evaluated.
12834///
12835/// Since ExprWithCleanups nodes are implicitly generated, we
12836/// just transform the subexpression and return that.
12837template<typename Derived>
12838ExprResult
12839TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
12840 return getDerived().TransformExpr(E->getSubExpr());
12841}
12842
12843template<typename Derived>
12844ExprResult
12845TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
12846 CXXTemporaryObjectExpr *E) {
12847 TypeSourceInfo *T =
12848 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
12849 if (!T)
12850 return ExprError();
12851
12852 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12853 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12854 if (!Constructor)
12855 return ExprError();
12856
12857 bool ArgumentChanged = false;
12858 SmallVector<Expr*, 8> Args;
12859 Args.reserve(E->getNumArgs());
12860 {
12861 EnterExpressionEvaluationContext Context(
12862 getSema(), EnterExpressionEvaluationContext::InitList,
12863 E->isListInitialization());
12864 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12865 &ArgumentChanged))
12866 return ExprError();
12867 }
12868
12869 if (!getDerived().AlwaysRebuild() &&
12870 T == E->getTypeSourceInfo() &&
12871 Constructor == E->getConstructor() &&
12872 !ArgumentChanged) {
12873 // FIXME: Instantiation-specific
12874 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12875 return SemaRef.MaybeBindToTemporary(E);
12876 }
12877
12878 // FIXME: We should just pass E->isListInitialization(), but we're not
12879 // prepared to handle list-initialization without a child InitListExpr.
12880 SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
12881 return getDerived().RebuildCXXTemporaryObjectExpr(
12882 T, LParenLoc, Args, E->getEndLoc(),
12883 /*ListInitialization=*/LParenLoc.isInvalid());
12884}
12885
12886template<typename Derived>
12887ExprResult
12888TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
12889 // Transform any init-capture expressions before entering the scope of the
12890 // lambda body, because they are not semantically within that scope.
12891 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
12892 struct TransformedInitCapture {
12893 // The location of the ... if the result is retaining a pack expansion.
12894 SourceLocation EllipsisLoc;
12895 // Zero or more expansions of the init-capture.
12896 SmallVector<InitCaptureInfoTy, 4> Expansions;
12897 };
12898 SmallVector<TransformedInitCapture, 4> InitCaptures;
12899 InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
12900 for (LambdaExpr::capture_iterator C = E->capture_begin(),
12901 CEnd = E->capture_end();
12902 C != CEnd; ++C) {
12903 if (!E->isInitCapture(C))
12904 continue;
12905
12906 TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
12907 VarDecl *OldVD = C->getCapturedVar();
12908
12909 auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
12910 Optional<unsigned> NumExpansions) {
12911 ExprResult NewExprInitResult = getDerived().TransformInitializer(
12912 OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
12913
12914 if (NewExprInitResult.isInvalid()) {
12915 Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
12916 return;
12917 }
12918 Expr *NewExprInit = NewExprInitResult.get();
12919
12920 QualType NewInitCaptureType =
12921 getSema().buildLambdaInitCaptureInitialization(
12922 C->getLocation(), OldVD->getType()->isReferenceType(),
12923 EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
12924 C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
12925 NewExprInit);
12926 Result.Expansions.push_back(
12927 InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
12928 };
12929
12930 // If this is an init-capture pack, consider expanding the pack now.
12931 if (OldVD->isParameterPack()) {
12932 PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
12933 ->getTypeLoc()
12934 .castAs<PackExpansionTypeLoc>();
12935 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12936 SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
12937
12938 // Determine whether the set of unexpanded parameter packs can and should
12939 // be expanded.
12940 bool Expand = true;
12941 bool RetainExpansion = false;
12942 Optional<unsigned> OrigNumExpansions =
12943 ExpansionTL.getTypePtr()->getNumExpansions();
12944 Optional<unsigned> NumExpansions = OrigNumExpansions;
12945 if (getDerived().TryExpandParameterPacks(
12946 ExpansionTL.getEllipsisLoc(),
12947 OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
12948 RetainExpansion, NumExpansions))
12949 return ExprError();
12950 if (Expand) {
12951 for (unsigned I = 0; I != *NumExpansions; ++I) {
12952 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12953 SubstInitCapture(SourceLocation(), None);
12954 }
12955 }
12956 if (!Expand || RetainExpansion) {
12957 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12958 SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
12959 Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
12960 }
12961 } else {
12962 SubstInitCapture(SourceLocation(), None);
12963 }
12964 }
12965
12966 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
12967 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
12968
12969 // Transform the template parameters, and add them to the current
12970 // instantiation scope. The null case is handled correctly.
12971 auto TPL = getDerived().TransformTemplateParameterList(
12972 E->getTemplateParameterList());
12973 LSI->GLTemplateParameterList = TPL;
12974
12975 // Transform the type of the original lambda's call operator.
12976 // The transformation MUST be done in the CurrentInstantiationScope since
12977 // it introduces a mapping of the original to the newly created
12978 // transformed parameters.
12979 TypeSourceInfo *NewCallOpTSI = nullptr;
12980 {
12981 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
12982 FunctionProtoTypeLoc OldCallOpFPTL =
12983 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
12984
12985 TypeLocBuilder NewCallOpTLBuilder;
12986 SmallVector<QualType, 4> ExceptionStorage;
12987 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
12988 QualType NewCallOpType = TransformFunctionProtoType(
12989 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
12990 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
12991 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
12992 ExceptionStorage, Changed);
12993 });
12994 if (NewCallOpType.isNull())
12995 return ExprError();
12996 NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
12997 NewCallOpType);
12998 }
12999
13000 // Transform the trailing requires clause
13001 ExprResult NewTrailingRequiresClause;
13002 if (Expr *TRC = E->getCallOperator()->getTrailingRequiresClause())
13003 // FIXME: Concepts: Substitution into requires clause should only happen
13004 // when checking satisfaction.
13005 NewTrailingRequiresClause = getDerived().TransformExpr(TRC);
13006
13007 // Create the local class that will describe the lambda.
13008
13009 // FIXME: DependencyKind below is wrong when substituting inside a templated
13010 // context that isn't a DeclContext (such as a variable template), or when
13011 // substituting an unevaluated lambda inside of a function's parameter's type
13012 // - as parameter types are not instantiated from within a function's DC. We
13013 // use isUnevaluatedContext() to distinguish the function parameter case.
13014 CXXRecordDecl::LambdaDependencyKind DependencyKind =
13015 CXXRecordDecl::LDK_Unknown;
13016 if (getSema().isUnevaluatedContext() &&
13017 (getSema().CurContext->isFileContext() ||
13018 !getSema().CurContext->getParent()->isDependentContext()))
13019 DependencyKind = CXXRecordDecl::LDK_NeverDependent;
13020
13021 CXXRecordDecl *OldClass = E->getLambdaClass();
13022 CXXRecordDecl *Class =
13023 getSema().createLambdaClosureType(E->getIntroducerRange(), NewCallOpTSI,
13024 DependencyKind, E->getCaptureDefault());
13025
13026 getDerived().transformedLocalDecl(OldClass, {Class});
13027
13028 Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling;
13029 if (getDerived().ReplacingOriginal())
13030 Mangling = std::make_tuple(OldClass->hasKnownLambdaInternalLinkage(),
13031 OldClass->getLambdaManglingNumber(),
13032 OldClass->getDeviceLambdaManglingNumber(),
13033 OldClass->getLambdaContextDecl());
13034
13035 // Build the call operator.
13036 CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
13037 Class, E->getIntroducerRange(), NewCallOpTSI,
13038 E->getCallOperator()->getEndLoc(),
13039 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
13040 E->getCallOperator()->getConstexprKind(),
13041 NewTrailingRequiresClause.get());
13042
13043 LSI->CallOperator = NewCallOperator;
13044
13045 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
13046 getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
13047
13048 // Number the lambda for linkage purposes if necessary.
13049 getSema().handleLambdaNumbering(Class, NewCallOperator, Mangling);
13050
13051 // Introduce the context of the call operator.
13052 Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
13053 /*NewThisContext*/false);
13054
13055 // Enter the scope of the lambda.
13056 getSema().buildLambdaScope(LSI, NewCallOperator,
13057 E->getIntroducerRange(),
13058 E->getCaptureDefault(),
13059 E->getCaptureDefaultLoc(),
13060 E->hasExplicitParameters(),
13061 E->hasExplicitResultType(),
13062 E->isMutable());
13063
13064 bool Invalid = false;
13065
13066 // Transform captures.
13067 for (LambdaExpr::capture_iterator C = E->capture_begin(),
13068 CEnd = E->capture_end();
13069 C != CEnd; ++C) {
13070 // When we hit the first implicit capture, tell Sema that we've finished
13071 // the list of explicit captures.
13072 if (C->isImplicit())
13073 break;
13074
13075 // Capturing 'this' is trivial.
13076 if (C->capturesThis()) {
13077 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13078 /*BuildAndDiagnose*/ true, nullptr,
13079 C->getCaptureKind() == LCK_StarThis);
13080 continue;
13081 }
13082 // Captured expression will be recaptured during captured variables
13083 // rebuilding.
13084 if (C->capturesVLAType())
13085 continue;
13086
13087 // Rebuild init-captures, including the implied field declaration.
13088 if (E->isInitCapture(C)) {
13089 TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
13090
13091 VarDecl *OldVD = C->getCapturedVar();
13092 llvm::SmallVector<Decl*, 4> NewVDs;
13093
13094 for (InitCaptureInfoTy &Info : NewC.Expansions) {
13095 ExprResult Init = Info.first;
13096 QualType InitQualType = Info.second;
13097 if (Init.isInvalid() || InitQualType.isNull()) {
13098 Invalid = true;
13099 break;
13100 }
13101 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
13102 OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
13103 OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get(),
13104 getSema().CurContext);
13105 if (!NewVD) {
13106 Invalid = true;
13107 break;
13108 }
13109 NewVDs.push_back(NewVD);
13110 getSema().addInitCapture(LSI, NewVD);
13111 }
13112
13113 if (Invalid)
13114 break;
13115
13116 getDerived().transformedLocalDecl(OldVD, NewVDs);
13117 continue;
13118 }
13119
13120 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", 13120, __extension__ __PRETTY_FUNCTION__
))
;
13121
13122 // Determine the capture kind for Sema.
13123 Sema::TryCaptureKind Kind
13124 = C->isImplicit()? Sema::TryCapture_Implicit
13125 : C->getCaptureKind() == LCK_ByCopy
13126 ? Sema::TryCapture_ExplicitByVal
13127 : Sema::TryCapture_ExplicitByRef;
13128 SourceLocation EllipsisLoc;
13129 if (C->isPackExpansion()) {
13130 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
13131 bool ShouldExpand = false;
13132 bool RetainExpansion = false;
13133 Optional<unsigned> NumExpansions;
13134 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
13135 C->getLocation(),
13136 Unexpanded,
13137 ShouldExpand, RetainExpansion,
13138 NumExpansions)) {
13139 Invalid = true;
13140 continue;
13141 }
13142
13143 if (ShouldExpand) {
13144 // The transform has determined that we should perform an expansion;
13145 // transform and capture each of the arguments.
13146 // expansion of the pattern. Do so.
13147 VarDecl *Pack = C->getCapturedVar();
13148 for (unsigned I = 0; I != *NumExpansions; ++I) {
13149 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13150 VarDecl *CapturedVar
13151 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
13152 Pack));
13153 if (!CapturedVar) {
13154 Invalid = true;
13155 continue;
13156 }
13157
13158 // Capture the transformed variable.
13159 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
13160 }
13161
13162 // FIXME: Retain a pack expansion if RetainExpansion is true.
13163
13164 continue;
13165 }
13166
13167 EllipsisLoc = C->getEllipsisLoc();
13168 }
13169
13170 // Transform the captured variable.
13171 VarDecl *CapturedVar
13172 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
13173 C->getCapturedVar()));
13174 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
13175 Invalid = true;
13176 continue;
13177 }
13178
13179 // Capture the transformed variable.
13180 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
13181 EllipsisLoc);
13182 }
13183 getSema().finishLambdaExplicitCaptures(LSI);
13184
13185 // FIXME: Sema's lambda-building mechanism expects us to push an expression
13186 // evaluation context even if we're not transforming the function body.
13187 getSema().PushExpressionEvaluationContext(
13188 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13189
13190 // Instantiate the body of the lambda expression.
13191 StmtResult Body =
13192 Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
13193
13194 // ActOnLambda* will pop the function scope for us.
13195 FuncScopeCleanup.disable();
13196
13197 if (Body.isInvalid()) {
13198 SavedContext.pop();
13199 getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
13200 /*IsInstantiation=*/true);
13201 return ExprError();
13202 }
13203
13204 // Copy the LSI before ActOnFinishFunctionBody removes it.
13205 // FIXME: This is dumb. Store the lambda information somewhere that outlives
13206 // the call operator.
13207 auto LSICopy = *LSI;
13208 getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
13209 /*IsInstantiation*/ true);
13210 SavedContext.pop();
13211
13212 return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
13213 &LSICopy);
13214}
13215
13216template<typename Derived>
13217StmtResult
13218TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
13219 return TransformStmt(S);
13220}
13221
13222template<typename Derived>
13223StmtResult
13224TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
13225 // Transform captures.
13226 for (LambdaExpr::capture_iterator C = E->capture_begin(),
13227 CEnd = E->capture_end();
13228 C != CEnd; ++C) {
13229 // When we hit the first implicit capture, tell Sema that we've finished
13230 // the list of explicit captures.
13231 if (!C->isImplicit())
13232 continue;
13233
13234 // Capturing 'this' is trivial.
13235 if (C->capturesThis()) {
13236 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13237 /*BuildAndDiagnose*/ true, nullptr,
13238 C->getCaptureKind() == LCK_StarThis);
13239 continue;
13240 }
13241 // Captured expression will be recaptured during captured variables
13242 // rebuilding.
13243 if (C->capturesVLAType())
13244 continue;
13245
13246 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", 13246, __extension__ __PRETTY_FUNCTION__
))
;
13247 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", 13247, __extension__ __PRETTY_FUNCTION__
))
;
13248
13249 // Transform the captured variable.
13250 VarDecl *CapturedVar = cast_or_null<VarDecl>(
13251 getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13252 if (!CapturedVar || CapturedVar->isInvalidDecl())
13253 return StmtError();
13254
13255 // Capture the transformed variable.
13256 getSema().tryCaptureVariable(CapturedVar, C->getLocation());
13257 }
13258
13259 return S;
13260}
13261
13262template<typename Derived>
13263ExprResult
13264TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
13265 CXXUnresolvedConstructExpr *E) {
13266 TypeSourceInfo *T =
13267 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13268 if (!T)
13269 return ExprError();
13270
13271 bool ArgumentChanged = false;
13272 SmallVector<Expr*, 8> Args;
13273 Args.reserve(E->getNumArgs());
13274 {
13275 EnterExpressionEvaluationContext Context(
13276 getSema(), EnterExpressionEvaluationContext::InitList,
13277 E->isListInitialization());
13278 if (getDerived().TransformExprs(E->arg_begin(), E->getNumArgs(), true, Args,
13279 &ArgumentChanged))
13280 return ExprError();
13281 }
13282
13283 if (!getDerived().AlwaysRebuild() &&
13284 T == E->getTypeSourceInfo() &&
13285 !ArgumentChanged)
13286 return E;
13287
13288 // FIXME: we're faking the locations of the commas
13289 return getDerived().RebuildCXXUnresolvedConstructExpr(
13290 T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
13291}
13292
13293template<typename Derived>
13294ExprResult
13295TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
13296 CXXDependentScopeMemberExpr *E) {
13297 // Transform the base of the expression.
13298 ExprResult Base((Expr*) nullptr);
13299 Expr *OldBase;
13300 QualType BaseType;
13301 QualType ObjectType;
13302 if (!E->isImplicitAccess()) {
13303 OldBase = E->getBase();
13304 Base = getDerived().TransformExpr(OldBase);
13305 if (Base.isInvalid())
13306 return ExprError();
13307
13308 // Start the member reference and compute the object's type.
13309 ParsedType ObjectTy;
13310 bool MayBePseudoDestructor = false;
13311 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
13312 E->getOperatorLoc(),
13313 E->isArrow()? tok::arrow : tok::period,
13314 ObjectTy,
13315 MayBePseudoDestructor);
13316 if (Base.isInvalid())
13317 return ExprError();
13318
13319 ObjectType = ObjectTy.get();
13320 BaseType = ((Expr*) Base.get())->getType();
13321 } else {
13322 OldBase = nullptr;
13323 BaseType = getDerived().TransformType(E->getBaseType());
13324 ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
13325 }
13326
13327 // Transform the first part of the nested-name-specifier that qualifies
13328 // the member name.
13329 NamedDecl *FirstQualifierInScope
13330 = getDerived().TransformFirstQualifierInScope(
13331 E->getFirstQualifierFoundInScope(),
13332 E->getQualifierLoc().getBeginLoc());
13333
13334 NestedNameSpecifierLoc QualifierLoc;
13335 if (E->getQualifier()) {
13336 QualifierLoc
13337 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
13338 ObjectType,
13339 FirstQualifierInScope);
13340 if (!QualifierLoc)
13341 return ExprError();
13342 }
13343
13344 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13345
13346 // TODO: If this is a conversion-function-id, verify that the
13347 // destination type name (if present) resolves the same way after
13348 // instantiation as it did in the local scope.
13349
13350 DeclarationNameInfo NameInfo
13351 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
13352 if (!NameInfo.getName())
13353 return ExprError();
13354
13355 if (!E->hasExplicitTemplateArgs()) {
13356 // This is a reference to a member without an explicitly-specified
13357 // template argument list. Optimize for this common case.
13358 if (!getDerived().AlwaysRebuild() &&
13359 Base.get() == OldBase &&
13360 BaseType == E->getBaseType() &&
13361 QualifierLoc == E->getQualifierLoc() &&
13362 NameInfo.getName() == E->getMember() &&
13363 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
13364 return E;
13365
13366 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13367 BaseType,
13368 E->isArrow(),
13369 E->getOperatorLoc(),
13370 QualifierLoc,
13371 TemplateKWLoc,
13372 FirstQualifierInScope,
13373 NameInfo,
13374 /*TemplateArgs*/nullptr);
13375 }
13376
13377 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13378 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
13379 E->getNumTemplateArgs(),
13380 TransArgs))
13381 return ExprError();
13382
13383 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13384 BaseType,
13385 E->isArrow(),
13386 E->getOperatorLoc(),
13387 QualifierLoc,
13388 TemplateKWLoc,
13389 FirstQualifierInScope,
13390 NameInfo,
13391 &TransArgs);
13392}
13393
13394template <typename Derived>
13395ExprResult TreeTransform<Derived>::TransformUnresolvedMemberExpr(
13396 UnresolvedMemberExpr *Old) {
13397 // Transform the base of the expression.
13398 ExprResult Base((Expr *)nullptr);
13399 QualType BaseType;
13400 if (!Old->isImplicitAccess()) {
13401 Base = getDerived().TransformExpr(Old->getBase());
13402 if (Base.isInvalid())
13403 return ExprError();
13404 Base =
13405 getSema().PerformMemberExprBaseConversion(Base.get(), Old->isArrow());
13406 if (Base.isInvalid())
13407 return ExprError();
13408 BaseType = Base.get()->getType();
13409 } else {
13410 BaseType = getDerived().TransformType(Old->getBaseType());
13411 }
13412
13413 NestedNameSpecifierLoc QualifierLoc;
13414 if (Old->getQualifierLoc()) {
13415 QualifierLoc =
13416 getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
13417 if (!QualifierLoc)
13418 return ExprError();
13419 }
13420
13421 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
13422
13423 LookupResult R(SemaRef, Old->getMemberNameInfo(), Sema::LookupOrdinaryName);
13424
13425 // Transform the declaration set.
13426 if (TransformOverloadExprDecls(Old, /*RequiresADL*/ false, R))
13427 return ExprError();
13428
13429 // Determine the naming class.
13430 if (Old->getNamingClass()) {
13431 CXXRecordDecl *NamingClass = cast_or_null<CXXRecordDecl>(
13432 getDerived().TransformDecl(Old->getMemberLoc(), Old->getNamingClass()));
13433 if (!NamingClass)
13434 return ExprError();
13435
13436 R.setNamingClass(NamingClass);
13437 }
13438
13439 TemplateArgumentListInfo TransArgs;
13440 if (Old->hasExplicitTemplateArgs()) {
13441 TransArgs.setLAngleLoc(Old->getLAngleLoc());
13442 TransArgs.setRAngleLoc(Old->getRAngleLoc());
13443 if (getDerived().TransformTemplateArguments(
13444 Old->getTemplateArgs(), Old->getNumTemplateArgs(), TransArgs))
13445 return ExprError();
13446 }
13447
13448 // FIXME: to do this check properly, we will need to preserve the
13449 // first-qualifier-in-scope here, just in case we had a dependent
13450 // base (and therefore couldn't do the check) and a
13451 // nested-name-qualifier (and therefore could do the lookup).
13452 NamedDecl *FirstQualifierInScope = nullptr;
13453
13454 return getDerived().RebuildUnresolvedMemberExpr(
13455 Base.get(), BaseType, Old->getOperatorLoc(), Old->isArrow(), QualifierLoc,
13456 TemplateKWLoc, FirstQualifierInScope, R,
13457 (Old->hasExplicitTemplateArgs() ? &TransArgs : nullptr));
13458}
13459
13460template<typename Derived>
13461ExprResult
13462TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
13463 EnterExpressionEvaluationContext Unevaluated(
13464 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13465 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
13466 if (SubExpr.isInvalid())
13467 return ExprError();
13468
13469 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
13470 return E;
13471
13472 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
13473}
13474
13475template<typename Derived>
13476ExprResult
13477TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
13478 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
13479 if (Pattern.isInvalid())
13480 return ExprError();
13481
13482 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
13483 return E;
13484
13485 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
13486 E->getNumExpansions());
13487}
13488
13489template<typename Derived>
13490ExprResult
13491TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
13492 // If E is not value-dependent, then nothing will change when we transform it.
13493 // Note: This is an instantiation-centric view.
13494 if (!E->isValueDependent())
13495 return E;
13496
13497 EnterExpressionEvaluationContext Unevaluated(
13498 getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
13499
13500 ArrayRef<TemplateArgument> PackArgs;
13501 TemplateArgument ArgStorage;
13502
13503 // Find the argument list to transform.
13504 if (E->isPartiallySubstituted()) {
13505 PackArgs = E->getPartialArguments();
13506 } else if (E->isValueDependent()) {
13507 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
13508 bool ShouldExpand = false;
13509 bool RetainExpansion = false;
13510 Optional<unsigned> NumExpansions;
13511 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
13512 Unexpanded,
13513 ShouldExpand, RetainExpansion,
13514 NumExpansions))
13515 return ExprError();
13516
13517 // If we need to expand the pack, build a template argument from it and
13518 // expand that.
13519 if (ShouldExpand) {
13520 auto *Pack = E->getPack();
13521 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
13522 ArgStorage = getSema().Context.getPackExpansionType(
13523 getSema().Context.getTypeDeclType(TTPD), None);
13524 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
13525 ArgStorage = TemplateArgument(TemplateName(TTPD), None);
13526 } else {
13527 auto *VD = cast<ValueDecl>(Pack);
13528 ExprResult DRE = getSema().BuildDeclRefExpr(
13529 VD, VD->getType().getNonLValueExprType(getSema().Context),
13530 VD->getType()->isReferenceType() ? VK_LValue : VK_PRValue,
13531 E->getPackLoc());
13532 if (DRE.isInvalid())
13533 return ExprError();
13534 ArgStorage = new (getSema().Context) PackExpansionExpr(
13535 getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
13536 }
13537 PackArgs = ArgStorage;
13538 }
13539 }
13540
13541 // If we're not expanding the pack, just transform the decl.
13542 if (!PackArgs.size()) {
13543 auto *Pack = cast_or_null<NamedDecl>(
13544 getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
13545 if (!Pack)
13546 return ExprError();
13547 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
13548 E->getPackLoc(),
13549 E->getRParenLoc(), None, None);
13550 }
13551
13552 // Try to compute the result without performing a partial substitution.
13553 Optional<unsigned> Result = 0;
13554 for (const TemplateArgument &Arg : PackArgs) {
13555 if (!Arg.isPackExpansion()) {
13556 Result = *Result + 1;
13557 continue;
13558 }
13559
13560 TemplateArgumentLoc ArgLoc;
13561 InventTemplateArgumentLoc(Arg, ArgLoc);
13562
13563 // Find the pattern of the pack expansion.
13564 SourceLocation Ellipsis;
13565 Optional<unsigned> OrigNumExpansions;
13566 TemplateArgumentLoc Pattern =
13567 getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
13568 OrigNumExpansions);
13569
13570 // Substitute under the pack expansion. Do not expand the pack (yet).
13571 TemplateArgumentLoc OutPattern;
13572 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13573 if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
13574 /*Uneval*/ true))
13575 return true;
13576
13577 // See if we can determine the number of arguments from the result.
13578 Optional<unsigned> NumExpansions =
13579 getSema().getFullyPackExpandedSize(OutPattern.getArgument());
13580 if (!NumExpansions) {
13581 // No: we must be in an alias template expansion, and we're going to need
13582 // to actually expand the packs.
13583 Result = None;
13584 break;
13585 }
13586
13587 Result = *Result + *NumExpansions;
13588 }
13589
13590 // Common case: we could determine the number of expansions without
13591 // substituting.
13592 if (Result)
13593 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13594 E->getPackLoc(),
13595 E->getRParenLoc(), *Result, None);
13596
13597 TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
13598 E->getPackLoc());
13599 {
13600 TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
13601 typedef TemplateArgumentLocInventIterator<
13602 Derived, const TemplateArgument*> PackLocIterator;
13603 if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
13604 PackLocIterator(*this, PackArgs.end()),
13605 TransformedPackArgs, /*Uneval*/true))
13606 return ExprError();
13607 }
13608
13609 // Check whether we managed to fully-expand the pack.
13610 // FIXME: Is it possible for us to do so and not hit the early exit path?
13611 SmallVector<TemplateArgument, 8> Args;
13612 bool PartialSubstitution = false;
13613 for (auto &Loc : TransformedPackArgs.arguments()) {
13614 Args.push_back(Loc.getArgument());
13615 if (Loc.getArgument().isPackExpansion())
13616 PartialSubstitution = true;
13617 }
13618
13619 if (PartialSubstitution)
13620 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13621 E->getPackLoc(),
13622 E->getRParenLoc(), None, Args);
13623
13624 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13625 E->getPackLoc(), E->getRParenLoc(),
13626 Args.size(), None);
13627}
13628
13629template<typename Derived>
13630ExprResult
13631TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
13632 SubstNonTypeTemplateParmPackExpr *E) {
13633 // Default behavior is to do nothing with this transformation.
13634 return E;
13635}
13636
13637template<typename Derived>
13638ExprResult
13639TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
13640 SubstNonTypeTemplateParmExpr *E) {
13641 // Default behavior is to do nothing with this transformation.
13642 return E;
13643}
13644
13645template<typename Derived>
13646ExprResult
13647TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
13648 // Default behavior is to do nothing with this transformation.
13649 return E;
13650}
13651
13652template<typename Derived>
13653ExprResult
13654TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
13655 MaterializeTemporaryExpr *E) {
13656 return getDerived().TransformExpr(E->getSubExpr());
13657}
13658
13659template<typename Derived>
13660ExprResult
13661TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
13662 UnresolvedLookupExpr *Callee = nullptr;
13663 if (Expr *OldCallee = E->getCallee()) {
13664 ExprResult CalleeResult = getDerived().TransformExpr(OldCallee);
13665 if (CalleeResult.isInvalid())
13666 return ExprError();
13667 Callee = cast<UnresolvedLookupExpr>(CalleeResult.get());
13668 }
13669
13670 Expr *Pattern = E->getPattern();
13671
13672 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13673 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
13674 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", 13674, __extension__ __PRETTY_FUNCTION__
))
;
13675
13676 // Determine whether the set of unexpanded parameter packs can and should
13677 // be expanded.
13678 bool Expand = true;
13679 bool RetainExpansion = false;
13680 Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
13681 NumExpansions = OrigNumExpansions;
13682 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
13683 Pattern->getSourceRange(),
13684 Unexpanded,
13685 Expand, RetainExpansion,
13686 NumExpansions))
13687 return true;
13688
13689 if (!Expand) {
13690 // Do not expand any packs here, just transform and rebuild a fold
13691 // expression.
13692 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13693
13694 ExprResult LHS =
13695 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
13696 if (LHS.isInvalid())
13697 return true;
13698
13699 ExprResult RHS =
13700 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
13701 if (RHS.isInvalid())
13702 return true;
13703
13704 if (!getDerived().AlwaysRebuild() &&
13705 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
13706 return E;
13707
13708 return getDerived().RebuildCXXFoldExpr(
13709 Callee, E->getBeginLoc(), LHS.get(), E->getOperator(),
13710 E->getEllipsisLoc(), RHS.get(), E->getEndLoc(), NumExpansions);
13711 }
13712
13713 // Formally a fold expression expands to nested parenthesized expressions.
13714 // Enforce this limit to avoid creating trees so deep we can't safely traverse
13715 // them.
13716 if (NumExpansions && SemaRef.getLangOpts().BracketDepth < NumExpansions) {
13717 SemaRef.Diag(E->getEllipsisLoc(),
13718 clang::diag::err_fold_expression_limit_exceeded)
13719 << *NumExpansions << SemaRef.getLangOpts().BracketDepth
13720 << E->getSourceRange();
13721 SemaRef.Diag(E->getEllipsisLoc(), diag::note_bracket_depth);
13722 return ExprError();
13723 }
13724
13725 // The transform has determined that we should perform an elementwise
13726 // expansion of the pattern. Do so.
13727 ExprResult Result = getDerived().TransformExpr(E->getInit());
13728 if (Result.isInvalid())
13729 return true;
13730 bool LeftFold = E->isLeftFold();
13731
13732 // If we're retaining an expansion for a right fold, it is the innermost
13733 // component and takes the init (if any).
13734 if (!LeftFold && RetainExpansion) {
13735 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13736
13737 ExprResult Out = getDerived().TransformExpr(Pattern);
13738 if (Out.isInvalid())
13739 return true;
13740
13741 Result = getDerived().RebuildCXXFoldExpr(
13742 Callee, E->getBeginLoc(), Out.get(), E->getOperator(),
13743 E->getEllipsisLoc(), Result.get(), E->getEndLoc(), OrigNumExpansions);
13744 if (Result.isInvalid())
13745 return true;
13746 }
13747
13748 for (unsigned I = 0; I != *NumExpansions; ++I) {
13749 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
13750 getSema(), LeftFold ? I : *NumExpansions - I - 1);
13751 ExprResult Out = getDerived().TransformExpr(Pattern);
13752 if (Out.isInvalid())
13753 return true;
13754
13755 if (Out.get()->containsUnexpandedParameterPack()) {
13756 // We still have a pack; retain a pack expansion for this slice.
13757 Result = getDerived().RebuildCXXFoldExpr(
13758 Callee, E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
13759 E->getOperator(), E->getEllipsisLoc(),
13760 LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
13761 OrigNumExpansions);
13762 } else if (Result.isUsable()) {
13763 // We've got down to a single element; build a binary operator.
13764 Expr *LHS = LeftFold ? Result.get() : Out.get();
13765 Expr *RHS = LeftFold ? Out.get() : Result.get();
13766 if (Callee)
13767 Result = getDerived().RebuildCXXOperatorCallExpr(
13768 BinaryOperator::getOverloadedOperator(E->getOperator()),
13769 E->getEllipsisLoc(), Callee, LHS, RHS);
13770 else
13771 Result = getDerived().RebuildBinaryOperator(E->getEllipsisLoc(),
13772 E->getOperator(), LHS, RHS);
13773 } else
13774 Result = Out;
13775
13776 if (Result.isInvalid())
13777 return true;
13778 }
13779
13780 // If we're retaining an expansion for a left fold, it is the outermost
13781 // component and takes the complete expansion so far as its init (if any).
13782 if (LeftFold && RetainExpansion) {
13783 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13784
13785 ExprResult Out = getDerived().TransformExpr(Pattern);
13786 if (Out.isInvalid())
13787 return true;
13788
13789 Result = getDerived().RebuildCXXFoldExpr(
13790 Callee, E->getBeginLoc(), Result.get(), E->getOperator(),
13791 E->getEllipsisLoc(), Out.get(), E->getEndLoc(), OrigNumExpansions);
13792 if (Result.isInvalid())
13793 return true;
13794 }
13795
13796 // If we had no init and an empty pack, and we're not retaining an expansion,
13797 // then produce a fallback value or error.
13798 if (Result.isUnset())
13799 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
13800 E->getOperator());
13801
13802 return Result;
13803}
13804
13805template<typename Derived>
13806ExprResult
13807TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
13808 CXXStdInitializerListExpr *E) {
13809 return getDerived().TransformExpr(E->getSubExpr());
13810}
13811
13812template<typename Derived>
13813ExprResult
13814TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
13815 return SemaRef.MaybeBindToTemporary(E);
13816}
13817
13818template<typename Derived>
13819ExprResult
13820TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
13821 return E;
13822}
13823
13824template<typename Derived>
13825ExprResult
13826TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
13827 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
13828 if (SubExpr.isInvalid())
13829 return ExprError();
13830
13831 if (!getDerived().AlwaysRebuild() &&
13832 SubExpr.get() == E->getSubExpr())
13833 return E;
13834
13835 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
13836}
13837
13838template<typename Derived>
13839ExprResult
13840TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
13841 // Transform each of the elements.
13842 SmallVector<Expr *, 8> Elements;
13843 bool ArgChanged = false;
13844 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
13845 /*IsCall=*/false, Elements, &ArgChanged))
13846 return ExprError();
13847
13848 if (!getDerived().AlwaysRebuild() && !ArgChanged)
13849 return SemaRef.MaybeBindToTemporary(E);
13850
13851 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
13852 Elements.data(),
13853 Elements.size());
13854}
13855
13856template<typename Derived>
13857ExprResult
13858TreeTransform<Derived>::TransformObjCDictionaryLiteral(
13859 ObjCDictionaryLiteral *E) {
13860 // Transform each of the elements.
13861 SmallVector<ObjCDictionaryElement, 8> Elements;
13862 bool ArgChanged = false;
13863 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
13864 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
13865
13866 if (OrigElement.isPackExpansion()) {
13867 // This key/value element is a pack expansion.
13868 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13869 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
13870 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
13871 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", 13871, __extension__ __PRETTY_FUNCTION__
))
;
13872
13873 // Determine whether the set of unexpanded parameter packs can
13874 // and should be expanded.
13875 bool Expand = true;
13876 bool RetainExpansion = false;
13877 Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
13878 Optional<unsigned> NumExpansions = OrigNumExpansions;
13879 SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
13880 OrigElement.Value->getEndLoc());
13881 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
13882 PatternRange, Unexpanded, Expand,
13883 RetainExpansion, NumExpansions))
13884 return ExprError();
13885
13886 if (!Expand) {
13887 // The transform has determined that we should perform a simple
13888 // transformation on the pack expansion, producing another pack
13889 // expansion.
13890 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13891 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13892 if (Key.isInvalid())
13893 return ExprError();
13894
13895 if (Key.get() != OrigElement.Key)
13896 ArgChanged = true;
13897
13898 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
13899 if (Value.isInvalid())
13900 return ExprError();
13901
13902 if (Value.get() != OrigElement.Value)
13903 ArgChanged = true;
13904
13905 ObjCDictionaryElement Expansion = {
13906 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
13907 };
13908 Elements.push_back(Expansion);
13909 continue;
13910 }
13911
13912 // Record right away that the argument was changed. This needs
13913 // to happen even if the array expands to nothing.
13914 ArgChanged = true;
13915
13916 // The transform has determined that we should perform an elementwise
13917 // expansion of the pattern. Do so.
13918 for (unsigned I = 0; I != *NumExpansions; ++I) {
13919 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13920 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13921 if (Key.isInvalid())
13922 return ExprError();
13923
13924 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
13925 if (Value.isInvalid())
13926 return ExprError();
13927
13928 ObjCDictionaryElement Element = {
13929 Key.get(), Value.get(), SourceLocation(), NumExpansions
13930 };
13931
13932 // If any unexpanded parameter packs remain, we still have a
13933 // pack expansion.
13934 // FIXME: Can this really happen?
13935 if (Key.get()->containsUnexpandedParameterPack() ||
13936 Value.get()->containsUnexpandedParameterPack())
13937 Element.EllipsisLoc = OrigElement.EllipsisLoc;
13938
13939 Elements.push_back(Element);
13940 }
13941
13942 // FIXME: Retain a pack expansion if RetainExpansion is true.
13943
13944 // We've finished with this pack expansion.
13945 continue;
13946 }
13947
13948 // Transform and check key.
13949 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13950 if (Key.isInvalid())
13951 return ExprError();
13952
13953 if (Key.get() != OrigElement.Key)
13954 ArgChanged = true;
13955
13956 // Transform and check value.
13957 ExprResult Value
13958 = getDerived().TransformExpr(OrigElement.Value);
13959 if (Value.isInvalid())
13960 return ExprError();
13961
13962 if (Value.get() != OrigElement.Value)
13963 ArgChanged = true;
13964
13965 ObjCDictionaryElement Element = {
13966 Key.get(), Value.get(), SourceLocation(), None
13967 };
13968 Elements.push_back(Element);
13969 }
13970
13971 if (!getDerived().AlwaysRebuild() && !ArgChanged)
13972 return SemaRef.MaybeBindToTemporary(E);
13973
13974 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
13975 Elements);
13976}
13977
13978template<typename Derived>
13979ExprResult
13980TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
13981 TypeSourceInfo *EncodedTypeInfo
13982 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
13983 if (!EncodedTypeInfo)
13984 return ExprError();
13985
13986 if (!getDerived().AlwaysRebuild() &&
13987 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
13988 return E;
13989
13990 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
13991 EncodedTypeInfo,
13992 E->getRParenLoc());
13993}
13994
13995template<typename Derived>
13996ExprResult TreeTransform<Derived>::
13997TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
13998 // This is a kind of implicit conversion, and it needs to get dropped
13999 // and recomputed for the same general reasons that ImplicitCastExprs
14000 // do, as well a more specific one: this expression is only valid when
14001 // it appears *immediately* as an argument expression.
14002 return getDerived().TransformExpr(E->getSubExpr());
14003}
14004
14005template<typename Derived>
14006ExprResult TreeTransform<Derived>::
14007TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
14008 TypeSourceInfo *TSInfo
14009 = getDerived().TransformType(E->getTypeInfoAsWritten());
14010 if (!TSInfo)
14011 return ExprError();
14012
14013 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
14014 if (Result.isInvalid())
14015 return ExprError();
14016
14017 if (!getDerived().AlwaysRebuild() &&
14018 TSInfo == E->getTypeInfoAsWritten() &&
14019 Result.get() == E->getSubExpr())
14020 return E;
14021
14022 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
14023 E->getBridgeKeywordLoc(), TSInfo,
14024 Result.get());
14025}
14026
14027template <typename Derived>
14028ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
14029 ObjCAvailabilityCheckExpr *E) {
14030 return E;
14031}
14032
14033template<typename Derived>
14034ExprResult
14035TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
14036 // Transform arguments.
14037 bool ArgChanged = false;
14038 SmallVector<Expr*, 8> Args;
14039 Args.reserve(E->getNumArgs());
14040 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
14041 &ArgChanged))
14042 return ExprError();
14043
14044 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
14045 // Class message: transform the receiver type.
14046 TypeSourceInfo *ReceiverTypeInfo
14047 = getDerived().TransformType(E->getClassReceiverTypeInfo());
14048 if (!ReceiverTypeInfo)
14049 return ExprError();
14050
14051 // If nothing changed, just retain the existing message send.
14052 if (!getDerived().AlwaysRebuild() &&
14053 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
14054 return SemaRef.MaybeBindToTemporary(E);
14055
14056 // Build a new class message send.
14057 SmallVector<SourceLocation, 16> SelLocs;
14058 E->getSelectorLocs(SelLocs);
14059 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
14060 E->getSelector(),
14061 SelLocs,
14062 E->getMethodDecl(),
14063 E->getLeftLoc(),
14064 Args,
14065 E->getRightLoc());
14066 }
14067 else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
14068 E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14069 if (!E->getMethodDecl())
14070 return ExprError();
14071
14072 // Build a new class message send to 'super'.
14073 SmallVector<SourceLocation, 16> SelLocs;
14074 E->getSelectorLocs(SelLocs);
14075 return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
14076 E->getSelector(),
14077 SelLocs,
14078 E->getReceiverType(),
14079 E->getMethodDecl(),
14080 E->getLeftLoc(),
14081 Args,
14082 E->getRightLoc());
14083 }
14084
14085 // Instance message: transform the receiver
14086 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", 14087, __extension__ __PRETTY_FUNCTION__
))
14087 "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", 14087, __extension__ __PRETTY_FUNCTION__
))
;
14088 ExprResult Receiver
14089 = getDerived().TransformExpr(E->getInstanceReceiver());
14090 if (Receiver.isInvalid())
14091 return ExprError();
14092
14093 // If nothing changed, just retain the existing message send.
14094 if (!getDerived().AlwaysRebuild() &&
14095 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
14096 return SemaRef.MaybeBindToTemporary(E);
14097
14098 // Build a new instance message send.
14099 SmallVector<SourceLocation, 16> SelLocs;
14100 E->getSelectorLocs(SelLocs);
14101 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
14102 E->getSelector(),
14103 SelLocs,
14104 E->getMethodDecl(),
14105 E->getLeftLoc(),
14106 Args,
14107 E->getRightLoc());
14108}
14109
14110template<typename Derived>
14111ExprResult
14112TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
14113 return E;
14114}
14115
14116template<typename Derived>
14117ExprResult
14118TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
14119 return E;
14120}
14121
14122template<typename Derived>
14123ExprResult
14124TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
14125 // Transform the base expression.
14126 ExprResult Base = getDerived().TransformExpr(E->getBase());
14127 if (Base.isInvalid())
14128 return ExprError();
14129
14130 // We don't need to transform the ivar; it will never change.
14131
14132 // If nothing changed, just retain the existing expression.
14133 if (!getDerived().AlwaysRebuild() &&
14134 Base.get() == E->getBase())
14135 return E;
14136
14137 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
14138 E->getLocation(),
14139 E->isArrow(), E->isFreeIvar());
14140}
14141
14142template<typename Derived>
14143ExprResult
14144TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
14145 // 'super' and types never change. Property never changes. Just
14146 // retain the existing expression.
14147 if (!E->isObjectReceiver())
14148 return E;
14149
14150 // Transform the base expression.
14151 ExprResult Base = getDerived().TransformExpr(E->getBase());
14152 if (Base.isInvalid())
14153 return ExprError();
14154
14155 // We don't need to transform the property; it will never change.
14156
14157 // If nothing changed, just retain the existing expression.
14158 if (!getDerived().AlwaysRebuild() &&
14159 Base.get() == E->getBase())
14160 return E;
14161
14162 if (E->isExplicitProperty())
14163 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14164 E->getExplicitProperty(),
14165 E->getLocation());
14166
14167 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14168 SemaRef.Context.PseudoObjectTy,
14169 E->getImplicitPropertyGetter(),
14170 E->getImplicitPropertySetter(),
14171 E->getLocation());
14172}
14173
14174template<typename Derived>
14175ExprResult
14176TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
14177 // Transform the base expression.
14178 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
14179 if (Base.isInvalid())
14180 return ExprError();
14181
14182 // Transform the key expression.
14183 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
14184 if (Key.isInvalid())
14185 return ExprError();
14186
14187 // If nothing changed, just retain the existing expression.
14188 if (!getDerived().AlwaysRebuild() &&
14189 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
14190 return E;
14191
14192 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
14193 Base.get(), Key.get(),
14194 E->getAtIndexMethodDecl(),
14195 E->setAtIndexMethodDecl());
14196}
14197
14198template<typename Derived>
14199ExprResult
14200TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
14201 // Transform the base expression.
14202 ExprResult Base = getDerived().TransformExpr(E->getBase());
14203 if (Base.isInvalid())
14204 return ExprError();
14205
14206 // If nothing changed, just retain the existing expression.
14207 if (!getDerived().AlwaysRebuild() &&
14208 Base.get() == E->getBase())
14209 return E;
14210
14211 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
14212 E->getOpLoc(),
14213 E->isArrow());
14214}
14215
14216template<typename Derived>
14217ExprResult
14218TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
14219 bool ArgumentChanged = false;
14220 SmallVector<Expr*, 8> SubExprs;
14221 SubExprs.reserve(E->getNumSubExprs());
14222 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14223 SubExprs, &ArgumentChanged))
14224 return ExprError();
14225
14226 if (!getDerived().AlwaysRebuild() &&
14227 !ArgumentChanged)
14228 return E;
14229
14230 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
14231 SubExprs,
14232 E->getRParenLoc());
14233}
14234
14235template<typename Derived>
14236ExprResult
14237TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
14238 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14239 if (SrcExpr.isInvalid())
14240 return ExprError();
14241
14242 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
14243 if (!Type)
14244 return ExprError();
14245
14246 if (!getDerived().AlwaysRebuild() &&
14247 Type == E->getTypeSourceInfo() &&
14248 SrcExpr.get() == E->getSrcExpr())
14249 return E;
14250
14251 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
14252 SrcExpr.get(), Type,
14253 E->getRParenLoc());
14254}
14255
14256template<typename Derived>
14257ExprResult
14258TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
14259 BlockDecl *oldBlock = E->getBlockDecl();
14260
14261 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
14262 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
14263
14264 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
14265 blockScope->TheDecl->setBlockMissingReturnType(
14266 oldBlock->blockMissingReturnType());
14267
14268 SmallVector<ParmVarDecl*, 4> params;
14269 SmallVector<QualType, 4> paramTypes;
14270
14271 const FunctionProtoType *exprFunctionType = E->getFunctionType();
14272
14273 // Parameter substitution.
14274 Sema::ExtParameterInfoBuilder extParamInfos;
14275 if (getDerived().TransformFunctionTypeParams(
14276 E->getCaretLocation(), oldBlock->parameters(), nullptr,
14277 exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
14278 extParamInfos)) {
14279 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14280 return ExprError();
14281 }
14282
14283 QualType exprResultType =
14284 getDerived().TransformType(exprFunctionType->getReturnType());
14285
14286 auto epi = exprFunctionType->getExtProtoInfo();
14287 epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
14288
14289 QualType functionType =
14290 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
14291 blockScope->FunctionType = functionType;
14292
14293 // Set the parameters on the block decl.
14294 if (!params.empty())
14295 blockScope->TheDecl->setParams(params);
14296
14297 if (!oldBlock->blockMissingReturnType()) {
14298 blockScope->HasImplicitReturnType = false;
14299 blockScope->ReturnType = exprResultType;
14300 }
14301
14302 // Transform the body
14303 StmtResult body = getDerived().TransformStmt(E->getBody());
14304 if (body.isInvalid()) {
14305 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14306 return ExprError();
14307 }
14308
14309#ifndef NDEBUG
14310 // In builds with assertions, make sure that we captured everything we
14311 // captured before.
14312 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
14313 for (const auto &I : oldBlock->captures()) {
14314 VarDecl *oldCapture = I.getVariable();
14315
14316 // Ignore parameter packs.
14317 if (oldCapture->isParameterPack())
14318 continue;
14319
14320 VarDecl *newCapture =
14321 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
14322 oldCapture));
14323 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", 14323, __extension__ __PRETTY_FUNCTION__
))
;
14324 }
14325 assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured())(static_cast <bool> (oldBlock->capturesCXXThis() == blockScope
->isCXXThisCaptured()) ? void (0) : __assert_fail ("oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured()"
, "clang/lib/Sema/TreeTransform.h", 14325, __extension__ __PRETTY_FUNCTION__
))
;
14326 }
14327#endif
14328
14329 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
14330 /*Scope=*/nullptr);
14331}
14332
14333template<typename Derived>
14334ExprResult
14335TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
14336 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14337 if (SrcExpr.isInvalid())
14338 return ExprError();
14339
14340 QualType Type = getDerived().TransformType(E->getType());
14341
14342 return SemaRef.BuildAsTypeExpr(SrcExpr.get(), Type, E->getBuiltinLoc(),
14343 E->getRParenLoc());
14344}
14345
14346template<typename Derived>
14347ExprResult
14348TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
14349 bool ArgumentChanged = false;
14350 SmallVector<Expr*, 8> SubExprs;
14351 SubExprs.reserve(E->getNumSubExprs());
14352 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14353 SubExprs, &ArgumentChanged))
14354 return ExprError();
14355
14356 if (!getDerived().AlwaysRebuild() &&
14357 !ArgumentChanged)
14358 return E;
14359
14360 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
14361 E->getOp(), E->getRParenLoc());
14362}
14363
14364//===----------------------------------------------------------------------===//
14365// Type reconstruction
14366//===----------------------------------------------------------------------===//
14367
14368template<typename Derived>
14369QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
14370 SourceLocation Star) {
14371 return SemaRef.BuildPointerType(PointeeType, Star,
14372 getDerived().getBaseEntity());
14373}
14374
14375template<typename Derived>
14376QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
14377 SourceLocation Star) {
14378 return SemaRef.BuildBlockPointerType(PointeeType, Star,
14379 getDerived().getBaseEntity());
14380}
14381
14382template<typename Derived>
14383QualType
14384TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
14385 bool WrittenAsLValue,
14386 SourceLocation Sigil) {
14387 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
14388 Sigil, getDerived().getBaseEntity());
14389}
14390
14391template<typename Derived>
14392QualType
14393TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
14394 QualType ClassType,
14395 SourceLocation Sigil) {
14396 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
14397 getDerived().getBaseEntity());
14398}
14399
14400template<typename Derived>
14401QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
14402 const ObjCTypeParamDecl *Decl,
14403 SourceLocation ProtocolLAngleLoc,
14404 ArrayRef<ObjCProtocolDecl *> Protocols,
14405 ArrayRef<SourceLocation> ProtocolLocs,
14406 SourceLocation ProtocolRAngleLoc) {
14407 return SemaRef.BuildObjCTypeParamType(Decl,
14408 ProtocolLAngleLoc, Protocols,
14409 ProtocolLocs, ProtocolRAngleLoc,
14410 /*FailOnError=*/true);
14411}
14412
14413template<typename Derived>
14414QualType TreeTransform<Derived>::RebuildObjCObjectType(
14415 QualType BaseType,
14416 SourceLocation Loc,
14417 SourceLocation TypeArgsLAngleLoc,
14418 ArrayRef<TypeSourceInfo *> TypeArgs,
14419 SourceLocation TypeArgsRAngleLoc,
14420 SourceLocation ProtocolLAngleLoc,
14421 ArrayRef<ObjCProtocolDecl *> Protocols,
14422 ArrayRef<SourceLocation> ProtocolLocs,
14423 SourceLocation ProtocolRAngleLoc) {
14424 return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
14425 TypeArgs, TypeArgsRAngleLoc,
14426 ProtocolLAngleLoc, Protocols, ProtocolLocs,
14427 ProtocolRAngleLoc,
14428 /*FailOnError=*/true);
14429}
14430
14431template<typename Derived>
14432QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
14433 QualType PointeeType,
14434 SourceLocation Star) {
14435 return SemaRef.Context.getObjCObjectPointerType(PointeeType);
14436}
14437
14438template<typename Derived>
14439QualType
14440TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
14441 ArrayType::ArraySizeModifier SizeMod,
14442 const llvm::APInt *Size,
14443 Expr *SizeExpr,
14444 unsigned IndexTypeQuals,
14445 SourceRange BracketsRange) {
14446 if (SizeExpr || !Size)
14447 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
14448 IndexTypeQuals, BracketsRange,
14449 getDerived().getBaseEntity());
14450
14451 QualType Types[] = {
14452 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
14453 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
14454 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
14455 };
14456 const unsigned NumTypes = llvm::array_lengthof(Types);
14457 QualType SizeType;
14458 for (unsigned I = 0; I != NumTypes; ++I)
14459 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
14460 SizeType = Types[I];
14461 break;
14462 }
14463
14464 // Note that we can return a VariableArrayType here in the case where
14465 // the element type was a dependent VariableArrayType.
14466 IntegerLiteral *ArraySize
14467 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
14468 /*FIXME*/BracketsRange.getBegin());
14469 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
14470 IndexTypeQuals, BracketsRange,
14471 getDerived().getBaseEntity());
14472}
14473
14474template<typename Derived>
14475QualType
14476TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
14477 ArrayType::ArraySizeModifier SizeMod,
14478 const llvm::APInt &Size,
14479 Expr *SizeExpr,
14480 unsigned IndexTypeQuals,
14481 SourceRange BracketsRange) {
14482 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
14483 IndexTypeQuals, BracketsRange);
14484}
14485
14486template<typename Derived>
14487QualType
14488TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
14489 ArrayType::ArraySizeModifier SizeMod,
14490 unsigned IndexTypeQuals,
14491 SourceRange BracketsRange) {
14492 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
14493 IndexTypeQuals, BracketsRange);
14494}
14495
14496template<typename Derived>
14497QualType
14498TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
14499 ArrayType::ArraySizeModifier SizeMod,
14500 Expr *SizeExpr,
14501 unsigned IndexTypeQuals,
14502 SourceRange BracketsRange) {
14503 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14504 SizeExpr,
14505 IndexTypeQuals, BracketsRange);
14506}
14507
14508template<typename Derived>
14509QualType
14510TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
14511 ArrayType::ArraySizeModifier SizeMod,
14512 Expr *SizeExpr,
14513 unsigned IndexTypeQuals,
14514 SourceRange BracketsRange) {
14515 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14516 SizeExpr,
14517 IndexTypeQuals, BracketsRange);
14518}
14519
14520template <typename Derived>
14521QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
14522 QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
14523 return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
14524 AttributeLoc);
14525}
14526
14527template <typename Derived>
14528QualType
14529TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
14530 unsigned NumElements,
14531 VectorType::VectorKind VecKind) {
14532 // FIXME: semantic checking!
14533 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
14534}
14535
14536template <typename Derived>
14537QualType TreeTransform<Derived>::RebuildDependentVectorType(
14538 QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
14539 VectorType::VectorKind VecKind) {
14540 return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
14541}
14542
14543template<typename Derived>
14544QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
14545 unsigned NumElements,
14546 SourceLocation AttributeLoc) {
14547 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14548 NumElements, true);
14549 IntegerLiteral *VectorSize
14550 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
14551 AttributeLoc);
14552 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
14553}
14554
14555template<typename Derived>
14556QualType
14557TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
14558 Expr *SizeExpr,
14559 SourceLocation AttributeLoc) {
14560 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
14561}
14562
14563template <typename Derived>
14564QualType TreeTransform<Derived>::RebuildConstantMatrixType(
14565 QualType ElementType, unsigned NumRows, unsigned NumColumns) {
14566 return SemaRef.Context.getConstantMatrixType(ElementType, NumRows,
14567 NumColumns);
14568}
14569
14570template <typename Derived>
14571QualType TreeTransform<Derived>::RebuildDependentSizedMatrixType(
14572 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr,
14573 SourceLocation AttributeLoc) {
14574 return SemaRef.BuildMatrixType(ElementType, RowExpr, ColumnExpr,
14575 AttributeLoc);
14576}
14577
14578template<typename Derived>
14579QualType TreeTransform<Derived>::RebuildFunctionProtoType(
14580 QualType T,
14581 MutableArrayRef<QualType> ParamTypes,
14582 const FunctionProtoType::ExtProtoInfo &EPI) {
14583 return SemaRef.BuildFunctionType(T, ParamTypes,
14584 getDerived().getBaseLocation(),
14585 getDerived().getBaseEntity(),
14586 EPI);
14587}
14588
14589template<typename Derived>
14590QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
14591 return SemaRef.Context.getFunctionNoProtoType(T);
14592}
14593
14594template<typename Derived>
14595QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
14596 Decl *D) {
14597 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"
, 14597, __extension__ __PRETTY_FUNCTION__))
;
14598 if (D->isInvalidDecl()) return QualType();
14599
14600 // FIXME: Doesn't account for ObjCInterfaceDecl!
14601 if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
14602 // A valid resolved using typename pack expansion decl can have multiple
14603 // UsingDecls, but they must each have exactly one type, and it must be
14604 // the same type in every case. But we must have at least one expansion!
14605 if (UPD->expansions().empty()) {
14606 getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
14607 << UPD->isCXXClassMember() << UPD;
14608 return QualType();
14609 }
14610
14611 // We might still have some unresolved types. Try to pick a resolved type
14612 // if we can. The final instantiation will check that the remaining
14613 // unresolved types instantiate to the type we pick.
14614 QualType FallbackT;
14615 QualType T;
14616 for (auto *E : UPD->expansions()) {
14617 QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
14618 if (ThisT.isNull())
14619 continue;
14620 else if (ThisT->getAs<UnresolvedUsingType>())
14621 FallbackT = ThisT;
14622 else if (T.isNull())
14623 T = ThisT;
14624 else
14625 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", 14626, __extension__ __PRETTY_FUNCTION__
))
14626 "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", 14626, __extension__ __PRETTY_FUNCTION__
))
;
14627 }
14628 return T.isNull() ? FallbackT : T;
14629 } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
14630 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", 14631, __extension__ __PRETTY_FUNCTION__
))
14631 "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", 14631, __extension__ __PRETTY_FUNCTION__
))
;
14632
14633 // A valid resolved using typename decl points to exactly one type decl.
14634 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", 14634, __extension__ __PRETTY_FUNCTION__
))
;
14635
14636 UsingShadowDecl *Shadow = *Using->shadow_begin();
14637 if (SemaRef.DiagnoseUseOfDecl(Shadow->getTargetDecl(), Loc))
14638 return QualType();
14639 return SemaRef.Context.getUsingType(
14640 Shadow, SemaRef.Context.getTypeDeclType(
14641 cast<TypeDecl>(Shadow->getTargetDecl())));
14642 } else {
14643 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", 14644, __extension__ __PRETTY_FUNCTION__
))
14644 "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", 14644, __extension__ __PRETTY_FUNCTION__
))
;
14645 return SemaRef.Context.getTypeDeclType(
14646 cast<UnresolvedUsingTypenameDecl>(D));
14647 }
14648}
14649
14650template <typename Derived>
14651QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
14652 SourceLocation) {
14653 return SemaRef.BuildTypeofExprType(E);
14654}
14655
14656template<typename Derived>
14657QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
14658 return SemaRef.Context.getTypeOfType(Underlying);
14659}
14660
14661template <typename Derived>
14662QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E, SourceLocation) {
14663 return SemaRef.BuildDecltypeType(E);
14664}
14665
14666template<typename Derived>
14667QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
14668 UnaryTransformType::UTTKind UKind,
14669 SourceLocation Loc) {
14670 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
14671}
14672
14673template<typename Derived>
14674QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
14675 TemplateName Template,
14676 SourceLocation TemplateNameLoc,
14677 TemplateArgumentListInfo &TemplateArgs) {
14678 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
14679}
14680
14681template<typename Derived>
14682QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
14683 SourceLocation KWLoc) {
14684 return SemaRef.BuildAtomicType(ValueType, KWLoc);
14685}
14686
14687template<typename Derived>
14688QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
14689 SourceLocation KWLoc,
14690 bool isReadPipe) {
14691 return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
14692 : SemaRef.BuildWritePipeType(ValueType, KWLoc);
14693}
14694
14695template <typename Derived>
14696QualType TreeTransform<Derived>::RebuildBitIntType(bool IsUnsigned,
14697 unsigned NumBits,
14698 SourceLocation Loc) {
14699 llvm::APInt NumBitsAP(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14700 NumBits, true);
14701 IntegerLiteral *Bits = IntegerLiteral::Create(SemaRef.Context, NumBitsAP,
14702 SemaRef.Context.IntTy, Loc);
14703 return SemaRef.BuildBitIntType(IsUnsigned, Bits, Loc);
14704}
14705
14706template <typename Derived>
14707QualType TreeTransform<Derived>::RebuildDependentBitIntType(
14708 bool IsUnsigned, Expr *NumBitsExpr, SourceLocation Loc) {
14709 return SemaRef.BuildBitIntType(IsUnsigned, NumBitsExpr, Loc);
14710}
14711
14712template<typename Derived>
14713TemplateName
14714TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14715 bool TemplateKW,
14716 TemplateDecl *Template) {
14717 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
14718 Template);
14719}
14720
14721template<typename Derived>
14722TemplateName
14723TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14724 SourceLocation TemplateKWLoc,
14725 const IdentifierInfo &Name,
14726 SourceLocation NameLoc,
14727 QualType ObjectType,
14728 NamedDecl *FirstQualifierInScope,
14729 bool AllowInjectedClassName) {
14730 UnqualifiedId TemplateName;
14731 TemplateName.setIdentifier(&Name, NameLoc);
14732 Sema::TemplateTy Template;
14733 getSema().ActOnTemplateName(/*Scope=*/nullptr, SS, TemplateKWLoc,
14734 TemplateName, ParsedType::make(ObjectType),
14735 /*EnteringContext=*/false, Template,
14736 AllowInjectedClassName);
14737 return Template.get();
14738}
14739
14740template<typename Derived>
14741TemplateName
14742TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14743 SourceLocation TemplateKWLoc,
14744 OverloadedOperatorKind Operator,
14745 SourceLocation NameLoc,
14746 QualType ObjectType,
14747 bool AllowInjectedClassName) {
14748 UnqualifiedId Name;
14749 // FIXME: Bogus location information.
14750 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
14751 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
14752 Sema::TemplateTy Template;
14753 getSema().ActOnTemplateName(
14754 /*Scope=*/nullptr, SS, TemplateKWLoc, Name, ParsedType::make(ObjectType),
14755 /*EnteringContext=*/false, Template, AllowInjectedClassName);
14756 return Template.get();
14757}
14758
14759template<typename Derived>
14760ExprResult
14761TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
14762 SourceLocation OpLoc,
14763 Expr *OrigCallee,
14764 Expr *First,
14765 Expr *Second) {
14766 Expr *Callee = OrigCallee->IgnoreParenCasts();
14767 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
14768
14769 if (First->getObjectKind() == OK_ObjCProperty) {
14770 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14771 if (BinaryOperator::isAssignmentOp(Opc))
14772 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
14773 First, Second);
14774 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
14775 if (Result.isInvalid())
14776 return ExprError();
14777 First = Result.get();
14778 }
14779
14780 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
14781 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
14782 if (Result.isInvalid())
14783 return ExprError();
14784 Second = Result.get();
14785 }
14786
14787 // Determine whether this should be a builtin operation.
14788 if (Op == OO_Subscript) {
14789 if (!First->getType()->isOverloadableType() &&
14790 !Second->getType()->isOverloadableType())
14791 return getSema().CreateBuiltinArraySubscriptExpr(
14792 First, Callee->getBeginLoc(), Second, OpLoc);
14793 } else if (Op == OO_Arrow) {
14794 // It is possible that the type refers to a RecoveryExpr created earlier
14795 // in the tree transformation.
14796 if (First->getType()->isDependentType())
14797 return ExprError();
14798 // -> is never a builtin operation.
14799 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
14800 } else if (Second == nullptr || isPostIncDec) {
14801 if (!First->getType()->isOverloadableType() ||
14802 (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
14803 // The argument is not of overloadable type, or this is an expression
14804 // of the form &Class::member, so try to create a built-in unary
14805 // operation.
14806 UnaryOperatorKind Opc
14807 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
14808
14809 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
14810 }
14811 } else {
14812 if (!First->getType()->isOverloadableType() &&
14813 !Second->getType()->isOverloadableType()) {
14814 // Neither of the arguments is an overloadable type, so try to
14815 // create a built-in binary operation.
14816 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14817 ExprResult Result
14818 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
14819 if (Result.isInvalid())
14820 return ExprError();
14821
14822 return Result;
14823 }
14824 }
14825
14826 // Compute the transformed set of functions (and function templates) to be
14827 // used during overload resolution.
14828 UnresolvedSet<16> Functions;
14829 bool RequiresADL;
14830
14831 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
14832 Functions.append(ULE->decls_begin(), ULE->decls_end());
14833 // If the overload could not be resolved in the template definition
14834 // (because we had a dependent argument), ADL is performed as part of
14835 // template instantiation.
14836 RequiresADL = ULE->requiresADL();
14837 } else {
14838 // If we've resolved this to a particular non-member function, just call
14839 // that function. If we resolved it to a member function,
14840 // CreateOverloaded* will find that function for us.
14841 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
14842 if (!isa<CXXMethodDecl>(ND))
14843 Functions.addDecl(ND);
14844 RequiresADL = false;
14845 }
14846
14847 // Add any functions found via argument-dependent lookup.
14848 Expr *Args[2] = { First, Second };
14849 unsigned NumArgs = 1 + (Second != nullptr);
14850
14851 // Create the overloaded operator invocation for unary operators.
14852 if (NumArgs == 1 || isPostIncDec) {
14853 UnaryOperatorKind Opc
14854 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
14855 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
14856 RequiresADL);
14857 }
14858
14859 if (Op == OO_Subscript) {
14860 SourceLocation LBrace;
14861 SourceLocation RBrace;
14862
14863 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
14864 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
14865 LBrace = NameLoc.getCXXOperatorNameBeginLoc();
14866 RBrace = NameLoc.getCXXOperatorNameEndLoc();
14867 } else {
14868 LBrace = Callee->getBeginLoc();
14869 RBrace = OpLoc;
14870 }
14871
14872 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
14873 First, Second);
14874 }
14875
14876 // Create the overloaded operator invocation for binary operators.
14877 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14878 ExprResult Result = SemaRef.CreateOverloadedBinOp(
14879 OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
14880 if (Result.isInvalid())
14881 return ExprError();
14882
14883 return Result;
14884}
14885
14886template<typename Derived>
14887ExprResult
14888TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
14889 SourceLocation OperatorLoc,
14890 bool isArrow,
14891 CXXScopeSpec &SS,
14892 TypeSourceInfo *ScopeType,
14893 SourceLocation CCLoc,
14894 SourceLocation TildeLoc,
14895 PseudoDestructorTypeStorage Destroyed) {
14896 QualType BaseType = Base->getType();
14897 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
14898 (!isArrow && !BaseType->getAs<RecordType>()) ||
14899 (isArrow && BaseType->getAs<PointerType>() &&
14900 !BaseType->castAs<PointerType>()->getPointeeType()
14901 ->template getAs<RecordType>())){
14902 // This pseudo-destructor expression is still a pseudo-destructor.
14903 return SemaRef.BuildPseudoDestructorExpr(
14904 Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
14905 CCLoc, TildeLoc, Destroyed);
14906 }
14907
14908 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
14909 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
14910 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
14911 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
14912 NameInfo.setNamedTypeInfo(DestroyedType);
14913
14914 // The scope type is now known to be a valid nested name specifier
14915 // component. Tack it on to the end of the nested name specifier.
14916 if (ScopeType) {
14917 if (!ScopeType->getType()->getAs<TagType>()) {
14918 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
14919 diag::err_expected_class_or_namespace)
14920 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
14921 return ExprError();
14922 }
14923 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
14924 CCLoc);
14925 }
14926
14927 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
14928 return getSema().BuildMemberReferenceExpr(Base, BaseType,
14929 OperatorLoc, isArrow,
14930 SS, TemplateKWLoc,
14931 /*FIXME: FirstQualifier*/ nullptr,
14932 NameInfo,
14933 /*TemplateArgs*/ nullptr,
14934 /*S*/nullptr);
14935}
14936
14937template<typename Derived>
14938StmtResult
14939TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
14940 SourceLocation Loc = S->getBeginLoc();
14941 CapturedDecl *CD = S->getCapturedDecl();
14942 unsigned NumParams = CD->getNumParams();
14943 unsigned ContextParamPos = CD->getContextParamPosition();
14944 SmallVector<Sema::CapturedParamNameType, 4> Params;
14945 for (unsigned I = 0; I < NumParams; ++I) {
14946 if (I != ContextParamPos) {
14947 Params.push_back(
14948 std::make_pair(
14949 CD->getParam(I)->getName(),
14950 getDerived().TransformType(CD->getParam(I)->getType())));
14951 } else {
14952 Params.push_back(std::make_pair(StringRef(), QualType()));
14953 }
14954 }
14955 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
14956 S->getCapturedRegionKind(), Params);
14957 StmtResult Body;
14958 {
14959 Sema::CompoundScopeRAII CompoundScope(getSema());
14960 Body = getDerived().TransformStmt(S->getCapturedStmt());
14961 }
14962
14963 if (Body.isInvalid()) {
14964 getSema().ActOnCapturedRegionError();
14965 return StmtError();
14966 }
14967
14968 return getSema().ActOnCapturedRegionEnd(Body.get());
14969}
14970
14971} // end namespace clang
14972
14973#endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H