Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220320100729+487629cc61b5/clang/lib/Sema/SemaExpr.cpp
Warning:line 9571, column 27
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~++20220320100729+487629cc61b5/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~++20220320100729+487629cc61b5/clang/lib/Sema -I /build/llvm-toolchain-snapshot-15~++20220320100729+487629cc61b5/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-15~++20220320100729+487629cc61b5/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~++20220320100729+487629cc61b5/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220320100729+487629cc61b5/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220320100729+487629cc61b5/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220320100729+487629cc61b5/= -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~++20220320100729+487629cc61b5/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220320100729+487629cc61b5/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220320100729+487629cc61b5/= -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-03-20-232535-108605-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220320100729+487629cc61b5/clang/lib/Sema/SemaExpr.cpp

/build/llvm-toolchain-snapshot-15~++20220320100729+487629cc61b5/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/TypeLoc.h"
31#include "clang/Basic/Builtins.h"
32#include "clang/Basic/DiagnosticSema.h"
33#include "clang/Basic/PartialDiagnostic.h"
34#include "clang/Basic/SourceManager.h"
35#include "clang/Basic/TargetInfo.h"
36#include "clang/Lex/LiteralSupport.h"
37#include "clang/Lex/Preprocessor.h"
38#include "clang/Sema/AnalysisBasedWarnings.h"
39#include "clang/Sema/DeclSpec.h"
40#include "clang/Sema/DelayedDiagnostic.h"
41#include "clang/Sema/Designator.h"
42#include "clang/Sema/Initialization.h"
43#include "clang/Sema/Lookup.h"
44#include "clang/Sema/Overload.h"
45#include "clang/Sema/ParsedTemplate.h"
46#include "clang/Sema/Scope.h"
47#include "clang/Sema/ScopeInfo.h"
48#include "clang/Sema/SemaFixItUtils.h"
49#include "clang/Sema/SemaInternal.h"
50#include "clang/Sema/Template.h"
51#include "llvm/ADT/STLExtras.h"
52#include "llvm/ADT/StringExtras.h"
53#include "llvm/Support/ConvertUTF.h"
54#include "llvm/Support/SaveAndRestore.h"
55
56using namespace clang;
57using namespace sema;
58
59/// Determine whether the use of this declaration is valid, without
60/// emitting diagnostics.
61bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
62 // See if this is an auto-typed variable whose initializer we are parsing.
63 if (ParsingInitForAutoVars.count(D))
64 return false;
65
66 // See if this is a deleted function.
67 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
68 if (FD->isDeleted())
69 return false;
70
71 // If the function has a deduced return type, and we can't deduce it,
72 // then we can't use it either.
73 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
74 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
75 return false;
76
77 // See if this is an aligned allocation/deallocation function that is
78 // unavailable.
79 if (TreatUnavailableAsInvalid &&
80 isUnavailableAlignedAllocationFunction(*FD))
81 return false;
82 }
83
84 // See if this function is unavailable.
85 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
86 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
87 return false;
88
89 if (isa<UnresolvedUsingIfExistsDecl>(D))
90 return false;
91
92 return true;
93}
94
95static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
96 // Warn if this is used but marked unused.
97 if (const auto *A = D->getAttr<UnusedAttr>()) {
98 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
99 // should diagnose them.
100 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
101 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
102 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
103 if (DC && !DC->hasAttr<UnusedAttr>())
104 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
105 }
106 }
107}
108
109/// Emit a note explaining that this function is deleted.
110void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
111 assert(Decl && Decl->isDeleted())(static_cast <bool> (Decl && Decl->isDeleted
()) ? void (0) : __assert_fail ("Decl && Decl->isDeleted()"
, "clang/lib/Sema/SemaExpr.cpp", 111, __extension__ __PRETTY_FUNCTION__
))
;
112
113 if (Decl->isDefaulted()) {
114 // If the method was explicitly defaulted, point at that declaration.
115 if (!Decl->isImplicit())
116 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
117
118 // Try to diagnose why this special member function was implicitly
119 // deleted. This might fail, if that reason no longer applies.
120 DiagnoseDeletedDefaultedFunction(Decl);
121 return;
122 }
123
124 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
125 if (Ctor && Ctor->isInheritingConstructor())
126 return NoteDeletedInheritingConstructor(Ctor);
127
128 Diag(Decl->getLocation(), diag::note_availability_specified_here)
129 << Decl << 1;
130}
131
132/// Determine whether a FunctionDecl was ever declared with an
133/// explicit storage class.
134static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
135 for (auto I : D->redecls()) {
136 if (I->getStorageClass() != SC_None)
137 return true;
138 }
139 return false;
140}
141
142/// Check whether we're in an extern inline function and referring to a
143/// variable or function with internal linkage (C11 6.7.4p3).
144///
145/// This is only a warning because we used to silently accept this code, but
146/// in many cases it will not behave correctly. This is not enabled in C++ mode
147/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
148/// and so while there may still be user mistakes, most of the time we can't
149/// prove that there are errors.
150static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
151 const NamedDecl *D,
152 SourceLocation Loc) {
153 // This is disabled under C++; there are too many ways for this to fire in
154 // contexts where the warning is a false positive, or where it is technically
155 // correct but benign.
156 if (S.getLangOpts().CPlusPlus)
157 return;
158
159 // Check if this is an inlined function or method.
160 FunctionDecl *Current = S.getCurFunctionDecl();
161 if (!Current)
162 return;
163 if (!Current->isInlined())
164 return;
165 if (!Current->isExternallyVisible())
166 return;
167
168 // Check if the decl has internal linkage.
169 if (D->getFormalLinkage() != InternalLinkage)
170 return;
171
172 // Downgrade from ExtWarn to Extension if
173 // (1) the supposedly external inline function is in the main file,
174 // and probably won't be included anywhere else.
175 // (2) the thing we're referencing is a pure function.
176 // (3) the thing we're referencing is another inline function.
177 // This last can give us false negatives, but it's better than warning on
178 // wrappers for simple C library functions.
179 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
180 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
181 if (!DowngradeWarning && UsedFn)
182 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
183
184 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
185 : diag::ext_internal_in_extern_inline)
186 << /*IsVar=*/!UsedFn << D;
187
188 S.MaybeSuggestAddingStaticToDecl(Current);
189
190 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
191 << D;
192}
193
194void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
195 const FunctionDecl *First = Cur->getFirstDecl();
196
197 // Suggest "static" on the function, if possible.
198 if (!hasAnyExplicitStorageClass(First)) {
199 SourceLocation DeclBegin = First->getSourceRange().getBegin();
200 Diag(DeclBegin, diag::note_convert_inline_to_static)
201 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
202 }
203}
204
205/// Determine whether the use of this declaration is valid, and
206/// emit any corresponding diagnostics.
207///
208/// This routine diagnoses various problems with referencing
209/// declarations that can occur when using a declaration. For example,
210/// it might warn if a deprecated or unavailable declaration is being
211/// used, or produce an error (and return true) if a C++0x deleted
212/// function is being used.
213///
214/// \returns true if there was an error (this declaration cannot be
215/// referenced), false otherwise.
216///
217bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
218 const ObjCInterfaceDecl *UnknownObjCClass,
219 bool ObjCPropertyAccess,
220 bool AvoidPartialAvailabilityChecks,
221 ObjCInterfaceDecl *ClassReceiver) {
222 SourceLocation Loc = Locs.front();
223 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
224 // If there were any diagnostics suppressed by template argument deduction,
225 // emit them now.
226 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
227 if (Pos != SuppressedDiagnostics.end()) {
228 for (const PartialDiagnosticAt &Suppressed : Pos->second)
229 Diag(Suppressed.first, Suppressed.second);
230
231 // Clear out the list of suppressed diagnostics, so that we don't emit
232 // them again for this specialization. However, we don't obsolete this
233 // entry from the table, because we want to avoid ever emitting these
234 // diagnostics again.
235 Pos->second.clear();
236 }
237
238 // C++ [basic.start.main]p3:
239 // The function 'main' shall not be used within a program.
240 if (cast<FunctionDecl>(D)->isMain())
241 Diag(Loc, diag::ext_main_used);
242
243 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
244 }
245
246 // See if this is an auto-typed variable whose initializer we are parsing.
247 if (ParsingInitForAutoVars.count(D)) {
248 if (isa<BindingDecl>(D)) {
249 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
250 << D->getDeclName();
251 } else {
252 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
253 << D->getDeclName() << cast<VarDecl>(D)->getType();
254 }
255 return true;
256 }
257
258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
259 // See if this is a deleted function.
260 if (FD->isDeleted()) {
261 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
262 if (Ctor && Ctor->isInheritingConstructor())
263 Diag(Loc, diag::err_deleted_inherited_ctor_use)
264 << Ctor->getParent()
265 << Ctor->getInheritedConstructor().getConstructor()->getParent();
266 else
267 Diag(Loc, diag::err_deleted_function_use);
268 NoteDeletedFunction(FD);
269 return true;
270 }
271
272 // [expr.prim.id]p4
273 // A program that refers explicitly or implicitly to a function with a
274 // trailing requires-clause whose constraint-expression is not satisfied,
275 // other than to declare it, is ill-formed. [...]
276 //
277 // See if this is a function with constraints that need to be satisfied.
278 // Check this before deducing the return type, as it might instantiate the
279 // definition.
280 if (FD->getTrailingRequiresClause()) {
281 ConstraintSatisfaction Satisfaction;
282 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
283 // A diagnostic will have already been generated (non-constant
284 // constraint expression, for example)
285 return true;
286 if (!Satisfaction.IsSatisfied) {
287 Diag(Loc,
288 diag::err_reference_to_function_with_unsatisfied_constraints)
289 << D;
290 DiagnoseUnsatisfiedConstraint(Satisfaction);
291 return true;
292 }
293 }
294
295 // If the function has a deduced return type, and we can't deduce it,
296 // then we can't use it either.
297 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
298 DeduceReturnType(FD, Loc))
299 return true;
300
301 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
302 return true;
303
304 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
305 return true;
306 }
307
308 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
309 // Lambdas are only default-constructible or assignable in C++2a onwards.
310 if (MD->getParent()->isLambda() &&
311 ((isa<CXXConstructorDecl>(MD) &&
312 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
313 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
314 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
315 << !isa<CXXConstructorDecl>(MD);
316 }
317 }
318
319 auto getReferencedObjCProp = [](const NamedDecl *D) ->
320 const ObjCPropertyDecl * {
321 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
322 return MD->findPropertyDecl();
323 return nullptr;
324 };
325 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
326 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
327 return true;
328 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
329 return true;
330 }
331
332 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
333 // Only the variables omp_in and omp_out are allowed in the combiner.
334 // Only the variables omp_priv and omp_orig are allowed in the
335 // initializer-clause.
336 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
337 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
338 isa<VarDecl>(D)) {
339 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
340 << getCurFunction()->HasOMPDeclareReductionCombiner;
341 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
342 return true;
343 }
344
345 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
346 // List-items in map clauses on this construct may only refer to the declared
347 // variable var and entities that could be referenced by a procedure defined
348 // at the same location
349 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
350 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
351 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
352 << getOpenMPDeclareMapperVarName();
353 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
354 return true;
355 }
356
357 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
358 Diag(Loc, diag::err_use_of_empty_using_if_exists);
359 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
360 return true;
361 }
362
363 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
364 AvoidPartialAvailabilityChecks, ClassReceiver);
365
366 DiagnoseUnusedOfDecl(*this, D, Loc);
367
368 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
369
370 if (auto *VD = dyn_cast<ValueDecl>(D))
371 checkTypeSupport(VD->getType(), Loc, VD);
372
373 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
374 if (!Context.getTargetInfo().isTLSSupported())
375 if (const auto *VD = dyn_cast<VarDecl>(D))
376 if (VD->getTLSKind() != VarDecl::TLS_None)
377 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
378 }
379
380 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
381 !isUnevaluatedContext()) {
382 // C++ [expr.prim.req.nested] p3
383 // A local parameter shall only appear as an unevaluated operand
384 // (Clause 8) within the constraint-expression.
385 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
386 << D;
387 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
388 return true;
389 }
390
391 return false;
392}
393
394/// DiagnoseSentinelCalls - This routine checks whether a call or
395/// message-send is to a declaration with the sentinel attribute, and
396/// if so, it checks that the requirements of the sentinel are
397/// satisfied.
398void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
399 ArrayRef<Expr *> Args) {
400 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
401 if (!attr)
402 return;
403
404 // The number of formal parameters of the declaration.
405 unsigned numFormalParams;
406
407 // The kind of declaration. This is also an index into a %select in
408 // the diagnostic.
409 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
410
411 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
412 numFormalParams = MD->param_size();
413 calleeType = CT_Method;
414 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
415 numFormalParams = FD->param_size();
416 calleeType = CT_Function;
417 } else if (isa<VarDecl>(D)) {
418 QualType type = cast<ValueDecl>(D)->getType();
419 const FunctionType *fn = nullptr;
420 if (const PointerType *ptr = type->getAs<PointerType>()) {
421 fn = ptr->getPointeeType()->getAs<FunctionType>();
422 if (!fn) return;
423 calleeType = CT_Function;
424 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
425 fn = ptr->getPointeeType()->castAs<FunctionType>();
426 calleeType = CT_Block;
427 } else {
428 return;
429 }
430
431 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
432 numFormalParams = proto->getNumParams();
433 } else {
434 numFormalParams = 0;
435 }
436 } else {
437 return;
438 }
439
440 // "nullPos" is the number of formal parameters at the end which
441 // effectively count as part of the variadic arguments. This is
442 // useful if you would prefer to not have *any* formal parameters,
443 // but the language forces you to have at least one.
444 unsigned nullPos = attr->getNullPos();
445 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", 445, __extension__ __PRETTY_FUNCTION__
))
;
446 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
447
448 // The number of arguments which should follow the sentinel.
449 unsigned numArgsAfterSentinel = attr->getSentinel();
450
451 // If there aren't enough arguments for all the formal parameters,
452 // the sentinel, and the args after the sentinel, complain.
453 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
454 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
455 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
456 return;
457 }
458
459 // Otherwise, find the sentinel expression.
460 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
461 if (!sentinelExpr) return;
462 if (sentinelExpr->isValueDependent()) return;
463 if (Context.isSentinelNullExpr(sentinelExpr)) return;
464
465 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
466 // or 'NULL' if those are actually defined in the context. Only use
467 // 'nil' for ObjC methods, where it's much more likely that the
468 // variadic arguments form a list of object pointers.
469 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
470 std::string NullValue;
471 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
472 NullValue = "nil";
473 else if (getLangOpts().CPlusPlus11)
474 NullValue = "nullptr";
475 else if (PP.isMacroDefined("NULL"))
476 NullValue = "NULL";
477 else
478 NullValue = "(void*) 0";
479
480 if (MissingNilLoc.isInvalid())
481 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
482 else
483 Diag(MissingNilLoc, diag::warn_missing_sentinel)
484 << int(calleeType)
485 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
486 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
487}
488
489SourceRange Sema::getExprRange(Expr *E) const {
490 return E ? E->getSourceRange() : SourceRange();
491}
492
493//===----------------------------------------------------------------------===//
494// Standard Promotions and Conversions
495//===----------------------------------------------------------------------===//
496
497/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
498ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
499 // Handle any placeholder expressions which made it here.
500 if (E->hasPlaceholderType()) {
501 ExprResult result = CheckPlaceholderExpr(E);
502 if (result.isInvalid()) return ExprError();
503 E = result.get();
504 }
505
506 QualType Ty = E->getType();
507 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", 507, __extension__ __PRETTY_FUNCTION__
))
;
508
509 if (Ty->isFunctionType()) {
510 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
511 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
512 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
513 return ExprError();
514
515 E = ImpCastExprToType(E, Context.getPointerType(Ty),
516 CK_FunctionToPointerDecay).get();
517 } else if (Ty->isArrayType()) {
518 // In C90 mode, arrays only promote to pointers if the array expression is
519 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
520 // type 'array of type' is converted to an expression that has type 'pointer
521 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
522 // that has type 'array of type' ...". The relevant change is "an lvalue"
523 // (C90) to "an expression" (C99).
524 //
525 // C++ 4.2p1:
526 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
527 // T" can be converted to an rvalue of type "pointer to T".
528 //
529 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
530 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
531 CK_ArrayToPointerDecay);
532 if (Res.isInvalid())
533 return ExprError();
534 E = Res.get();
535 }
536 }
537 return E;
538}
539
540static void CheckForNullPointerDereference(Sema &S, Expr *E) {
541 // Check to see if we are dereferencing a null pointer. If so,
542 // and if not volatile-qualified, this is undefined behavior that the
543 // optimizer will delete, so warn about it. People sometimes try to use this
544 // to get a deterministic trap and are surprised by clang's behavior. This
545 // only handles the pattern "*null", which is a very syntactic check.
546 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
547 if (UO && UO->getOpcode() == UO_Deref &&
548 UO->getSubExpr()->getType()->isPointerType()) {
549 const LangAS AS =
550 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
551 if ((!isTargetAddressSpace(AS) ||
552 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
553 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
554 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
555 !UO->getType().isVolatileQualified()) {
556 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
557 S.PDiag(diag::warn_indirection_through_null)
558 << UO->getSubExpr()->getSourceRange());
559 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
560 S.PDiag(diag::note_indirection_through_null));
561 }
562 }
563}
564
565static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
566 SourceLocation AssignLoc,
567 const Expr* RHS) {
568 const ObjCIvarDecl *IV = OIRE->getDecl();
569 if (!IV)
570 return;
571
572 DeclarationName MemberName = IV->getDeclName();
573 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
574 if (!Member || !Member->isStr("isa"))
575 return;
576
577 const Expr *Base = OIRE->getBase();
578 QualType BaseType = Base->getType();
579 if (OIRE->isArrow())
580 BaseType = BaseType->getPointeeType();
581 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
582 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
583 ObjCInterfaceDecl *ClassDeclared = nullptr;
584 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
585 if (!ClassDeclared->getSuperClass()
586 && (*ClassDeclared->ivar_begin()) == IV) {
587 if (RHS) {
588 NamedDecl *ObjectSetClass =
589 S.LookupSingleName(S.TUScope,
590 &S.Context.Idents.get("object_setClass"),
591 SourceLocation(), S.LookupOrdinaryName);
592 if (ObjectSetClass) {
593 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
594 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
595 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
596 "object_setClass(")
597 << FixItHint::CreateReplacement(
598 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
599 << FixItHint::CreateInsertion(RHSLocEnd, ")");
600 }
601 else
602 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
603 } else {
604 NamedDecl *ObjectGetClass =
605 S.LookupSingleName(S.TUScope,
606 &S.Context.Idents.get("object_getClass"),
607 SourceLocation(), S.LookupOrdinaryName);
608 if (ObjectGetClass)
609 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
610 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
611 "object_getClass(")
612 << FixItHint::CreateReplacement(
613 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
614 else
615 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
616 }
617 S.Diag(IV->getLocation(), diag::note_ivar_decl);
618 }
619 }
620}
621
622ExprResult Sema::DefaultLvalueConversion(Expr *E) {
623 // Handle any placeholder expressions which made it here.
624 if (E->hasPlaceholderType()) {
625 ExprResult result = CheckPlaceholderExpr(E);
626 if (result.isInvalid()) return ExprError();
627 E = result.get();
628 }
629
630 // C++ [conv.lval]p1:
631 // A glvalue of a non-function, non-array type T can be
632 // converted to a prvalue.
633 if (!E->isGLValue()) return E;
634
635 QualType T = E->getType();
636 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", 636, __extension__ __PRETTY_FUNCTION__
))
;
637
638 // lvalue-to-rvalue conversion cannot be applied to function or array types.
639 if (T->isFunctionType() || T->isArrayType())
640 return E;
641
642 // We don't want to throw lvalue-to-rvalue casts on top of
643 // expressions of certain types in C++.
644 if (getLangOpts().CPlusPlus &&
645 (E->getType() == Context.OverloadTy ||
646 T->isDependentType() ||
647 T->isRecordType()))
648 return E;
649
650 // The C standard is actually really unclear on this point, and
651 // DR106 tells us what the result should be but not why. It's
652 // generally best to say that void types just doesn't undergo
653 // lvalue-to-rvalue at all. Note that expressions of unqualified
654 // 'void' type are never l-values, but qualified void can be.
655 if (T->isVoidType())
656 return E;
657
658 // OpenCL usually rejects direct accesses to values of 'half' type.
659 if (getLangOpts().OpenCL &&
660 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
661 T->isHalfType()) {
662 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
663 << 0 << T;
664 return ExprError();
665 }
666
667 CheckForNullPointerDereference(*this, E);
668 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
669 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
670 &Context.Idents.get("object_getClass"),
671 SourceLocation(), LookupOrdinaryName);
672 if (ObjectGetClass)
673 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
674 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
675 << FixItHint::CreateReplacement(
676 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
677 else
678 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
679 }
680 else if (const ObjCIvarRefExpr *OIRE =
681 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
682 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
683
684 // C++ [conv.lval]p1:
685 // [...] If T is a non-class type, the type of the prvalue is the
686 // cv-unqualified version of T. Otherwise, the type of the
687 // rvalue is T.
688 //
689 // C99 6.3.2.1p2:
690 // If the lvalue has qualified type, the value has the unqualified
691 // version of the type of the lvalue; otherwise, the value has the
692 // type of the lvalue.
693 if (T.hasQualifiers())
694 T = T.getUnqualifiedType();
695
696 // Under the MS ABI, lock down the inheritance model now.
697 if (T->isMemberPointerType() &&
698 Context.getTargetInfo().getCXXABI().isMicrosoft())
699 (void)isCompleteType(E->getExprLoc(), T);
700
701 ExprResult Res = CheckLValueToRValueConversionOperand(E);
702 if (Res.isInvalid())
703 return Res;
704 E = Res.get();
705
706 // Loading a __weak object implicitly retains the value, so we need a cleanup to
707 // balance that.
708 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
709 Cleanup.setExprNeedsCleanups(true);
710
711 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
712 Cleanup.setExprNeedsCleanups(true);
713
714 // C++ [conv.lval]p3:
715 // If T is cv std::nullptr_t, the result is a null pointer constant.
716 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
717 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
718 CurFPFeatureOverrides());
719
720 // C11 6.3.2.1p2:
721 // ... if the lvalue has atomic type, the value has the non-atomic version
722 // of the type of the lvalue ...
723 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
724 T = Atomic->getValueType().getUnqualifiedType();
725 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
726 nullptr, VK_PRValue, FPOptionsOverride());
727 }
728
729 return Res;
730}
731
732ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
733 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
734 if (Res.isInvalid())
735 return ExprError();
736 Res = DefaultLvalueConversion(Res.get());
737 if (Res.isInvalid())
738 return ExprError();
739 return Res;
740}
741
742/// CallExprUnaryConversions - a special case of an unary conversion
743/// performed on a function designator of a call expression.
744ExprResult Sema::CallExprUnaryConversions(Expr *E) {
745 QualType Ty = E->getType();
746 ExprResult Res = E;
747 // Only do implicit cast for a function type, but not for a pointer
748 // to function type.
749 if (Ty->isFunctionType()) {
750 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
751 CK_FunctionToPointerDecay);
752 if (Res.isInvalid())
753 return ExprError();
754 }
755 Res = DefaultLvalueConversion(Res.get());
756 if (Res.isInvalid())
757 return ExprError();
758 return Res.get();
759}
760
761/// UsualUnaryConversions - Performs various conversions that are common to most
762/// operators (C99 6.3). The conversions of array and function types are
763/// sometimes suppressed. For example, the array->pointer conversion doesn't
764/// apply if the array is an argument to the sizeof or address (&) operators.
765/// In these instances, this routine should *not* be called.
766ExprResult Sema::UsualUnaryConversions(Expr *E) {
767 // First, convert to an r-value.
768 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
769 if (Res.isInvalid())
770 return ExprError();
771 E = Res.get();
772
773 QualType Ty = E->getType();
774 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", 774, __extension__ __PRETTY_FUNCTION__
))
;
775
776 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
777 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
778 (getLangOpts().getFPEvalMethod() !=
779 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
780 PP.getLastFPEvalPragmaLocation().isValid())) {
781 switch (EvalMethod) {
782 default:
783 llvm_unreachable("Unrecognized float evaluation method")::llvm::llvm_unreachable_internal("Unrecognized float evaluation method"
, "clang/lib/Sema/SemaExpr.cpp", 783)
;
784 break;
785 case LangOptions::FEM_UnsetOnCommandLine:
786 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", 786)
;
787 break;
788 case LangOptions::FEM_Double:
789 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
790 // Widen the expression to double.
791 return Ty->isComplexType()
792 ? ImpCastExprToType(E,
793 Context.getComplexType(Context.DoubleTy),
794 CK_FloatingComplexCast)
795 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
796 break;
797 case LangOptions::FEM_Extended:
798 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
799 // Widen the expression to long double.
800 return Ty->isComplexType()
801 ? ImpCastExprToType(
802 E, Context.getComplexType(Context.LongDoubleTy),
803 CK_FloatingComplexCast)
804 : ImpCastExprToType(E, Context.LongDoubleTy,
805 CK_FloatingCast);
806 break;
807 }
808 }
809
810 // Half FP have to be promoted to float unless it is natively supported
811 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
812 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
813
814 // Try to perform integral promotions if the object has a theoretically
815 // promotable type.
816 if (Ty->isIntegralOrUnscopedEnumerationType()) {
817 // C99 6.3.1.1p2:
818 //
819 // The following may be used in an expression wherever an int or
820 // unsigned int may be used:
821 // - an object or expression with an integer type whose integer
822 // conversion rank is less than or equal to the rank of int
823 // and unsigned int.
824 // - A bit-field of type _Bool, int, signed int, or unsigned int.
825 //
826 // If an int can represent all values of the original type, the
827 // value is converted to an int; otherwise, it is converted to an
828 // unsigned int. These are called the integer promotions. All
829 // other types are unchanged by the integer promotions.
830
831 QualType PTy = Context.isPromotableBitField(E);
832 if (!PTy.isNull()) {
833 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
834 return E;
835 }
836 if (Ty->isPromotableIntegerType()) {
837 QualType PT = Context.getPromotedIntegerType(Ty);
838 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
839 return E;
840 }
841 }
842 return E;
843}
844
845/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
846/// do not have a prototype. Arguments that have type float or __fp16
847/// are promoted to double. All other argument types are converted by
848/// UsualUnaryConversions().
849ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
850 QualType Ty = E->getType();
851 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", 851, __extension__ __PRETTY_FUNCTION__
))
;
852
853 ExprResult Res = UsualUnaryConversions(E);
854 if (Res.isInvalid())
855 return ExprError();
856 E = Res.get();
857
858 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
859 // promote to double.
860 // Note that default argument promotion applies only to float (and
861 // half/fp16); it does not apply to _Float16.
862 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
863 if (BTy && (BTy->getKind() == BuiltinType::Half ||
864 BTy->getKind() == BuiltinType::Float)) {
865 if (getLangOpts().OpenCL &&
866 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
867 if (BTy->getKind() == BuiltinType::Half) {
868 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
869 }
870 } else {
871 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
872 }
873 }
874 if (BTy &&
875 getLangOpts().getExtendIntArgs() ==
876 LangOptions::ExtendArgsKind::ExtendTo64 &&
877 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
878 Context.getTypeSizeInChars(BTy) <
879 Context.getTypeSizeInChars(Context.LongLongTy)) {
880 E = (Ty->isUnsignedIntegerType())
881 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
882 .get()
883 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
884 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", 885, __extension__ __PRETTY_FUNCTION__
))
885 "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", 885, __extension__ __PRETTY_FUNCTION__
))
;
886 }
887
888 // C++ performs lvalue-to-rvalue conversion as a default argument
889 // promotion, even on class types, but note:
890 // C++11 [conv.lval]p2:
891 // When an lvalue-to-rvalue conversion occurs in an unevaluated
892 // operand or a subexpression thereof the value contained in the
893 // referenced object is not accessed. Otherwise, if the glvalue
894 // has a class type, the conversion copy-initializes a temporary
895 // of type T from the glvalue and the result of the conversion
896 // is a prvalue for the temporary.
897 // FIXME: add some way to gate this entire thing for correctness in
898 // potentially potentially evaluated contexts.
899 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
900 ExprResult Temp = PerformCopyInitialization(
901 InitializedEntity::InitializeTemporary(E->getType()),
902 E->getExprLoc(), E);
903 if (Temp.isInvalid())
904 return ExprError();
905 E = Temp.get();
906 }
907
908 return E;
909}
910
911/// Determine the degree of POD-ness for an expression.
912/// Incomplete types are considered POD, since this check can be performed
913/// when we're in an unevaluated context.
914Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
915 if (Ty->isIncompleteType()) {
916 // C++11 [expr.call]p7:
917 // After these conversions, if the argument does not have arithmetic,
918 // enumeration, pointer, pointer to member, or class type, the program
919 // is ill-formed.
920 //
921 // Since we've already performed array-to-pointer and function-to-pointer
922 // decay, the only such type in C++ is cv void. This also handles
923 // initializer lists as variadic arguments.
924 if (Ty->isVoidType())
925 return VAK_Invalid;
926
927 if (Ty->isObjCObjectType())
928 return VAK_Invalid;
929 return VAK_Valid;
930 }
931
932 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
933 return VAK_Invalid;
934
935 if (Ty.isCXX98PODType(Context))
936 return VAK_Valid;
937
938 // C++11 [expr.call]p7:
939 // Passing a potentially-evaluated argument of class type (Clause 9)
940 // having a non-trivial copy constructor, a non-trivial move constructor,
941 // or a non-trivial destructor, with no corresponding parameter,
942 // is conditionally-supported with implementation-defined semantics.
943 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
944 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
945 if (!Record->hasNonTrivialCopyConstructor() &&
946 !Record->hasNonTrivialMoveConstructor() &&
947 !Record->hasNonTrivialDestructor())
948 return VAK_ValidInCXX11;
949
950 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
951 return VAK_Valid;
952
953 if (Ty->isObjCObjectType())
954 return VAK_Invalid;
955
956 if (getLangOpts().MSVCCompat)
957 return VAK_MSVCUndefined;
958
959 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
960 // permitted to reject them. We should consider doing so.
961 return VAK_Undefined;
962}
963
964void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
965 // Don't allow one to pass an Objective-C interface to a vararg.
966 const QualType &Ty = E->getType();
967 VarArgKind VAK = isValidVarArgType(Ty);
968
969 // Complain about passing non-POD types through varargs.
970 switch (VAK) {
971 case VAK_ValidInCXX11:
972 DiagRuntimeBehavior(
973 E->getBeginLoc(), nullptr,
974 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
975 LLVM_FALLTHROUGH[[gnu::fallthrough]];
976 case VAK_Valid:
977 if (Ty->isRecordType()) {
978 // This is unlikely to be what the user intended. If the class has a
979 // 'c_str' member function, the user probably meant to call that.
980 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
981 PDiag(diag::warn_pass_class_arg_to_vararg)
982 << Ty << CT << hasCStrMethod(E) << ".c_str()");
983 }
984 break;
985
986 case VAK_Undefined:
987 case VAK_MSVCUndefined:
988 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
989 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
990 << getLangOpts().CPlusPlus11 << Ty << CT);
991 break;
992
993 case VAK_Invalid:
994 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
995 Diag(E->getBeginLoc(),
996 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
997 << Ty << CT;
998 else if (Ty->isObjCObjectType())
999 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1000 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1001 << Ty << CT);
1002 else
1003 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1004 << isa<InitListExpr>(E) << Ty << CT;
1005 break;
1006 }
1007}
1008
1009/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1010/// will create a trap if the resulting type is not a POD type.
1011ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1012 FunctionDecl *FDecl) {
1013 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1014 // Strip the unbridged-cast placeholder expression off, if applicable.
1015 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1016 (CT == VariadicMethod ||
1017 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1018 E = stripARCUnbridgedCast(E);
1019
1020 // Otherwise, do normal placeholder checking.
1021 } else {
1022 ExprResult ExprRes = CheckPlaceholderExpr(E);
1023 if (ExprRes.isInvalid())
1024 return ExprError();
1025 E = ExprRes.get();
1026 }
1027 }
1028
1029 ExprResult ExprRes = DefaultArgumentPromotion(E);
1030 if (ExprRes.isInvalid())
1031 return ExprError();
1032
1033 // Copy blocks to the heap.
1034 if (ExprRes.get()->getType()->isBlockPointerType())
1035 maybeExtendBlockObject(ExprRes);
1036
1037 E = ExprRes.get();
1038
1039 // Diagnostics regarding non-POD argument types are
1040 // emitted along with format string checking in Sema::CheckFunctionCall().
1041 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1042 // Turn this into a trap.
1043 CXXScopeSpec SS;
1044 SourceLocation TemplateKWLoc;
1045 UnqualifiedId Name;
1046 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1047 E->getBeginLoc());
1048 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1049 /*HasTrailingLParen=*/true,
1050 /*IsAddressOfOperand=*/false);
1051 if (TrapFn.isInvalid())
1052 return ExprError();
1053
1054 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1055 None, E->getEndLoc());
1056 if (Call.isInvalid())
1057 return ExprError();
1058
1059 ExprResult Comma =
1060 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1061 if (Comma.isInvalid())
1062 return ExprError();
1063 return Comma.get();
1064 }
1065
1066 if (!getLangOpts().CPlusPlus &&
1067 RequireCompleteType(E->getExprLoc(), E->getType(),
1068 diag::err_call_incomplete_argument))
1069 return ExprError();
1070
1071 return E;
1072}
1073
1074/// Converts an integer to complex float type. Helper function of
1075/// UsualArithmeticConversions()
1076///
1077/// \return false if the integer expression is an integer type and is
1078/// successfully converted to the complex type.
1079static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1080 ExprResult &ComplexExpr,
1081 QualType IntTy,
1082 QualType ComplexTy,
1083 bool SkipCast) {
1084 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1085 if (SkipCast) return false;
1086 if (IntTy->isIntegerType()) {
1087 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1088 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1089 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1090 CK_FloatingRealToComplex);
1091 } else {
1092 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "clang/lib/Sema/SemaExpr.cpp", 1092, __extension__ __PRETTY_FUNCTION__
))
;
1093 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1094 CK_IntegralComplexToFloatingComplex);
1095 }
1096 return false;
1097}
1098
1099/// Handle arithmetic conversion with complex types. Helper function of
1100/// UsualArithmeticConversions()
1101static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1102 ExprResult &RHS, QualType LHSType,
1103 QualType RHSType,
1104 bool IsCompAssign) {
1105 // if we have an integer operand, the result is the complex type.
1106 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1107 /*skipCast*/false))
1108 return LHSType;
1109 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1110 /*skipCast*/IsCompAssign))
1111 return RHSType;
1112
1113 // This handles complex/complex, complex/float, or float/complex.
1114 // When both operands are complex, the shorter operand is converted to the
1115 // type of the longer, and that is the type of the result. This corresponds
1116 // to what is done when combining two real floating-point operands.
1117 // The fun begins when size promotion occur across type domains.
1118 // From H&S 6.3.4: When one operand is complex and the other is a real
1119 // floating-point type, the less precise type is converted, within it's
1120 // real or complex domain, to the precision of the other type. For example,
1121 // when combining a "long double" with a "double _Complex", the
1122 // "double _Complex" is promoted to "long double _Complex".
1123
1124 // Compute the rank of the two types, regardless of whether they are complex.
1125 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1126
1127 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1128 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1129 QualType LHSElementType =
1130 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1131 QualType RHSElementType =
1132 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1133
1134 QualType ResultType = S.Context.getComplexType(LHSElementType);
1135 if (Order < 0) {
1136 // Promote the precision of the LHS if not an assignment.
1137 ResultType = S.Context.getComplexType(RHSElementType);
1138 if (!IsCompAssign) {
1139 if (LHSComplexType)
1140 LHS =
1141 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1142 else
1143 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1144 }
1145 } else if (Order > 0) {
1146 // Promote the precision of the RHS.
1147 if (RHSComplexType)
1148 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1149 else
1150 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1151 }
1152 return ResultType;
1153}
1154
1155/// Handle arithmetic conversion from integer to float. Helper function
1156/// of UsualArithmeticConversions()
1157static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1158 ExprResult &IntExpr,
1159 QualType FloatTy, QualType IntTy,
1160 bool ConvertFloat, bool ConvertInt) {
1161 if (IntTy->isIntegerType()) {
1162 if (ConvertInt)
1163 // Convert intExpr to the lhs floating point type.
1164 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1165 CK_IntegralToFloating);
1166 return FloatTy;
1167 }
1168
1169 // Convert both sides to the appropriate complex float.
1170 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "clang/lib/Sema/SemaExpr.cpp", 1170, __extension__ __PRETTY_FUNCTION__
))
;
1171 QualType result = S.Context.getComplexType(FloatTy);
1172
1173 // _Complex int -> _Complex float
1174 if (ConvertInt)
1175 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1176 CK_IntegralComplexToFloatingComplex);
1177
1178 // float -> _Complex float
1179 if (ConvertFloat)
1180 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1181 CK_FloatingRealToComplex);
1182
1183 return result;
1184}
1185
1186/// Handle arithmethic conversion with floating point types. Helper
1187/// function of UsualArithmeticConversions()
1188static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1189 ExprResult &RHS, QualType LHSType,
1190 QualType RHSType, bool IsCompAssign) {
1191 bool LHSFloat = LHSType->isRealFloatingType();
1192 bool RHSFloat = RHSType->isRealFloatingType();
1193
1194 // N1169 4.1.4: If one of the operands has a floating type and the other
1195 // operand has a fixed-point type, the fixed-point operand
1196 // is converted to the floating type [...]
1197 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1198 if (LHSFloat)
1199 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1200 else if (!IsCompAssign)
1201 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1202 return LHSFloat ? LHSType : RHSType;
1203 }
1204
1205 // If we have two real floating types, convert the smaller operand
1206 // to the bigger result.
1207 if (LHSFloat && RHSFloat) {
1208 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1209 if (order > 0) {
1210 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1211 return LHSType;
1212 }
1213
1214 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", 1214, __extension__ __PRETTY_FUNCTION__
))
;
1215 if (!IsCompAssign)
1216 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1217 return RHSType;
1218 }
1219
1220 if (LHSFloat) {
1221 // Half FP has to be promoted to float unless it is natively supported
1222 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1223 LHSType = S.Context.FloatTy;
1224
1225 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1226 /*ConvertFloat=*/!IsCompAssign,
1227 /*ConvertInt=*/ true);
1228 }
1229 assert(RHSFloat)(static_cast <bool> (RHSFloat) ? void (0) : __assert_fail
("RHSFloat", "clang/lib/Sema/SemaExpr.cpp", 1229, __extension__
__PRETTY_FUNCTION__))
;
1230 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1231 /*ConvertFloat=*/ true,
1232 /*ConvertInt=*/!IsCompAssign);
1233}
1234
1235/// Diagnose attempts to convert between __float128, __ibm128 and
1236/// long double if there is no support for such conversion.
1237/// Helper function of UsualArithmeticConversions().
1238static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1239 QualType RHSType) {
1240 // No issue if either is not a floating point type.
1241 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
31
Assuming the condition is false
32
Assuming the condition is false
33
Taking false branch
1242 return false;
1243
1244 // No issue if both have the same 128-bit float semantics.
1245 auto *LHSComplex = LHSType->getAs<ComplexType>();
34
Assuming the object is not a 'ComplexType'
1246 auto *RHSComplex = RHSType->getAs<ComplexType>();
35
Assuming the object is not a 'ComplexType'
1247
1248 QualType LHSElem = LHSComplex
35.1
'LHSComplex' is null
35.1
'LHSComplex' is null
35.1
'LHSComplex' is null
35.1
'LHSComplex' is null
? LHSComplex->getElementType() : LHSType;
36
'?' condition is false
1249 QualType RHSElem = RHSComplex
36.1
'RHSComplex' is null
36.1
'RHSComplex' is null
36.1
'RHSComplex' is null
36.1
'RHSComplex' is null
? RHSComplex->getElementType() : RHSType;
37
'?' condition is false
1250
1251 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1252 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1253
1254 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
38
Assuming the condition is false
42
Taking true branch
1255 &RHSSem != &llvm::APFloat::IEEEquad()) &&
39
Assuming the condition is true
1256 (&LHSSem != &llvm::APFloat::IEEEquad() ||
40
Assuming the condition is false
1257 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
41
Assuming the condition is true
1258 return false;
43
Returning zero, which participates in a condition later
1259
1260 return true;
1261}
1262
1263typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1264
1265namespace {
1266/// These helper callbacks are placed in an anonymous namespace to
1267/// permit their use as function template parameters.
1268ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1269 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1270}
1271
1272ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1273 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1274 CK_IntegralComplexCast);
1275}
1276}
1277
1278/// Handle integer arithmetic conversions. Helper function of
1279/// UsualArithmeticConversions()
1280template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1281static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1282 ExprResult &RHS, QualType LHSType,
1283 QualType RHSType, bool IsCompAssign) {
1284 // The rules for this case are in C99 6.3.1.8
1285 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1286 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1287 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1288 if (LHSSigned == RHSSigned) {
1289 // Same signedness; use the higher-ranked type
1290 if (order >= 0) {
1291 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1292 return LHSType;
1293 } else if (!IsCompAssign)
1294 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1295 return RHSType;
1296 } else if (order != (LHSSigned ? 1 : -1)) {
1297 // The unsigned type has greater than or equal rank to the
1298 // signed type, so use the unsigned type
1299 if (RHSSigned) {
1300 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1301 return LHSType;
1302 } else if (!IsCompAssign)
1303 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1304 return RHSType;
1305 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1306 // The two types are different widths; if we are here, that
1307 // means the signed type is larger than the unsigned type, so
1308 // use the signed type.
1309 if (LHSSigned) {
1310 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1311 return LHSType;
1312 } else if (!IsCompAssign)
1313 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1314 return RHSType;
1315 } else {
1316 // The signed type is higher-ranked than the unsigned type,
1317 // but isn't actually any bigger (like unsigned int and long
1318 // on most 32-bit systems). Use the unsigned type corresponding
1319 // to the signed type.
1320 QualType result =
1321 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1322 RHS = (*doRHSCast)(S, RHS.get(), result);
1323 if (!IsCompAssign)
1324 LHS = (*doLHSCast)(S, LHS.get(), result);
1325 return result;
1326 }
1327}
1328
1329/// Handle conversions with GCC complex int extension. Helper function
1330/// of UsualArithmeticConversions()
1331static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1332 ExprResult &RHS, QualType LHSType,
1333 QualType RHSType,
1334 bool IsCompAssign) {
1335 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1336 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1337
1338 if (LHSComplexInt && RHSComplexInt) {
1339 QualType LHSEltType = LHSComplexInt->getElementType();
1340 QualType RHSEltType = RHSComplexInt->getElementType();
1341 QualType ScalarType =
1342 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1343 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1344
1345 return S.Context.getComplexType(ScalarType);
1346 }
1347
1348 if (LHSComplexInt) {
1349 QualType LHSEltType = LHSComplexInt->getElementType();
1350 QualType ScalarType =
1351 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1352 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1353 QualType ComplexType = S.Context.getComplexType(ScalarType);
1354 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1355 CK_IntegralRealToComplex);
1356
1357 return ComplexType;
1358 }
1359
1360 assert(RHSComplexInt)(static_cast <bool> (RHSComplexInt) ? void (0) : __assert_fail
("RHSComplexInt", "clang/lib/Sema/SemaExpr.cpp", 1360, __extension__
__PRETTY_FUNCTION__))
;
1361
1362 QualType RHSEltType = RHSComplexInt->getElementType();
1363 QualType ScalarType =
1364 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1365 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1366 QualType ComplexType = S.Context.getComplexType(ScalarType);
1367
1368 if (!IsCompAssign)
1369 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1370 CK_IntegralRealToComplex);
1371 return ComplexType;
1372}
1373
1374/// Return the rank of a given fixed point or integer type. The value itself
1375/// doesn't matter, but the values must be increasing with proper increasing
1376/// rank as described in N1169 4.1.1.
1377static unsigned GetFixedPointRank(QualType Ty) {
1378 const auto *BTy = Ty->getAs<BuiltinType>();
1379 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", 1379, __extension__ __PRETTY_FUNCTION__
))
;
1380
1381 switch (BTy->getKind()) {
1382 case BuiltinType::ShortFract:
1383 case BuiltinType::UShortFract:
1384 case BuiltinType::SatShortFract:
1385 case BuiltinType::SatUShortFract:
1386 return 1;
1387 case BuiltinType::Fract:
1388 case BuiltinType::UFract:
1389 case BuiltinType::SatFract:
1390 case BuiltinType::SatUFract:
1391 return 2;
1392 case BuiltinType::LongFract:
1393 case BuiltinType::ULongFract:
1394 case BuiltinType::SatLongFract:
1395 case BuiltinType::SatULongFract:
1396 return 3;
1397 case BuiltinType::ShortAccum:
1398 case BuiltinType::UShortAccum:
1399 case BuiltinType::SatShortAccum:
1400 case BuiltinType::SatUShortAccum:
1401 return 4;
1402 case BuiltinType::Accum:
1403 case BuiltinType::UAccum:
1404 case BuiltinType::SatAccum:
1405 case BuiltinType::SatUAccum:
1406 return 5;
1407 case BuiltinType::LongAccum:
1408 case BuiltinType::ULongAccum:
1409 case BuiltinType::SatLongAccum:
1410 case BuiltinType::SatULongAccum:
1411 return 6;
1412 default:
1413 if (BTy->isInteger())
1414 return 0;
1415 llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type"
, "clang/lib/Sema/SemaExpr.cpp", 1415)
;
1416 }
1417}
1418
1419/// handleFixedPointConversion - Fixed point operations between fixed
1420/// point types and integers or other fixed point types do not fall under
1421/// usual arithmetic conversion since these conversions could result in loss
1422/// of precsision (N1169 4.1.4). These operations should be calculated with
1423/// the full precision of their result type (N1169 4.1.6.2.1).
1424static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1425 QualType RHSTy) {
1426 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", 1427, __extension__ __PRETTY_FUNCTION__
))
1427 "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", 1427, __extension__ __PRETTY_FUNCTION__
))
;
1428 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", 1431, __extension__ __PRETTY_FUNCTION__
))
1429 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", 1431, __extension__ __PRETTY_FUNCTION__
))
1430 "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", 1431, __extension__ __PRETTY_FUNCTION__
))
1431 "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", 1431, __extension__ __PRETTY_FUNCTION__
))
;
1432
1433 // If one operand has signed fixed-point type and the other operand has
1434 // unsigned fixed-point type, then the unsigned fixed-point operand is
1435 // converted to its corresponding signed fixed-point type and the resulting
1436 // type is the type of the converted operand.
1437 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1438 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1439 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1440 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1441
1442 // The result type is the type with the highest rank, whereby a fixed-point
1443 // conversion rank is always greater than an integer conversion rank; if the
1444 // type of either of the operands is a saturating fixedpoint type, the result
1445 // type shall be the saturating fixed-point type corresponding to the type
1446 // with the highest rank; the resulting value is converted (taking into
1447 // account rounding and overflow) to the precision of the resulting type.
1448 // Same ranks between signed and unsigned types are resolved earlier, so both
1449 // types are either signed or both unsigned at this point.
1450 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1451 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1452
1453 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1454
1455 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1456 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1457
1458 return ResultTy;
1459}
1460
1461/// Check that the usual arithmetic conversions can be performed on this pair of
1462/// expressions that might be of enumeration type.
1463static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1464 SourceLocation Loc,
1465 Sema::ArithConvKind ACK) {
1466 // C++2a [expr.arith.conv]p1:
1467 // If one operand is of enumeration type and the other operand is of a
1468 // different enumeration type or a floating-point type, this behavior is
1469 // deprecated ([depr.arith.conv.enum]).
1470 //
1471 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1472 // Eventually we will presumably reject these cases (in C++23 onwards?).
1473 QualType L = LHS->getType(), R = RHS->getType();
1474 bool LEnum = L->isUnscopedEnumerationType(),
1475 REnum = R->isUnscopedEnumerationType();
1476 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1477 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1478 (REnum && L->isFloatingType())) {
1479 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1480 ? diag::warn_arith_conv_enum_float_cxx20
1481 : diag::warn_arith_conv_enum_float)
1482 << LHS->getSourceRange() << RHS->getSourceRange()
1483 << (int)ACK << LEnum << L << R;
1484 } else if (!IsCompAssign && LEnum && REnum &&
1485 !S.Context.hasSameUnqualifiedType(L, R)) {
1486 unsigned DiagID;
1487 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1488 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1489 // If either enumeration type is unnamed, it's less likely that the
1490 // user cares about this, but this situation is still deprecated in
1491 // C++2a. Use a different warning group.
1492 DiagID = S.getLangOpts().CPlusPlus20
1493 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1494 : diag::warn_arith_conv_mixed_anon_enum_types;
1495 } else if (ACK == Sema::ACK_Conditional) {
1496 // Conditional expressions are separated out because they have
1497 // historically had a different warning flag.
1498 DiagID = S.getLangOpts().CPlusPlus20
1499 ? diag::warn_conditional_mixed_enum_types_cxx20
1500 : diag::warn_conditional_mixed_enum_types;
1501 } else if (ACK == Sema::ACK_Comparison) {
1502 // Comparison expressions are separated out because they have
1503 // historically had a different warning flag.
1504 DiagID = S.getLangOpts().CPlusPlus20
1505 ? diag::warn_comparison_mixed_enum_types_cxx20
1506 : diag::warn_comparison_mixed_enum_types;
1507 } else {
1508 DiagID = S.getLangOpts().CPlusPlus20
1509 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1510 : diag::warn_arith_conv_mixed_enum_types;
1511 }
1512 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1513 << (int)ACK << L << R;
1514 }
1515}
1516
1517/// UsualArithmeticConversions - Performs various conversions that are common to
1518/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1519/// routine returns the first non-arithmetic type found. The client is
1520/// responsible for emitting appropriate error diagnostics.
1521QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1522 SourceLocation Loc,
1523 ArithConvKind ACK) {
1524 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1525
1526 if (ACK != ACK_CompAssign) {
1527 LHS = UsualUnaryConversions(LHS.get());
1528 if (LHS.isInvalid())
1529 return QualType();
1530 }
1531
1532 RHS = UsualUnaryConversions(RHS.get());
1533 if (RHS.isInvalid())
1534 return QualType();
1535
1536 // For conversion purposes, we ignore any qualifiers.
1537 // For example, "const float" and "float" are equivalent.
1538 QualType LHSType =
1539 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1540 QualType RHSType =
1541 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1542
1543 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1544 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1545 LHSType = AtomicLHS->getValueType();
1546
1547 // If both types are identical, no conversion is needed.
1548 if (LHSType == RHSType)
1549 return LHSType;
1550
1551 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1552 // The caller can deal with this (e.g. pointer + int).
1553 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1554 return QualType();
1555
1556 // Apply unary and bitfield promotions to the LHS's type.
1557 QualType LHSUnpromotedType = LHSType;
1558 if (LHSType->isPromotableIntegerType())
1559 LHSType = Context.getPromotedIntegerType(LHSType);
1560 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1561 if (!LHSBitfieldPromoteTy.isNull())
1562 LHSType = LHSBitfieldPromoteTy;
1563 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1564 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1565
1566 // If both types are identical, no conversion is needed.
1567 if (LHSType == RHSType)
1568 return LHSType;
1569
1570 // At this point, we have two different arithmetic types.
1571
1572 // Diagnose attempts to convert between __ibm128, __float128 and long double
1573 // where such conversions currently can't be handled.
1574 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1575 return QualType();
1576
1577 // Handle complex types first (C99 6.3.1.8p1).
1578 if (LHSType->isComplexType() || RHSType->isComplexType())
1579 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1580 ACK == ACK_CompAssign);
1581
1582 // Now handle "real" floating types (i.e. float, double, long double).
1583 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1584 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1585 ACK == ACK_CompAssign);
1586
1587 // Handle GCC complex int extension.
1588 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1589 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1590 ACK == ACK_CompAssign);
1591
1592 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1593 return handleFixedPointConversion(*this, LHSType, RHSType);
1594
1595 // Finally, we have two differing integer types.
1596 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1597 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1598}
1599
1600//===----------------------------------------------------------------------===//
1601// Semantic Analysis for various Expression Types
1602//===----------------------------------------------------------------------===//
1603
1604
1605ExprResult
1606Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1607 SourceLocation DefaultLoc,
1608 SourceLocation RParenLoc,
1609 Expr *ControllingExpr,
1610 ArrayRef<ParsedType> ArgTypes,
1611 ArrayRef<Expr *> ArgExprs) {
1612 unsigned NumAssocs = ArgTypes.size();
1613 assert(NumAssocs == ArgExprs.size())(static_cast <bool> (NumAssocs == ArgExprs.size()) ? void
(0) : __assert_fail ("NumAssocs == ArgExprs.size()", "clang/lib/Sema/SemaExpr.cpp"
, 1613, __extension__ __PRETTY_FUNCTION__))
;
1614
1615 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1616 for (unsigned i = 0; i < NumAssocs; ++i) {
1617 if (ArgTypes[i])
1618 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1619 else
1620 Types[i] = nullptr;
1621 }
1622
1623 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1624 ControllingExpr,
1625 llvm::makeArrayRef(Types, NumAssocs),
1626 ArgExprs);
1627 delete [] Types;
1628 return ER;
1629}
1630
1631ExprResult
1632Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1633 SourceLocation DefaultLoc,
1634 SourceLocation RParenLoc,
1635 Expr *ControllingExpr,
1636 ArrayRef<TypeSourceInfo *> Types,
1637 ArrayRef<Expr *> Exprs) {
1638 unsigned NumAssocs = Types.size();
1639 assert(NumAssocs == Exprs.size())(static_cast <bool> (NumAssocs == Exprs.size()) ? void (
0) : __assert_fail ("NumAssocs == Exprs.size()", "clang/lib/Sema/SemaExpr.cpp"
, 1639, __extension__ __PRETTY_FUNCTION__))
;
1640
1641 // Decay and strip qualifiers for the controlling expression type, and handle
1642 // placeholder type replacement. See committee discussion from WG14 DR423.
1643 {
1644 EnterExpressionEvaluationContext Unevaluated(
1645 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1646 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1647 if (R.isInvalid())
1648 return ExprError();
1649 ControllingExpr = R.get();
1650 }
1651
1652 // The controlling expression is an unevaluated operand, so side effects are
1653 // likely unintended.
1654 if (!inTemplateInstantiation() &&
1655 ControllingExpr->HasSideEffects(Context, false))
1656 Diag(ControllingExpr->getExprLoc(),
1657 diag::warn_side_effects_unevaluated_context);
1658
1659 bool TypeErrorFound = false,
1660 IsResultDependent = ControllingExpr->isTypeDependent(),
1661 ContainsUnexpandedParameterPack
1662 = ControllingExpr->containsUnexpandedParameterPack();
1663
1664 for (unsigned i = 0; i < NumAssocs; ++i) {
1665 if (Exprs[i]->containsUnexpandedParameterPack())
1666 ContainsUnexpandedParameterPack = true;
1667
1668 if (Types[i]) {
1669 if (Types[i]->getType()->containsUnexpandedParameterPack())
1670 ContainsUnexpandedParameterPack = true;
1671
1672 if (Types[i]->getType()->isDependentType()) {
1673 IsResultDependent = true;
1674 } else {
1675 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1676 // complete object type other than a variably modified type."
1677 unsigned D = 0;
1678 if (Types[i]->getType()->isIncompleteType())
1679 D = diag::err_assoc_type_incomplete;
1680 else if (!Types[i]->getType()->isObjectType())
1681 D = diag::err_assoc_type_nonobject;
1682 else if (Types[i]->getType()->isVariablyModifiedType())
1683 D = diag::err_assoc_type_variably_modified;
1684
1685 if (D != 0) {
1686 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1687 << Types[i]->getTypeLoc().getSourceRange()
1688 << Types[i]->getType();
1689 TypeErrorFound = true;
1690 }
1691
1692 // C11 6.5.1.1p2 "No two generic associations in the same generic
1693 // selection shall specify compatible types."
1694 for (unsigned j = i+1; j < NumAssocs; ++j)
1695 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1696 Context.typesAreCompatible(Types[i]->getType(),
1697 Types[j]->getType())) {
1698 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1699 diag::err_assoc_compatible_types)
1700 << Types[j]->getTypeLoc().getSourceRange()
1701 << Types[j]->getType()
1702 << Types[i]->getType();
1703 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1704 diag::note_compat_assoc)
1705 << Types[i]->getTypeLoc().getSourceRange()
1706 << Types[i]->getType();
1707 TypeErrorFound = true;
1708 }
1709 }
1710 }
1711 }
1712 if (TypeErrorFound)
1713 return ExprError();
1714
1715 // If we determined that the generic selection is result-dependent, don't
1716 // try to compute the result expression.
1717 if (IsResultDependent)
1718 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1719 Exprs, DefaultLoc, RParenLoc,
1720 ContainsUnexpandedParameterPack);
1721
1722 SmallVector<unsigned, 1> CompatIndices;
1723 unsigned DefaultIndex = -1U;
1724 for (unsigned i = 0; i < NumAssocs; ++i) {
1725 if (!Types[i])
1726 DefaultIndex = i;
1727 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1728 Types[i]->getType()))
1729 CompatIndices.push_back(i);
1730 }
1731
1732 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1733 // type compatible with at most one of the types named in its generic
1734 // association list."
1735 if (CompatIndices.size() > 1) {
1736 // We strip parens here because the controlling expression is typically
1737 // parenthesized in macro definitions.
1738 ControllingExpr = ControllingExpr->IgnoreParens();
1739 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1740 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1741 << (unsigned)CompatIndices.size();
1742 for (unsigned I : CompatIndices) {
1743 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1744 diag::note_compat_assoc)
1745 << Types[I]->getTypeLoc().getSourceRange()
1746 << Types[I]->getType();
1747 }
1748 return ExprError();
1749 }
1750
1751 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1752 // its controlling expression shall have type compatible with exactly one of
1753 // the types named in its generic association list."
1754 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1755 // We strip parens here because the controlling expression is typically
1756 // parenthesized in macro definitions.
1757 ControllingExpr = ControllingExpr->IgnoreParens();
1758 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1759 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1760 return ExprError();
1761 }
1762
1763 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1764 // type name that is compatible with the type of the controlling expression,
1765 // then the result expression of the generic selection is the expression
1766 // in that generic association. Otherwise, the result expression of the
1767 // generic selection is the expression in the default generic association."
1768 unsigned ResultIndex =
1769 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1770
1771 return GenericSelectionExpr::Create(
1772 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1773 ContainsUnexpandedParameterPack, ResultIndex);
1774}
1775
1776/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1777/// location of the token and the offset of the ud-suffix within it.
1778static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1779 unsigned Offset) {
1780 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1781 S.getLangOpts());
1782}
1783
1784/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1785/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1786static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1787 IdentifierInfo *UDSuffix,
1788 SourceLocation UDSuffixLoc,
1789 ArrayRef<Expr*> Args,
1790 SourceLocation LitEndLoc) {
1791 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", 1791, __extension__ __PRETTY_FUNCTION__
))
;
1792
1793 QualType ArgTy[2];
1794 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1795 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1796 if (ArgTy[ArgIdx]->isArrayType())
1797 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1798 }
1799
1800 DeclarationName OpName =
1801 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1802 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1803 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1804
1805 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1806 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1807 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1808 /*AllowStringTemplatePack*/ false,
1809 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1810 return ExprError();
1811
1812 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1813}
1814
1815/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1816/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1817/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1818/// multiple tokens. However, the common case is that StringToks points to one
1819/// string.
1820///
1821ExprResult
1822Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1823 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", 1823, __extension__ __PRETTY_FUNCTION__
))
;
1824
1825 StringLiteralParser Literal(StringToks, PP);
1826 if (Literal.hadError)
1827 return ExprError();
1828
1829 SmallVector<SourceLocation, 4> StringTokLocs;
1830 for (const Token &Tok : StringToks)
1831 StringTokLocs.push_back(Tok.getLocation());
1832
1833 QualType CharTy = Context.CharTy;
1834 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1835 if (Literal.isWide()) {
1836 CharTy = Context.getWideCharType();
1837 Kind = StringLiteral::Wide;
1838 } else if (Literal.isUTF8()) {
1839 if (getLangOpts().Char8)
1840 CharTy = Context.Char8Ty;
1841 Kind = StringLiteral::UTF8;
1842 } else if (Literal.isUTF16()) {
1843 CharTy = Context.Char16Ty;
1844 Kind = StringLiteral::UTF16;
1845 } else if (Literal.isUTF32()) {
1846 CharTy = Context.Char32Ty;
1847 Kind = StringLiteral::UTF32;
1848 } else if (Literal.isPascal()) {
1849 CharTy = Context.UnsignedCharTy;
1850 }
1851
1852 // Warn on initializing an array of char from a u8 string literal; this
1853 // becomes ill-formed in C++2a.
1854 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1855 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1856 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1857
1858 // Create removals for all 'u8' prefixes in the string literal(s). This
1859 // ensures C++2a compatibility (but may change the program behavior when
1860 // built by non-Clang compilers for which the execution character set is
1861 // not always UTF-8).
1862 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1863 SourceLocation RemovalDiagLoc;
1864 for (const Token &Tok : StringToks) {
1865 if (Tok.getKind() == tok::utf8_string_literal) {
1866 if (RemovalDiagLoc.isInvalid())
1867 RemovalDiagLoc = Tok.getLocation();
1868 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1869 Tok.getLocation(),
1870 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1871 getSourceManager(), getLangOpts())));
1872 }
1873 }
1874 Diag(RemovalDiagLoc, RemovalDiag);
1875 }
1876
1877 QualType StrTy =
1878 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1879
1880 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1881 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1882 Kind, Literal.Pascal, StrTy,
1883 &StringTokLocs[0],
1884 StringTokLocs.size());
1885 if (Literal.getUDSuffix().empty())
1886 return Lit;
1887
1888 // We're building a user-defined literal.
1889 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1890 SourceLocation UDSuffixLoc =
1891 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1892 Literal.getUDSuffixOffset());
1893
1894 // Make sure we're allowed user-defined literals here.
1895 if (!UDLScope)
1896 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1897
1898 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1899 // operator "" X (str, len)
1900 QualType SizeType = Context.getSizeType();
1901
1902 DeclarationName OpName =
1903 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1904 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1905 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1906
1907 QualType ArgTy[] = {
1908 Context.getArrayDecayedType(StrTy), SizeType
1909 };
1910
1911 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1912 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1913 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1914 /*AllowStringTemplatePack*/ true,
1915 /*DiagnoseMissing*/ true, Lit)) {
1916
1917 case LOLR_Cooked: {
1918 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1919 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1920 StringTokLocs[0]);
1921 Expr *Args[] = { Lit, LenArg };
1922
1923 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1924 }
1925
1926 case LOLR_Template: {
1927 TemplateArgumentListInfo ExplicitArgs;
1928 TemplateArgument Arg(Lit);
1929 TemplateArgumentLocInfo ArgInfo(Lit);
1930 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1931 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1932 &ExplicitArgs);
1933 }
1934
1935 case LOLR_StringTemplatePack: {
1936 TemplateArgumentListInfo ExplicitArgs;
1937
1938 unsigned CharBits = Context.getIntWidth(CharTy);
1939 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1940 llvm::APSInt Value(CharBits, CharIsUnsigned);
1941
1942 TemplateArgument TypeArg(CharTy);
1943 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1944 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1945
1946 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1947 Value = Lit->getCodeUnit(I);
1948 TemplateArgument Arg(Context, Value, CharTy);
1949 TemplateArgumentLocInfo ArgInfo;
1950 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1951 }
1952 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1953 &ExplicitArgs);
1954 }
1955 case LOLR_Raw:
1956 case LOLR_ErrorNoDiagnostic:
1957 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 1957)
;
1958 case LOLR_Error:
1959 return ExprError();
1960 }
1961 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 1961)
;
1962}
1963
1964DeclRefExpr *
1965Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1966 SourceLocation Loc,
1967 const CXXScopeSpec *SS) {
1968 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1969 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1970}
1971
1972DeclRefExpr *
1973Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1974 const DeclarationNameInfo &NameInfo,
1975 const CXXScopeSpec *SS, NamedDecl *FoundD,
1976 SourceLocation TemplateKWLoc,
1977 const TemplateArgumentListInfo *TemplateArgs) {
1978 NestedNameSpecifierLoc NNS =
1979 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1980 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1981 TemplateArgs);
1982}
1983
1984// CUDA/HIP: Check whether a captured reference variable is referencing a
1985// host variable in a device or host device lambda.
1986static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1987 VarDecl *VD) {
1988 if (!S.getLangOpts().CUDA || !VD->hasInit())
1989 return false;
1990 assert(VD->getType()->isReferenceType())(static_cast <bool> (VD->getType()->isReferenceType
()) ? void (0) : __assert_fail ("VD->getType()->isReferenceType()"
, "clang/lib/Sema/SemaExpr.cpp", 1990, __extension__ __PRETTY_FUNCTION__
))
;
1991
1992 // Check whether the reference variable is referencing a host variable.
1993 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1994 if (!DRE)
1995 return false;
1996 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1997 if (!Referee || !Referee->hasGlobalStorage() ||
1998 Referee->hasAttr<CUDADeviceAttr>())
1999 return false;
2000
2001 // Check whether the current function is a device or host device lambda.
2002 // Check whether the reference variable is a capture by getDeclContext()
2003 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2004 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2005 if (MD && MD->getParent()->isLambda() &&
2006 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2007 VD->getDeclContext() != MD)
2008 return true;
2009
2010 return false;
2011}
2012
2013NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2014 // A declaration named in an unevaluated operand never constitutes an odr-use.
2015 if (isUnevaluatedContext())
2016 return NOUR_Unevaluated;
2017
2018 // C++2a [basic.def.odr]p4:
2019 // A variable x whose name appears as a potentially-evaluated expression e
2020 // is odr-used by e unless [...] x is a reference that is usable in
2021 // constant expressions.
2022 // CUDA/HIP:
2023 // If a reference variable referencing a host variable is captured in a
2024 // device or host device lambda, the value of the referee must be copied
2025 // to the capture and the reference variable must be treated as odr-use
2026 // since the value of the referee is not known at compile time and must
2027 // be loaded from the captured.
2028 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2029 if (VD->getType()->isReferenceType() &&
2030 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2031 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2032 VD->isUsableInConstantExpressions(Context))
2033 return NOUR_Constant;
2034 }
2035
2036 // All remaining non-variable cases constitute an odr-use. For variables, we
2037 // need to wait and see how the expression is used.
2038 return NOUR_None;
2039}
2040
2041/// BuildDeclRefExpr - Build an expression that references a
2042/// declaration that does not require a closure capture.
2043DeclRefExpr *
2044Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2045 const DeclarationNameInfo &NameInfo,
2046 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2047 SourceLocation TemplateKWLoc,
2048 const TemplateArgumentListInfo *TemplateArgs) {
2049 bool RefersToCapturedVariable =
2050 isa<VarDecl>(D) &&
2051 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2052
2053 DeclRefExpr *E = DeclRefExpr::Create(
2054 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2055 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2056 MarkDeclRefReferenced(E);
2057
2058 // C++ [except.spec]p17:
2059 // An exception-specification is considered to be needed when:
2060 // - in an expression, the function is the unique lookup result or
2061 // the selected member of a set of overloaded functions.
2062 //
2063 // We delay doing this until after we've built the function reference and
2064 // marked it as used so that:
2065 // a) if the function is defaulted, we get errors from defining it before /
2066 // instead of errors from computing its exception specification, and
2067 // b) if the function is a defaulted comparison, we can use the body we
2068 // build when defining it as input to the exception specification
2069 // computation rather than computing a new body.
2070 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2071 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2072 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2073 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2074 }
2075 }
2076
2077 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2078 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2079 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2080 getCurFunction()->recordUseOfWeak(E);
2081
2082 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2083 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2084 FD = IFD->getAnonField();
2085 if (FD) {
2086 UnusedPrivateFields.remove(FD);
2087 // Just in case we're building an illegal pointer-to-member.
2088 if (FD->isBitField())
2089 E->setObjectKind(OK_BitField);
2090 }
2091
2092 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2093 // designates a bit-field.
2094 if (auto *BD = dyn_cast<BindingDecl>(D))
2095 if (auto *BE = BD->getBinding())
2096 E->setObjectKind(BE->getObjectKind());
2097
2098 return E;
2099}
2100
2101/// Decomposes the given name into a DeclarationNameInfo, its location, and
2102/// possibly a list of template arguments.
2103///
2104/// If this produces template arguments, it is permitted to call
2105/// DecomposeTemplateName.
2106///
2107/// This actually loses a lot of source location information for
2108/// non-standard name kinds; we should consider preserving that in
2109/// some way.
2110void
2111Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2112 TemplateArgumentListInfo &Buffer,
2113 DeclarationNameInfo &NameInfo,
2114 const TemplateArgumentListInfo *&TemplateArgs) {
2115 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2116 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2117 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2118
2119 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2120 Id.TemplateId->NumArgs);
2121 translateTemplateArguments(TemplateArgsPtr, Buffer);
2122
2123 TemplateName TName = Id.TemplateId->Template.get();
2124 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2125 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2126 TemplateArgs = &Buffer;
2127 } else {
2128 NameInfo = GetNameFromUnqualifiedId(Id);
2129 TemplateArgs = nullptr;
2130 }
2131}
2132
2133static void emitEmptyLookupTypoDiagnostic(
2134 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2135 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2136 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2137 DeclContext *Ctx =
2138 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2139 if (!TC) {
2140 // Emit a special diagnostic for failed member lookups.
2141 // FIXME: computing the declaration context might fail here (?)
2142 if (Ctx)
2143 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2144 << SS.getRange();
2145 else
2146 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2147 return;
2148 }
2149
2150 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2151 bool DroppedSpecifier =
2152 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2153 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2154 ? diag::note_implicit_param_decl
2155 : diag::note_previous_decl;
2156 if (!Ctx)
2157 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2158 SemaRef.PDiag(NoteID));
2159 else
2160 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2161 << Typo << Ctx << DroppedSpecifier
2162 << SS.getRange(),
2163 SemaRef.PDiag(NoteID));
2164}
2165
2166/// Diagnose a lookup that found results in an enclosing class during error
2167/// recovery. This usually indicates that the results were found in a dependent
2168/// base class that could not be searched as part of a template definition.
2169/// Always issues a diagnostic (though this may be only a warning in MS
2170/// compatibility mode).
2171///
2172/// Return \c true if the error is unrecoverable, or \c false if the caller
2173/// should attempt to recover using these lookup results.
2174bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2175 // During a default argument instantiation the CurContext points
2176 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2177 // function parameter list, hence add an explicit check.
2178 bool isDefaultArgument =
2179 !CodeSynthesisContexts.empty() &&
2180 CodeSynthesisContexts.back().Kind ==
2181 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2182 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2183 bool isInstance = CurMethod && CurMethod->isInstance() &&
2184 R.getNamingClass() == CurMethod->getParent() &&
2185 !isDefaultArgument;
2186
2187 // There are two ways we can find a class-scope declaration during template
2188 // instantiation that we did not find in the template definition: if it is a
2189 // member of a dependent base class, or if it is declared after the point of
2190 // use in the same class. Distinguish these by comparing the class in which
2191 // the member was found to the naming class of the lookup.
2192 unsigned DiagID = diag::err_found_in_dependent_base;
2193 unsigned NoteID = diag::note_member_declared_at;
2194 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2195 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2196 : diag::err_found_later_in_class;
2197 } else if (getLangOpts().MSVCCompat) {
2198 DiagID = diag::ext_found_in_dependent_base;
2199 NoteID = diag::note_dependent_member_use;
2200 }
2201
2202 if (isInstance) {
2203 // Give a code modification hint to insert 'this->'.
2204 Diag(R.getNameLoc(), DiagID)
2205 << R.getLookupName()
2206 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2207 CheckCXXThisCapture(R.getNameLoc());
2208 } else {
2209 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2210 // they're not shadowed).
2211 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2212 }
2213
2214 for (NamedDecl *D : R)
2215 Diag(D->getLocation(), NoteID);
2216
2217 // Return true if we are inside a default argument instantiation
2218 // and the found name refers to an instance member function, otherwise
2219 // the caller will try to create an implicit member call and this is wrong
2220 // for default arguments.
2221 //
2222 // FIXME: Is this special case necessary? We could allow the caller to
2223 // diagnose this.
2224 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2225 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2226 return true;
2227 }
2228
2229 // Tell the callee to try to recover.
2230 return false;
2231}
2232
2233/// Diagnose an empty lookup.
2234///
2235/// \return false if new lookup candidates were found
2236bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2237 CorrectionCandidateCallback &CCC,
2238 TemplateArgumentListInfo *ExplicitTemplateArgs,
2239 ArrayRef<Expr *> Args, TypoExpr **Out) {
2240 DeclarationName Name = R.getLookupName();
2241
2242 unsigned diagnostic = diag::err_undeclared_var_use;
2243 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2244 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2245 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2246 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2247 diagnostic = diag::err_undeclared_use;
2248 diagnostic_suggest = diag::err_undeclared_use_suggest;
2249 }
2250
2251 // If the original lookup was an unqualified lookup, fake an
2252 // unqualified lookup. This is useful when (for example) the
2253 // original lookup would not have found something because it was a
2254 // dependent name.
2255 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2256 while (DC) {
2257 if (isa<CXXRecordDecl>(DC)) {
2258 LookupQualifiedName(R, DC);
2259
2260 if (!R.empty()) {
2261 // Don't give errors about ambiguities in this lookup.
2262 R.suppressDiagnostics();
2263
2264 // If there's a best viable function among the results, only mention
2265 // that one in the notes.
2266 OverloadCandidateSet Candidates(R.getNameLoc(),
2267 OverloadCandidateSet::CSK_Normal);
2268 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2269 OverloadCandidateSet::iterator Best;
2270 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2271 OR_Success) {
2272 R.clear();
2273 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2274 R.resolveKind();
2275 }
2276
2277 return DiagnoseDependentMemberLookup(R);
2278 }
2279
2280 R.clear();
2281 }
2282
2283 DC = DC->getLookupParent();
2284 }
2285
2286 // We didn't find anything, so try to correct for a typo.
2287 TypoCorrection Corrected;
2288 if (S && Out) {
2289 SourceLocation TypoLoc = R.getNameLoc();
2290 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", 2291, __extension__ __PRETTY_FUNCTION__
))
2291 "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", 2291, __extension__ __PRETTY_FUNCTION__
))
;
2292 *Out = CorrectTypoDelayed(
2293 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2294 [=](const TypoCorrection &TC) {
2295 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2296 diagnostic, diagnostic_suggest);
2297 },
2298 nullptr, CTK_ErrorRecovery);
2299 if (*Out)
2300 return true;
2301 } else if (S &&
2302 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2303 S, &SS, CCC, CTK_ErrorRecovery))) {
2304 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2305 bool DroppedSpecifier =
2306 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2307 R.setLookupName(Corrected.getCorrection());
2308
2309 bool AcceptableWithRecovery = false;
2310 bool AcceptableWithoutRecovery = false;
2311 NamedDecl *ND = Corrected.getFoundDecl();
2312 if (ND) {
2313 if (Corrected.isOverloaded()) {
2314 OverloadCandidateSet OCS(R.getNameLoc(),
2315 OverloadCandidateSet::CSK_Normal);
2316 OverloadCandidateSet::iterator Best;
2317 for (NamedDecl *CD : Corrected) {
2318 if (FunctionTemplateDecl *FTD =
2319 dyn_cast<FunctionTemplateDecl>(CD))
2320 AddTemplateOverloadCandidate(
2321 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2322 Args, OCS);
2323 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2324 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2325 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2326 Args, OCS);
2327 }
2328 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2329 case OR_Success:
2330 ND = Best->FoundDecl;
2331 Corrected.setCorrectionDecl(ND);
2332 break;
2333 default:
2334 // FIXME: Arbitrarily pick the first declaration for the note.
2335 Corrected.setCorrectionDecl(ND);
2336 break;
2337 }
2338 }
2339 R.addDecl(ND);
2340 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2341 CXXRecordDecl *Record = nullptr;
2342 if (Corrected.getCorrectionSpecifier()) {
2343 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2344 Record = Ty->getAsCXXRecordDecl();
2345 }
2346 if (!Record)
2347 Record = cast<CXXRecordDecl>(
2348 ND->getDeclContext()->getRedeclContext());
2349 R.setNamingClass(Record);
2350 }
2351
2352 auto *UnderlyingND = ND->getUnderlyingDecl();
2353 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2354 isa<FunctionTemplateDecl>(UnderlyingND);
2355 // FIXME: If we ended up with a typo for a type name or
2356 // Objective-C class name, we're in trouble because the parser
2357 // is in the wrong place to recover. Suggest the typo
2358 // correction, but don't make it a fix-it since we're not going
2359 // to recover well anyway.
2360 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2361 getAsTypeTemplateDecl(UnderlyingND) ||
2362 isa<ObjCInterfaceDecl>(UnderlyingND);
2363 } else {
2364 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2365 // because we aren't able to recover.
2366 AcceptableWithoutRecovery = true;
2367 }
2368
2369 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2370 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2371 ? diag::note_implicit_param_decl
2372 : diag::note_previous_decl;
2373 if (SS.isEmpty())
2374 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2375 PDiag(NoteID), AcceptableWithRecovery);
2376 else
2377 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2378 << Name << computeDeclContext(SS, false)
2379 << DroppedSpecifier << SS.getRange(),
2380 PDiag(NoteID), AcceptableWithRecovery);
2381
2382 // Tell the callee whether to try to recover.
2383 return !AcceptableWithRecovery;
2384 }
2385 }
2386 R.clear();
2387
2388 // Emit a special diagnostic for failed member lookups.
2389 // FIXME: computing the declaration context might fail here (?)
2390 if (!SS.isEmpty()) {
2391 Diag(R.getNameLoc(), diag::err_no_member)
2392 << Name << computeDeclContext(SS, false)
2393 << SS.getRange();
2394 return true;
2395 }
2396
2397 // Give up, we can't recover.
2398 Diag(R.getNameLoc(), diagnostic) << Name;
2399 return true;
2400}
2401
2402/// In Microsoft mode, if we are inside a template class whose parent class has
2403/// dependent base classes, and we can't resolve an unqualified identifier, then
2404/// assume the identifier is a member of a dependent base class. We can only
2405/// recover successfully in static methods, instance methods, and other contexts
2406/// where 'this' is available. This doesn't precisely match MSVC's
2407/// instantiation model, but it's close enough.
2408static Expr *
2409recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2410 DeclarationNameInfo &NameInfo,
2411 SourceLocation TemplateKWLoc,
2412 const TemplateArgumentListInfo *TemplateArgs) {
2413 // Only try to recover from lookup into dependent bases in static methods or
2414 // contexts where 'this' is available.
2415 QualType ThisType = S.getCurrentThisType();
2416 const CXXRecordDecl *RD = nullptr;
2417 if (!ThisType.isNull())
2418 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2419 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2420 RD = MD->getParent();
2421 if (!RD || !RD->hasAnyDependentBases())
2422 return nullptr;
2423
2424 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2425 // is available, suggest inserting 'this->' as a fixit.
2426 SourceLocation Loc = NameInfo.getLoc();
2427 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2428 DB << NameInfo.getName() << RD;
2429
2430 if (!ThisType.isNull()) {
2431 DB << FixItHint::CreateInsertion(Loc, "this->");
2432 return CXXDependentScopeMemberExpr::Create(
2433 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2434 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2435 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2436 }
2437
2438 // Synthesize a fake NNS that points to the derived class. This will
2439 // perform name lookup during template instantiation.
2440 CXXScopeSpec SS;
2441 auto *NNS =
2442 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2443 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2444 return DependentScopeDeclRefExpr::Create(
2445 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2446 TemplateArgs);
2447}
2448
2449ExprResult
2450Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2451 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2452 bool HasTrailingLParen, bool IsAddressOfOperand,
2453 CorrectionCandidateCallback *CCC,
2454 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2455 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", 2456, __extension__ __PRETTY_FUNCTION__
))
2456 "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", 2456, __extension__ __PRETTY_FUNCTION__
))
;
2457 if (SS.isInvalid())
2458 return ExprError();
2459
2460 TemplateArgumentListInfo TemplateArgsBuffer;
2461
2462 // Decompose the UnqualifiedId into the following data.
2463 DeclarationNameInfo NameInfo;
2464 const TemplateArgumentListInfo *TemplateArgs;
2465 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2466
2467 DeclarationName Name = NameInfo.getName();
2468 IdentifierInfo *II = Name.getAsIdentifierInfo();
2469 SourceLocation NameLoc = NameInfo.getLoc();
2470
2471 if (II && II->isEditorPlaceholder()) {
2472 // FIXME: When typed placeholders are supported we can create a typed
2473 // placeholder expression node.
2474 return ExprError();
2475 }
2476
2477 // C++ [temp.dep.expr]p3:
2478 // An id-expression is type-dependent if it contains:
2479 // -- an identifier that was declared with a dependent type,
2480 // (note: handled after lookup)
2481 // -- a template-id that is dependent,
2482 // (note: handled in BuildTemplateIdExpr)
2483 // -- a conversion-function-id that specifies a dependent type,
2484 // -- a nested-name-specifier that contains a class-name that
2485 // names a dependent type.
2486 // Determine whether this is a member of an unknown specialization;
2487 // we need to handle these differently.
2488 bool DependentID = false;
2489 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2490 Name.getCXXNameType()->isDependentType()) {
2491 DependentID = true;
2492 } else if (SS.isSet()) {
2493 if (DeclContext *DC = computeDeclContext(SS, false)) {
2494 if (RequireCompleteDeclContext(SS, DC))
2495 return ExprError();
2496 } else {
2497 DependentID = true;
2498 }
2499 }
2500
2501 if (DependentID)
2502 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2503 IsAddressOfOperand, TemplateArgs);
2504
2505 // Perform the required lookup.
2506 LookupResult R(*this, NameInfo,
2507 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2508 ? LookupObjCImplicitSelfParam
2509 : LookupOrdinaryName);
2510 if (TemplateKWLoc.isValid() || TemplateArgs) {
2511 // Lookup the template name again to correctly establish the context in
2512 // which it was found. This is really unfortunate as we already did the
2513 // lookup to determine that it was a template name in the first place. If
2514 // this becomes a performance hit, we can work harder to preserve those
2515 // results until we get here but it's likely not worth it.
2516 bool MemberOfUnknownSpecialization;
2517 AssumedTemplateKind AssumedTemplate;
2518 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2519 MemberOfUnknownSpecialization, TemplateKWLoc,
2520 &AssumedTemplate))
2521 return ExprError();
2522
2523 if (MemberOfUnknownSpecialization ||
2524 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2525 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2526 IsAddressOfOperand, TemplateArgs);
2527 } else {
2528 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2529 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2530
2531 // If the result might be in a dependent base class, this is a dependent
2532 // id-expression.
2533 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2534 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2535 IsAddressOfOperand, TemplateArgs);
2536
2537 // If this reference is in an Objective-C method, then we need to do
2538 // some special Objective-C lookup, too.
2539 if (IvarLookupFollowUp) {
2540 ExprResult E(LookupInObjCMethod(R, S, II, true));
2541 if (E.isInvalid())
2542 return ExprError();
2543
2544 if (Expr *Ex = E.getAs<Expr>())
2545 return Ex;
2546 }
2547 }
2548
2549 if (R.isAmbiguous())
2550 return ExprError();
2551
2552 // This could be an implicitly declared function reference (legal in C90,
2553 // extension in C99, forbidden in C++).
2554 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2555 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2556 if (D) R.addDecl(D);
2557 }
2558
2559 // Determine whether this name might be a candidate for
2560 // argument-dependent lookup.
2561 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2562
2563 if (R.empty() && !ADL) {
2564 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2565 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2566 TemplateKWLoc, TemplateArgs))
2567 return E;
2568 }
2569
2570 // Don't diagnose an empty lookup for inline assembly.
2571 if (IsInlineAsmIdentifier)
2572 return ExprError();
2573
2574 // If this name wasn't predeclared and if this is not a function
2575 // call, diagnose the problem.
2576 TypoExpr *TE = nullptr;
2577 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2578 : nullptr);
2579 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2580 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", 2581, __extension__ __PRETTY_FUNCTION__
))
2581 "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", 2581, __extension__ __PRETTY_FUNCTION__
))
;
2582 if (CCC) {
2583 // Make sure the callback knows what the typo being diagnosed is.
2584 CCC->setTypoName(II);
2585 if (SS.isValid())
2586 CCC->setTypoNNS(SS.getScopeRep());
2587 }
2588 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2589 // a template name, but we happen to have always already looked up the name
2590 // before we get here if it must be a template name.
2591 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2592 None, &TE)) {
2593 if (TE && KeywordReplacement) {
2594 auto &State = getTypoExprState(TE);
2595 auto BestTC = State.Consumer->getNextCorrection();
2596 if (BestTC.isKeyword()) {
2597 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2598 if (State.DiagHandler)
2599 State.DiagHandler(BestTC);
2600 KeywordReplacement->startToken();
2601 KeywordReplacement->setKind(II->getTokenID());
2602 KeywordReplacement->setIdentifierInfo(II);
2603 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2604 // Clean up the state associated with the TypoExpr, since it has
2605 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2606 clearDelayedTypo(TE);
2607 // Signal that a correction to a keyword was performed by returning a
2608 // valid-but-null ExprResult.
2609 return (Expr*)nullptr;
2610 }
2611 State.Consumer->resetCorrectionStream();
2612 }
2613 return TE ? TE : ExprError();
2614 }
2615
2616 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", 2617, __extension__ __PRETTY_FUNCTION__
))
2617 "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", 2617, __extension__ __PRETTY_FUNCTION__
))
;
2618
2619 // If we found an Objective-C instance variable, let
2620 // LookupInObjCMethod build the appropriate expression to
2621 // reference the ivar.
2622 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2623 R.clear();
2624 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2625 // In a hopelessly buggy code, Objective-C instance variable
2626 // lookup fails and no expression will be built to reference it.
2627 if (!E.isInvalid() && !E.get())
2628 return ExprError();
2629 return E;
2630 }
2631 }
2632
2633 // This is guaranteed from this point on.
2634 assert(!R.empty() || ADL)(static_cast <bool> (!R.empty() || ADL) ? void (0) : __assert_fail
("!R.empty() || ADL", "clang/lib/Sema/SemaExpr.cpp", 2634, __extension__
__PRETTY_FUNCTION__))
;
2635
2636 // Check whether this might be a C++ implicit instance member access.
2637 // C++ [class.mfct.non-static]p3:
2638 // When an id-expression that is not part of a class member access
2639 // syntax and not used to form a pointer to member is used in the
2640 // body of a non-static member function of class X, if name lookup
2641 // resolves the name in the id-expression to a non-static non-type
2642 // member of some class C, the id-expression is transformed into a
2643 // class member access expression using (*this) as the
2644 // postfix-expression to the left of the . operator.
2645 //
2646 // But we don't actually need to do this for '&' operands if R
2647 // resolved to a function or overloaded function set, because the
2648 // expression is ill-formed if it actually works out to be a
2649 // non-static member function:
2650 //
2651 // C++ [expr.ref]p4:
2652 // Otherwise, if E1.E2 refers to a non-static member function. . .
2653 // [t]he expression can be used only as the left-hand operand of a
2654 // member function call.
2655 //
2656 // There are other safeguards against such uses, but it's important
2657 // to get this right here so that we don't end up making a
2658 // spuriously dependent expression if we're inside a dependent
2659 // instance method.
2660 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2661 bool MightBeImplicitMember;
2662 if (!IsAddressOfOperand)
2663 MightBeImplicitMember = true;
2664 else if (!SS.isEmpty())
2665 MightBeImplicitMember = false;
2666 else if (R.isOverloadedResult())
2667 MightBeImplicitMember = false;
2668 else if (R.isUnresolvableResult())
2669 MightBeImplicitMember = true;
2670 else
2671 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2672 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2673 isa<MSPropertyDecl>(R.getFoundDecl());
2674
2675 if (MightBeImplicitMember)
2676 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2677 R, TemplateArgs, S);
2678 }
2679
2680 if (TemplateArgs || TemplateKWLoc.isValid()) {
2681
2682 // In C++1y, if this is a variable template id, then check it
2683 // in BuildTemplateIdExpr().
2684 // The single lookup result must be a variable template declaration.
2685 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2686 Id.TemplateId->Kind == TNK_Var_template) {
2687 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", 2688, __extension__ __PRETTY_FUNCTION__
))
2688 "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", 2688, __extension__ __PRETTY_FUNCTION__
))
;
2689 }
2690
2691 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2692 }
2693
2694 return BuildDeclarationNameExpr(SS, R, ADL);
2695}
2696
2697/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2698/// declaration name, generally during template instantiation.
2699/// There's a large number of things which don't need to be done along
2700/// this path.
2701ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2702 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2703 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2704 DeclContext *DC = computeDeclContext(SS, false);
2705 if (!DC)
2706 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2707 NameInfo, /*TemplateArgs=*/nullptr);
2708
2709 if (RequireCompleteDeclContext(SS, DC))
2710 return ExprError();
2711
2712 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2713 LookupQualifiedName(R, DC);
2714
2715 if (R.isAmbiguous())
2716 return ExprError();
2717
2718 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2719 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2720 NameInfo, /*TemplateArgs=*/nullptr);
2721
2722 if (R.empty()) {
2723 // Don't diagnose problems with invalid record decl, the secondary no_member
2724 // diagnostic during template instantiation is likely bogus, e.g. if a class
2725 // is invalid because it's derived from an invalid base class, then missing
2726 // members were likely supposed to be inherited.
2727 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2728 if (CD->isInvalidDecl())
2729 return ExprError();
2730 Diag(NameInfo.getLoc(), diag::err_no_member)
2731 << NameInfo.getName() << DC << SS.getRange();
2732 return ExprError();
2733 }
2734
2735 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2736 // Diagnose a missing typename if this resolved unambiguously to a type in
2737 // a dependent context. If we can recover with a type, downgrade this to
2738 // a warning in Microsoft compatibility mode.
2739 unsigned DiagID = diag::err_typename_missing;
2740 if (RecoveryTSI && getLangOpts().MSVCCompat)
2741 DiagID = diag::ext_typename_missing;
2742 SourceLocation Loc = SS.getBeginLoc();
2743 auto D = Diag(Loc, DiagID);
2744 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2745 << SourceRange(Loc, NameInfo.getEndLoc());
2746
2747 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2748 // context.
2749 if (!RecoveryTSI)
2750 return ExprError();
2751
2752 // Only issue the fixit if we're prepared to recover.
2753 D << FixItHint::CreateInsertion(Loc, "typename ");
2754
2755 // Recover by pretending this was an elaborated type.
2756 QualType Ty = Context.getTypeDeclType(TD);
2757 TypeLocBuilder TLB;
2758 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2759
2760 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2761 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2762 QTL.setElaboratedKeywordLoc(SourceLocation());
2763 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2764
2765 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2766
2767 return ExprEmpty();
2768 }
2769
2770 // Defend against this resolving to an implicit member access. We usually
2771 // won't get here if this might be a legitimate a class member (we end up in
2772 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2773 // a pointer-to-member or in an unevaluated context in C++11.
2774 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2775 return BuildPossibleImplicitMemberExpr(SS,
2776 /*TemplateKWLoc=*/SourceLocation(),
2777 R, /*TemplateArgs=*/nullptr, S);
2778
2779 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2780}
2781
2782/// The parser has read a name in, and Sema has detected that we're currently
2783/// inside an ObjC method. Perform some additional checks and determine if we
2784/// should form a reference to an ivar.
2785///
2786/// Ideally, most of this would be done by lookup, but there's
2787/// actually quite a lot of extra work involved.
2788DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2789 IdentifierInfo *II) {
2790 SourceLocation Loc = Lookup.getNameLoc();
2791 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2792
2793 // Check for error condition which is already reported.
2794 if (!CurMethod)
2795 return DeclResult(true);
2796
2797 // There are two cases to handle here. 1) scoped lookup could have failed,
2798 // in which case we should look for an ivar. 2) scoped lookup could have
2799 // found a decl, but that decl is outside the current instance method (i.e.
2800 // a global variable). In these two cases, we do a lookup for an ivar with
2801 // this name, if the lookup sucedes, we replace it our current decl.
2802
2803 // If we're in a class method, we don't normally want to look for
2804 // ivars. But if we don't find anything else, and there's an
2805 // ivar, that's an error.
2806 bool IsClassMethod = CurMethod->isClassMethod();
2807
2808 bool LookForIvars;
2809 if (Lookup.empty())
2810 LookForIvars = true;
2811 else if (IsClassMethod)
2812 LookForIvars = false;
2813 else
2814 LookForIvars = (Lookup.isSingleResult() &&
2815 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2816 ObjCInterfaceDecl *IFace = nullptr;
2817 if (LookForIvars) {
2818 IFace = CurMethod->getClassInterface();
2819 ObjCInterfaceDecl *ClassDeclared;
2820 ObjCIvarDecl *IV = nullptr;
2821 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2822 // Diagnose using an ivar in a class method.
2823 if (IsClassMethod) {
2824 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2825 return DeclResult(true);
2826 }
2827
2828 // Diagnose the use of an ivar outside of the declaring class.
2829 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2830 !declaresSameEntity(ClassDeclared, IFace) &&
2831 !getLangOpts().DebuggerSupport)
2832 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2833
2834 // Success.
2835 return IV;
2836 }
2837 } else if (CurMethod->isInstanceMethod()) {
2838 // We should warn if a local variable hides an ivar.
2839 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2840 ObjCInterfaceDecl *ClassDeclared;
2841 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2842 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2843 declaresSameEntity(IFace, ClassDeclared))
2844 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2845 }
2846 }
2847 } else if (Lookup.isSingleResult() &&
2848 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2849 // If accessing a stand-alone ivar in a class method, this is an error.
2850 if (const ObjCIvarDecl *IV =
2851 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2852 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2853 return DeclResult(true);
2854 }
2855 }
2856
2857 // Didn't encounter an error, didn't find an ivar.
2858 return DeclResult(false);
2859}
2860
2861ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2862 ObjCIvarDecl *IV) {
2863 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2864 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", 2865, __extension__ __PRETTY_FUNCTION__
))
2865 "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", 2865, __extension__ __PRETTY_FUNCTION__
))
;
2866
2867 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2868 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", 2868, __extension__ __PRETTY_FUNCTION__
))
;
2869
2870 // If we're referencing an invalid decl, just return this as a silent
2871 // error node. The error diagnostic was already emitted on the decl.
2872 if (IV->isInvalidDecl())
2873 return ExprError();
2874
2875 // Check if referencing a field with __attribute__((deprecated)).
2876 if (DiagnoseUseOfDecl(IV, Loc))
2877 return ExprError();
2878
2879 // FIXME: This should use a new expr for a direct reference, don't
2880 // turn this into Self->ivar, just return a BareIVarExpr or something.
2881 IdentifierInfo &II = Context.Idents.get("self");
2882 UnqualifiedId SelfName;
2883 SelfName.setImplicitSelfParam(&II);
2884 CXXScopeSpec SelfScopeSpec;
2885 SourceLocation TemplateKWLoc;
2886 ExprResult SelfExpr =
2887 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2888 /*HasTrailingLParen=*/false,
2889 /*IsAddressOfOperand=*/false);
2890 if (SelfExpr.isInvalid())
2891 return ExprError();
2892
2893 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2894 if (SelfExpr.isInvalid())
2895 return ExprError();
2896
2897 MarkAnyDeclReferenced(Loc, IV, true);
2898
2899 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2900 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2901 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2902 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2903
2904 ObjCIvarRefExpr *Result = new (Context)
2905 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2906 IV->getLocation(), SelfExpr.get(), true, true);
2907
2908 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2909 if (!isUnevaluatedContext() &&
2910 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2911 getCurFunction()->recordUseOfWeak(Result);
2912 }
2913 if (getLangOpts().ObjCAutoRefCount)
2914 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2915 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2916
2917 return Result;
2918}
2919
2920/// The parser has read a name in, and Sema has detected that we're currently
2921/// inside an ObjC method. Perform some additional checks and determine if we
2922/// should form a reference to an ivar. If so, build an expression referencing
2923/// that ivar.
2924ExprResult
2925Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2926 IdentifierInfo *II, bool AllowBuiltinCreation) {
2927 // FIXME: Integrate this lookup step into LookupParsedName.
2928 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2929 if (Ivar.isInvalid())
2930 return ExprError();
2931 if (Ivar.isUsable())
2932 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2933 cast<ObjCIvarDecl>(Ivar.get()));
2934
2935 if (Lookup.empty() && II && AllowBuiltinCreation)
2936 LookupBuiltin(Lookup);
2937
2938 // Sentinel value saying that we didn't do anything special.
2939 return ExprResult(false);
2940}
2941
2942/// Cast a base object to a member's actual type.
2943///
2944/// There are two relevant checks:
2945///
2946/// C++ [class.access.base]p7:
2947///
2948/// If a class member access operator [...] is used to access a non-static
2949/// data member or non-static member function, the reference is ill-formed if
2950/// the left operand [...] cannot be implicitly converted to a pointer to the
2951/// naming class of the right operand.
2952///
2953/// C++ [expr.ref]p7:
2954///
2955/// If E2 is a non-static data member or a non-static member function, the
2956/// program is ill-formed if the class of which E2 is directly a member is an
2957/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
2958///
2959/// Note that the latter check does not consider access; the access of the
2960/// "real" base class is checked as appropriate when checking the access of the
2961/// member name.
2962ExprResult
2963Sema::PerformObjectMemberConversion(Expr *From,
2964 NestedNameSpecifier *Qualifier,
2965 NamedDecl *FoundDecl,
2966 NamedDecl *Member) {
2967 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2968 if (!RD)
2969 return From;
2970
2971 QualType DestRecordType;
2972 QualType DestType;
2973 QualType FromRecordType;
2974 QualType FromType = From->getType();
2975 bool PointerConversions = false;
2976 if (isa<FieldDecl>(Member)) {
2977 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2978 auto FromPtrType = FromType->getAs<PointerType>();
2979 DestRecordType = Context.getAddrSpaceQualType(
2980 DestRecordType, FromPtrType
2981 ? FromType->getPointeeType().getAddressSpace()
2982 : FromType.getAddressSpace());
2983
2984 if (FromPtrType) {
2985 DestType = Context.getPointerType(DestRecordType);
2986 FromRecordType = FromPtrType->getPointeeType();
2987 PointerConversions = true;
2988 } else {
2989 DestType = DestRecordType;
2990 FromRecordType = FromType;
2991 }
2992 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2993 if (Method->isStatic())
2994 return From;
2995
2996 DestType = Method->getThisType();
2997 DestRecordType = DestType->getPointeeType();
2998
2999 if (FromType->getAs<PointerType>()) {
3000 FromRecordType = FromType->getPointeeType();
3001 PointerConversions = true;
3002 } else {
3003 FromRecordType = FromType;
3004 DestType = DestRecordType;
3005 }
3006
3007 LangAS FromAS = FromRecordType.getAddressSpace();
3008 LangAS DestAS = DestRecordType.getAddressSpace();
3009 if (FromAS != DestAS) {
3010 QualType FromRecordTypeWithoutAS =
3011 Context.removeAddrSpaceQualType(FromRecordType);
3012 QualType FromTypeWithDestAS =
3013 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3014 if (PointerConversions)
3015 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3016 From = ImpCastExprToType(From, FromTypeWithDestAS,
3017 CK_AddressSpaceConversion, From->getValueKind())
3018 .get();
3019 }
3020 } else {
3021 // No conversion necessary.
3022 return From;
3023 }
3024
3025 if (DestType->isDependentType() || FromType->isDependentType())
3026 return From;
3027
3028 // If the unqualified types are the same, no conversion is necessary.
3029 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3030 return From;
3031
3032 SourceRange FromRange = From->getSourceRange();
3033 SourceLocation FromLoc = FromRange.getBegin();
3034
3035 ExprValueKind VK = From->getValueKind();
3036
3037 // C++ [class.member.lookup]p8:
3038 // [...] Ambiguities can often be resolved by qualifying a name with its
3039 // class name.
3040 //
3041 // If the member was a qualified name and the qualified referred to a
3042 // specific base subobject type, we'll cast to that intermediate type
3043 // first and then to the object in which the member is declared. That allows
3044 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3045 //
3046 // class Base { public: int x; };
3047 // class Derived1 : public Base { };
3048 // class Derived2 : public Base { };
3049 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3050 //
3051 // void VeryDerived::f() {
3052 // x = 17; // error: ambiguous base subobjects
3053 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3054 // }
3055 if (Qualifier && Qualifier->getAsType()) {
3056 QualType QType = QualType(Qualifier->getAsType(), 0);
3057 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", 3057, __extension__ __PRETTY_FUNCTION__
))
;
3058
3059 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3060
3061 // In C++98, the qualifier type doesn't actually have to be a base
3062 // type of the object type, in which case we just ignore it.
3063 // Otherwise build the appropriate casts.
3064 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3065 CXXCastPath BasePath;
3066 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3067 FromLoc, FromRange, &BasePath))
3068 return ExprError();
3069
3070 if (PointerConversions)
3071 QType = Context.getPointerType(QType);
3072 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3073 VK, &BasePath).get();
3074
3075 FromType = QType;
3076 FromRecordType = QRecordType;
3077
3078 // If the qualifier type was the same as the destination type,
3079 // we're done.
3080 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3081 return From;
3082 }
3083 }
3084
3085 CXXCastPath BasePath;
3086 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3087 FromLoc, FromRange, &BasePath,
3088 /*IgnoreAccess=*/true))
3089 return ExprError();
3090
3091 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3092 VK, &BasePath);
3093}
3094
3095bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3096 const LookupResult &R,
3097 bool HasTrailingLParen) {
3098 // Only when used directly as the postfix-expression of a call.
3099 if (!HasTrailingLParen)
3100 return false;
3101
3102 // Never if a scope specifier was provided.
3103 if (SS.isSet())
3104 return false;
3105
3106 // Only in C++ or ObjC++.
3107 if (!getLangOpts().CPlusPlus)
3108 return false;
3109
3110 // Turn off ADL when we find certain kinds of declarations during
3111 // normal lookup:
3112 for (NamedDecl *D : R) {
3113 // C++0x [basic.lookup.argdep]p3:
3114 // -- a declaration of a class member
3115 // Since using decls preserve this property, we check this on the
3116 // original decl.
3117 if (D->isCXXClassMember())
3118 return false;
3119
3120 // C++0x [basic.lookup.argdep]p3:
3121 // -- a block-scope function declaration that is not a
3122 // using-declaration
3123 // NOTE: we also trigger this for function templates (in fact, we
3124 // don't check the decl type at all, since all other decl types
3125 // turn off ADL anyway).
3126 if (isa<UsingShadowDecl>(D))
3127 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3128 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3129 return false;
3130
3131 // C++0x [basic.lookup.argdep]p3:
3132 // -- a declaration that is neither a function or a function
3133 // template
3134 // And also for builtin functions.
3135 if (isa<FunctionDecl>(D)) {
3136 FunctionDecl *FDecl = cast<FunctionDecl>(D);
3137
3138 // But also builtin functions.
3139 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3140 return false;
3141 } else if (!isa<FunctionTemplateDecl>(D))
3142 return false;
3143 }
3144
3145 return true;
3146}
3147
3148
3149/// Diagnoses obvious problems with the use of the given declaration
3150/// as an expression. This is only actually called for lookups that
3151/// were not overloaded, and it doesn't promise that the declaration
3152/// will in fact be used.
3153static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3154 if (D->isInvalidDecl())
3155 return true;
3156
3157 if (isa<TypedefNameDecl>(D)) {
3158 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3159 return true;
3160 }
3161
3162 if (isa<ObjCInterfaceDecl>(D)) {
3163 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3164 return true;
3165 }
3166
3167 if (isa<NamespaceDecl>(D)) {
3168 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3169 return true;
3170 }
3171
3172 return false;
3173}
3174
3175// Certain multiversion types should be treated as overloaded even when there is
3176// only one result.
3177static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3178 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", 3178, __extension__ __PRETTY_FUNCTION__
))
;
3179 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3180 return FD &&
3181 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3182}
3183
3184ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3185 LookupResult &R, bool NeedsADL,
3186 bool AcceptInvalidDecl) {
3187 // If this is a single, fully-resolved result and we don't need ADL,
3188 // just build an ordinary singleton decl ref.
3189 if (!NeedsADL && R.isSingleResult() &&
3190 !R.getAsSingle<FunctionTemplateDecl>() &&
3191 !ShouldLookupResultBeMultiVersionOverload(R))
3192 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3193 R.getRepresentativeDecl(), nullptr,
3194 AcceptInvalidDecl);
3195
3196 // We only need to check the declaration if there's exactly one
3197 // result, because in the overloaded case the results can only be
3198 // functions and function templates.
3199 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3200 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3201 return ExprError();
3202
3203 // Otherwise, just build an unresolved lookup expression. Suppress
3204 // any lookup-related diagnostics; we'll hash these out later, when
3205 // we've picked a target.
3206 R.suppressDiagnostics();
3207
3208 UnresolvedLookupExpr *ULE
3209 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3210 SS.getWithLocInContext(Context),
3211 R.getLookupNameInfo(),
3212 NeedsADL, R.isOverloadedResult(),
3213 R.begin(), R.end());
3214
3215 return ULE;
3216}
3217
3218static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3219 ValueDecl *var);
3220
3221/// Complete semantic analysis for a reference to the given declaration.
3222ExprResult Sema::BuildDeclarationNameExpr(
3223 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3224 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3225 bool AcceptInvalidDecl) {
3226 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", 3226, __extension__ __PRETTY_FUNCTION__
))
;
3227 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", 3228, __extension__ __PRETTY_FUNCTION__
))
3228 "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", 3228, __extension__ __PRETTY_FUNCTION__
))
;
3229
3230 SourceLocation Loc = NameInfo.getLoc();
3231 if (CheckDeclInExpr(*this, Loc, D)) {
3232 // Recovery from invalid cases (e.g. D is an invalid Decl).
3233 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3234 // diagnostics, as invalid decls use int as a fallback type.
3235 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3236 }
3237
3238 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3239 // Specifically diagnose references to class templates that are missing
3240 // a template argument list.
3241 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3242 return ExprError();
3243 }
3244
3245 // Make sure that we're referring to a value.
3246 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3247 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3248 Diag(D->getLocation(), diag::note_declared_at);
3249 return ExprError();
3250 }
3251
3252 // Check whether this declaration can be used. Note that we suppress
3253 // this check when we're going to perform argument-dependent lookup
3254 // on this function name, because this might not be the function
3255 // that overload resolution actually selects.
3256 if (DiagnoseUseOfDecl(D, Loc))
3257 return ExprError();
3258
3259 auto *VD = cast<ValueDecl>(D);
3260
3261 // Only create DeclRefExpr's for valid Decl's.
3262 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3263 return ExprError();
3264
3265 // Handle members of anonymous structs and unions. If we got here,
3266 // and the reference is to a class member indirect field, then this
3267 // must be the subject of a pointer-to-member expression.
3268 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3269 if (!indirectField->isCXXClassMember())
3270 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3271 indirectField);
3272
3273 QualType type = VD->getType();
3274 if (type.isNull())
3275 return ExprError();
3276 ExprValueKind valueKind = VK_PRValue;
3277
3278 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3279 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3280 // is expanded by some outer '...' in the context of the use.
3281 type = type.getNonPackExpansionType();
3282
3283 switch (D->getKind()) {
3284 // Ignore all the non-ValueDecl kinds.
3285#define ABSTRACT_DECL(kind)
3286#define VALUE(type, base)
3287#define DECL(type, base) case Decl::type:
3288#include "clang/AST/DeclNodes.inc"
3289 llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "clang/lib/Sema/SemaExpr.cpp"
, 3289)
;
3290
3291 // These shouldn't make it here.
3292 case Decl::ObjCAtDefsField:
3293 llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?"
, "clang/lib/Sema/SemaExpr.cpp", 3293)
;
3294
3295 // Enum constants are always r-values and never references.
3296 // Unresolved using declarations are dependent.
3297 case Decl::EnumConstant:
3298 case Decl::UnresolvedUsingValue:
3299 case Decl::OMPDeclareReduction:
3300 case Decl::OMPDeclareMapper:
3301 valueKind = VK_PRValue;
3302 break;
3303
3304 // Fields and indirect fields that got here must be for
3305 // pointer-to-member expressions; we just call them l-values for
3306 // internal consistency, because this subexpression doesn't really
3307 // exist in the high-level semantics.
3308 case Decl::Field:
3309 case Decl::IndirectField:
3310 case Decl::ObjCIvar:
3311 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", 3311, __extension__ __PRETTY_FUNCTION__
))
;
3312
3313 // These can't have reference type in well-formed programs, but
3314 // for internal consistency we do this anyway.
3315 type = type.getNonReferenceType();
3316 valueKind = VK_LValue;
3317 break;
3318
3319 // Non-type template parameters are either l-values or r-values
3320 // depending on the type.
3321 case Decl::NonTypeTemplateParm: {
3322 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3323 type = reftype->getPointeeType();
3324 valueKind = VK_LValue; // even if the parameter is an r-value reference
3325 break;
3326 }
3327
3328 // [expr.prim.id.unqual]p2:
3329 // If the entity is a template parameter object for a template
3330 // parameter of type T, the type of the expression is const T.
3331 // [...] The expression is an lvalue if the entity is a [...] template
3332 // parameter object.
3333 if (type->isRecordType()) {
3334 type = type.getUnqualifiedType().withConst();
3335 valueKind = VK_LValue;
3336 break;
3337 }
3338
3339 // For non-references, we need to strip qualifiers just in case
3340 // the template parameter was declared as 'const int' or whatever.
3341 valueKind = VK_PRValue;
3342 type = type.getUnqualifiedType();
3343 break;
3344 }
3345
3346 case Decl::Var:
3347 case Decl::VarTemplateSpecialization:
3348 case Decl::VarTemplatePartialSpecialization:
3349 case Decl::Decomposition:
3350 case Decl::OMPCapturedExpr:
3351 // In C, "extern void blah;" is valid and is an r-value.
3352 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3353 type->isVoidType()) {
3354 valueKind = VK_PRValue;
3355 break;
3356 }
3357 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3358
3359 case Decl::ImplicitParam:
3360 case Decl::ParmVar: {
3361 // These are always l-values.
3362 valueKind = VK_LValue;
3363 type = type.getNonReferenceType();
3364
3365 // FIXME: Does the addition of const really only apply in
3366 // potentially-evaluated contexts? Since the variable isn't actually
3367 // captured in an unevaluated context, it seems that the answer is no.
3368 if (!isUnevaluatedContext()) {
3369 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3370 if (!CapturedType.isNull())
3371 type = CapturedType;
3372 }
3373
3374 break;
3375 }
3376
3377 case Decl::Binding: {
3378 // These are always lvalues.
3379 valueKind = VK_LValue;
3380 type = type.getNonReferenceType();
3381 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3382 // decides how that's supposed to work.
3383 auto *BD = cast<BindingDecl>(VD);
3384 if (BD->getDeclContext() != CurContext) {
3385 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3386 if (DD && DD->hasLocalStorage())
3387 diagnoseUncapturableValueReference(*this, Loc, BD);
3388 }
3389 break;
3390 }
3391
3392 case Decl::Function: {
3393 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3394 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3395 type = Context.BuiltinFnTy;
3396 valueKind = VK_PRValue;
3397 break;
3398 }
3399 }
3400
3401 const FunctionType *fty = type->castAs<FunctionType>();
3402
3403 // If we're referring to a function with an __unknown_anytype
3404 // result type, make the entire expression __unknown_anytype.
3405 if (fty->getReturnType() == Context.UnknownAnyTy) {
3406 type = Context.UnknownAnyTy;
3407 valueKind = VK_PRValue;
3408 break;
3409 }
3410
3411 // Functions are l-values in C++.
3412 if (getLangOpts().CPlusPlus) {
3413 valueKind = VK_LValue;
3414 break;
3415 }
3416
3417 // C99 DR 316 says that, if a function type comes from a
3418 // function definition (without a prototype), that type is only
3419 // used for checking compatibility. Therefore, when referencing
3420 // the function, we pretend that we don't have the full function
3421 // type.
3422 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3423 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3424 fty->getExtInfo());
3425
3426 // Functions are r-values in C.
3427 valueKind = VK_PRValue;
3428 break;
3429 }
3430
3431 case Decl::CXXDeductionGuide:
3432 llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide"
, "clang/lib/Sema/SemaExpr.cpp", 3432)
;
3433
3434 case Decl::MSProperty:
3435 case Decl::MSGuid:
3436 case Decl::TemplateParamObject:
3437 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3438 // capture in OpenMP, or duplicated between host and device?
3439 valueKind = VK_LValue;
3440 break;
3441
3442 case Decl::CXXMethod:
3443 // If we're referring to a method with an __unknown_anytype
3444 // result type, make the entire expression __unknown_anytype.
3445 // This should only be possible with a type written directly.
3446 if (const FunctionProtoType *proto =
3447 dyn_cast<FunctionProtoType>(VD->getType()))
3448 if (proto->getReturnType() == Context.UnknownAnyTy) {
3449 type = Context.UnknownAnyTy;
3450 valueKind = VK_PRValue;
3451 break;
3452 }
3453
3454 // C++ methods are l-values if static, r-values if non-static.
3455 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3456 valueKind = VK_LValue;
3457 break;
3458 }
3459 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3460
3461 case Decl::CXXConversion:
3462 case Decl::CXXDestructor:
3463 case Decl::CXXConstructor:
3464 valueKind = VK_PRValue;
3465 break;
3466 }
3467
3468 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3469 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3470 TemplateArgs);
3471}
3472
3473static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3474 SmallString<32> &Target) {
3475 Target.resize(CharByteWidth * (Source.size() + 1));
3476 char *ResultPtr = &Target[0];
3477 const llvm::UTF8 *ErrorPtr;
3478 bool success =
3479 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3480 (void)success;
3481 assert(success)(static_cast <bool> (success) ? void (0) : __assert_fail
("success", "clang/lib/Sema/SemaExpr.cpp", 3481, __extension__
__PRETTY_FUNCTION__))
;
3482 Target.resize(ResultPtr - &Target[0]);
3483}
3484
3485ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3486 PredefinedExpr::IdentKind IK) {
3487 // Pick the current block, lambda, captured statement or function.
3488 Decl *currentDecl = nullptr;
3489 if (const BlockScopeInfo *BSI = getCurBlock())
3490 currentDecl = BSI->TheDecl;
3491 else if (const LambdaScopeInfo *LSI = getCurLambda())
3492 currentDecl = LSI->CallOperator;
3493 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3494 currentDecl = CSI->TheCapturedDecl;
3495 else
3496 currentDecl = getCurFunctionOrMethodDecl();
3497
3498 if (!currentDecl) {
3499 Diag(Loc, diag::ext_predef_outside_function);
3500 currentDecl = Context.getTranslationUnitDecl();
3501 }
3502
3503 QualType ResTy;
3504 StringLiteral *SL = nullptr;
3505 if (cast<DeclContext>(currentDecl)->isDependentContext())
3506 ResTy = Context.DependentTy;
3507 else {
3508 // Pre-defined identifiers are of type char[x], where x is the length of
3509 // the string.
3510 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3511 unsigned Length = Str.length();
3512
3513 llvm::APInt LengthI(32, Length + 1);
3514 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3515 ResTy =
3516 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3517 SmallString<32> RawChars;
3518 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3519 Str, RawChars);
3520 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3521 ArrayType::Normal,
3522 /*IndexTypeQuals*/ 0);
3523 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3524 /*Pascal*/ false, ResTy, Loc);
3525 } else {
3526 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3527 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3528 ArrayType::Normal,
3529 /*IndexTypeQuals*/ 0);
3530 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3531 /*Pascal*/ false, ResTy, Loc);
3532 }
3533 }
3534
3535 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3536}
3537
3538ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3539 SourceLocation LParen,
3540 SourceLocation RParen,
3541 TypeSourceInfo *TSI) {
3542 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3543}
3544
3545ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3546 SourceLocation LParen,
3547 SourceLocation RParen,
3548 ParsedType ParsedTy) {
3549 TypeSourceInfo *TSI = nullptr;
3550 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3551
3552 if (Ty.isNull())
3553 return ExprError();
3554 if (!TSI)
3555 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3556
3557 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3558}
3559
3560ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3561 PredefinedExpr::IdentKind IK;
3562
3563 switch (Kind) {
3564 default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!"
, "clang/lib/Sema/SemaExpr.cpp", 3564)
;
3565 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3566 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3567 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3568 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3569 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3570 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3571 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3572 }
3573
3574 return BuildPredefinedExpr(Loc, IK);
3575}
3576
3577ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3578 SmallString<16> CharBuffer;
3579 bool Invalid = false;
3580 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3581 if (Invalid)
3582 return ExprError();
3583
3584 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3585 PP, Tok.getKind());
3586 if (Literal.hadError())
3587 return ExprError();
3588
3589 QualType Ty;
3590 if (Literal.isWide())
3591 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3592 else if (Literal.isUTF8() && getLangOpts().Char8)
3593 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3594 else if (Literal.isUTF16())
3595 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3596 else if (Literal.isUTF32())
3597 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3598 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3599 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3600 else
3601 Ty = Context.CharTy; // 'x' -> char in C++
3602
3603 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3604 if (Literal.isWide())
3605 Kind = CharacterLiteral::Wide;
3606 else if (Literal.isUTF16())
3607 Kind = CharacterLiteral::UTF16;
3608 else if (Literal.isUTF32())
3609 Kind = CharacterLiteral::UTF32;
3610 else if (Literal.isUTF8())
3611 Kind = CharacterLiteral::UTF8;
3612
3613 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3614 Tok.getLocation());
3615
3616 if (Literal.getUDSuffix().empty())
3617 return Lit;
3618
3619 // We're building a user-defined literal.
3620 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3621 SourceLocation UDSuffixLoc =
3622 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3623
3624 // Make sure we're allowed user-defined literals here.
3625 if (!UDLScope)
3626 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3627
3628 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3629 // operator "" X (ch)
3630 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3631 Lit, Tok.getLocation());
3632}
3633
3634ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3635 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3636 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3637 Context.IntTy, Loc);
3638}
3639
3640static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3641 QualType Ty, SourceLocation Loc) {
3642 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3643
3644 using llvm::APFloat;
3645 APFloat Val(Format);
3646
3647 APFloat::opStatus result = Literal.GetFloatValue(Val);
3648
3649 // Overflow is always an error, but underflow is only an error if
3650 // we underflowed to zero (APFloat reports denormals as underflow).
3651 if ((result & APFloat::opOverflow) ||
3652 ((result & APFloat::opUnderflow) && Val.isZero())) {
3653 unsigned diagnostic;
3654 SmallString<20> buffer;
3655 if (result & APFloat::opOverflow) {
3656 diagnostic = diag::warn_float_overflow;
3657 APFloat::getLargest(Format).toString(buffer);
3658 } else {
3659 diagnostic = diag::warn_float_underflow;
3660 APFloat::getSmallest(Format).toString(buffer);
3661 }
3662
3663 S.Diag(Loc, diagnostic)
3664 << Ty
3665 << StringRef(buffer.data(), buffer.size());
3666 }
3667
3668 bool isExact = (result == APFloat::opOK);
3669 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3670}
3671
3672bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3673 assert(E && "Invalid expression")(static_cast <bool> (E && "Invalid expression")
? void (0) : __assert_fail ("E && \"Invalid expression\""
, "clang/lib/Sema/SemaExpr.cpp", 3673, __extension__ __PRETTY_FUNCTION__
))
;
3674
3675 if (E->isValueDependent())
3676 return false;
3677
3678 QualType QT = E->getType();
3679 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3680 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3681 return true;
3682 }
3683
3684 llvm::APSInt ValueAPS;
3685 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3686
3687 if (R.isInvalid())
3688 return true;
3689
3690 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3691 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3692 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3693 << toString(ValueAPS, 10) << ValueIsPositive;
3694 return true;
3695 }
3696
3697 return false;
3698}
3699
3700ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3701 // Fast path for a single digit (which is quite common). A single digit
3702 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3703 if (Tok.getLength() == 1) {
3704 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3705 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3706 }
3707
3708 SmallString<128> SpellingBuffer;
3709 // NumericLiteralParser wants to overread by one character. Add padding to
3710 // the buffer in case the token is copied to the buffer. If getSpelling()
3711 // returns a StringRef to the memory buffer, it should have a null char at
3712 // the EOF, so it is also safe.
3713 SpellingBuffer.resize(Tok.getLength() + 1);
3714
3715 // Get the spelling of the token, which eliminates trigraphs, etc.
3716 bool Invalid = false;
3717 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3718 if (Invalid)
3719 return ExprError();
3720
3721 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3722 PP.getSourceManager(), PP.getLangOpts(),
3723 PP.getTargetInfo(), PP.getDiagnostics());
3724 if (Literal.hadError)
3725 return ExprError();
3726
3727 if (Literal.hasUDSuffix()) {
3728 // We're building a user-defined literal.
3729 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3730 SourceLocation UDSuffixLoc =
3731 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3732
3733 // Make sure we're allowed user-defined literals here.
3734 if (!UDLScope)
3735 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3736
3737 QualType CookedTy;
3738 if (Literal.isFloatingLiteral()) {
3739 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3740 // long double, the literal is treated as a call of the form
3741 // operator "" X (f L)
3742 CookedTy = Context.LongDoubleTy;
3743 } else {
3744 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3745 // unsigned long long, the literal is treated as a call of the form
3746 // operator "" X (n ULL)
3747 CookedTy = Context.UnsignedLongLongTy;
3748 }
3749
3750 DeclarationName OpName =
3751 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3752 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3753 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3754
3755 SourceLocation TokLoc = Tok.getLocation();
3756
3757 // Perform literal operator lookup to determine if we're building a raw
3758 // literal or a cooked one.
3759 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3760 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3761 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3762 /*AllowStringTemplatePack*/ false,
3763 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3764 case LOLR_ErrorNoDiagnostic:
3765 // Lookup failure for imaginary constants isn't fatal, there's still the
3766 // GNU extension producing _Complex types.
3767 break;
3768 case LOLR_Error:
3769 return ExprError();
3770 case LOLR_Cooked: {
3771 Expr *Lit;
3772 if (Literal.isFloatingLiteral()) {
3773 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3774 } else {
3775 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3776 if (Literal.GetIntegerValue(ResultVal))
3777 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3778 << /* Unsigned */ 1;
3779 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3780 Tok.getLocation());
3781 }
3782 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3783 }
3784
3785 case LOLR_Raw: {
3786 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3787 // literal is treated as a call of the form
3788 // operator "" X ("n")
3789 unsigned Length = Literal.getUDSuffixOffset();
3790 QualType StrTy = Context.getConstantArrayType(
3791 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3792 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3793 Expr *Lit = StringLiteral::Create(
3794 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3795 /*Pascal*/false, StrTy, &TokLoc, 1);
3796 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3797 }
3798
3799 case LOLR_Template: {
3800 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3801 // template), L is treated as a call fo the form
3802 // operator "" X <'c1', 'c2', ... 'ck'>()
3803 // where n is the source character sequence c1 c2 ... ck.
3804 TemplateArgumentListInfo ExplicitArgs;
3805 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3806 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3807 llvm::APSInt Value(CharBits, CharIsUnsigned);
3808 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3809 Value = TokSpelling[I];
3810 TemplateArgument Arg(Context, Value, Context.CharTy);
3811 TemplateArgumentLocInfo ArgInfo;
3812 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3813 }
3814 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3815 &ExplicitArgs);
3816 }
3817 case LOLR_StringTemplatePack:
3818 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 3818)
;
3819 }
3820 }
3821
3822 Expr *Res;
3823
3824 if (Literal.isFixedPointLiteral()) {
3825 QualType Ty;
3826
3827 if (Literal.isAccum) {
3828 if (Literal.isHalf) {
3829 Ty = Context.ShortAccumTy;
3830 } else if (Literal.isLong) {
3831 Ty = Context.LongAccumTy;
3832 } else {
3833 Ty = Context.AccumTy;
3834 }
3835 } else if (Literal.isFract) {
3836 if (Literal.isHalf) {
3837 Ty = Context.ShortFractTy;
3838 } else if (Literal.isLong) {
3839 Ty = Context.LongFractTy;
3840 } else {
3841 Ty = Context.FractTy;
3842 }
3843 }
3844
3845 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3846
3847 bool isSigned = !Literal.isUnsigned;
3848 unsigned scale = Context.getFixedPointScale(Ty);
3849 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3850
3851 llvm::APInt Val(bit_width, 0, isSigned);
3852 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3853 bool ValIsZero = Val.isZero() && !Overflowed;
3854
3855 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3856 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3857 // Clause 6.4.4 - The value of a constant shall be in the range of
3858 // representable values for its type, with exception for constants of a
3859 // fract type with a value of exactly 1; such a constant shall denote
3860 // the maximal value for the type.
3861 --Val;
3862 else if (Val.ugt(MaxVal) || Overflowed)
3863 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3864
3865 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3866 Tok.getLocation(), scale);
3867 } else if (Literal.isFloatingLiteral()) {
3868 QualType Ty;
3869 if (Literal.isHalf){
3870 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3871 Ty = Context.HalfTy;
3872 else {
3873 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3874 return ExprError();
3875 }
3876 } else if (Literal.isFloat)
3877 Ty = Context.FloatTy;
3878 else if (Literal.isLong)
3879 Ty = Context.LongDoubleTy;
3880 else if (Literal.isFloat16)
3881 Ty = Context.Float16Ty;
3882 else if (Literal.isFloat128)
3883 Ty = Context.Float128Ty;
3884 else
3885 Ty = Context.DoubleTy;
3886
3887 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3888
3889 if (Ty == Context.DoubleTy) {
3890 if (getLangOpts().SinglePrecisionConstants) {
3891 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3892 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3893 }
3894 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3895 "cl_khr_fp64", getLangOpts())) {
3896 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3897 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3898 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3899 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3900 }
3901 }
3902 } else if (!Literal.isIntegerLiteral()) {
3903 return ExprError();
3904 } else {
3905 QualType Ty;
3906
3907 // 'long long' is a C99 or C++11 feature.
3908 if (!getLangOpts().C99 && Literal.isLongLong) {
3909 if (getLangOpts().CPlusPlus)
3910 Diag(Tok.getLocation(),
3911 getLangOpts().CPlusPlus11 ?
3912 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3913 else
3914 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3915 }
3916
3917 // 'z/uz' literals are a C++2b feature.
3918 if (Literal.isSizeT)
3919 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3920 ? getLangOpts().CPlusPlus2b
3921 ? diag::warn_cxx20_compat_size_t_suffix
3922 : diag::ext_cxx2b_size_t_suffix
3923 : diag::err_cxx2b_size_t_suffix);
3924
3925 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3926 // but we do not currently support the suffix in C++ mode because it's not
3927 // entirely clear whether WG21 will prefer this suffix to return a library
3928 // type such as std::bit_int instead of returning a _BitInt.
3929 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3930 PP.Diag(Tok.getLocation(), getLangOpts().C2x
3931 ? diag::warn_c2x_compat_bitint_suffix
3932 : diag::ext_c2x_bitint_suffix);
3933
3934 // Get the value in the widest-possible width. What is "widest" depends on
3935 // whether the literal is a bit-precise integer or not. For a bit-precise
3936 // integer type, try to scan the source to determine how many bits are
3937 // needed to represent the value. This may seem a bit expensive, but trying
3938 // to get the integer value from an overly-wide APInt is *extremely*
3939 // expensive, so the naive approach of assuming
3940 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3941 unsigned BitsNeeded =
3942 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3943 Literal.getLiteralDigits(), Literal.getRadix())
3944 : Context.getTargetInfo().getIntMaxTWidth();
3945 llvm::APInt ResultVal(BitsNeeded, 0);
3946
3947 if (Literal.GetIntegerValue(ResultVal)) {
3948 // If this value didn't fit into uintmax_t, error and force to ull.
3949 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3950 << /* Unsigned */ 1;
3951 Ty = Context.UnsignedLongLongTy;
3952 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", 3953, __extension__ __PRETTY_FUNCTION__
))
3953 "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", 3953, __extension__ __PRETTY_FUNCTION__
))
;
3954 } else {
3955 // If this value fits into a ULL, try to figure out what else it fits into
3956 // according to the rules of C99 6.4.4.1p5.
3957
3958 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3959 // be an unsigned int.
3960 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3961
3962 // Check from smallest to largest, picking the smallest type we can.
3963 unsigned Width = 0;
3964
3965 // Microsoft specific integer suffixes are explicitly sized.
3966 if (Literal.MicrosoftInteger) {
3967 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3968 Width = 8;
3969 Ty = Context.CharTy;
3970 } else {
3971 Width = Literal.MicrosoftInteger;
3972 Ty = Context.getIntTypeForBitwidth(Width,
3973 /*Signed=*/!Literal.isUnsigned);
3974 }
3975 }
3976
3977 // Bit-precise integer literals are automagically-sized based on the
3978 // width required by the literal.
3979 if (Literal.isBitInt) {
3980 // The signed version has one more bit for the sign value. There are no
3981 // zero-width bit-precise integers, even if the literal value is 0.
3982 Width = Literal.isUnsigned ? std::max(ResultVal.getActiveBits(), 1u)
3983 : std::max(ResultVal.getMinSignedBits(), 2u);
3984
3985 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
3986 // and reset the type to the largest supported width.
3987 unsigned int MaxBitIntWidth =
3988 Context.getTargetInfo().getMaxBitIntWidth();
3989 if (Width > MaxBitIntWidth) {
3990 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3991 << Literal.isUnsigned;
3992 Width = MaxBitIntWidth;
3993 }
3994
3995 // Reset the result value to the smaller APInt and select the correct
3996 // type to be used. Note, we zext even for signed values because the
3997 // literal itself is always an unsigned value (a preceeding - is a
3998 // unary operator, not part of the literal).
3999 ResultVal = ResultVal.zextOrTrunc(Width);
4000 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4001 }
4002
4003 // Check C++2b size_t literals.
4004 if (Literal.isSizeT) {
4005 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", 4006, __extension__ __PRETTY_FUNCTION__
))
4006 "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", 4006, __extension__ __PRETTY_FUNCTION__
))
;
4007 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4008 Context.getTargetInfo().getSizeType());
4009
4010 // Does it fit in size_t?
4011 if (ResultVal.isIntN(SizeTSize)) {
4012 // Does it fit in ssize_t?
4013 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4014 Ty = Context.getSignedSizeType();
4015 else if (AllowUnsigned)
4016 Ty = Context.getSizeType();
4017 Width = SizeTSize;
4018 }
4019 }
4020
4021 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4022 !Literal.isSizeT) {
4023 // Are int/unsigned possibilities?
4024 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4025
4026 // Does it fit in a unsigned int?
4027 if (ResultVal.isIntN(IntSize)) {
4028 // Does it fit in a signed int?
4029 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4030 Ty = Context.IntTy;
4031 else if (AllowUnsigned)
4032 Ty = Context.UnsignedIntTy;
4033 Width = IntSize;
4034 }
4035 }
4036
4037 // Are long/unsigned long possibilities?
4038 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4039 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4040
4041 // Does it fit in a unsigned long?
4042 if (ResultVal.isIntN(LongSize)) {
4043 // Does it fit in a signed long?
4044 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4045 Ty = Context.LongTy;
4046 else if (AllowUnsigned)
4047 Ty = Context.UnsignedLongTy;
4048 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4049 // is compatible.
4050 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4051 const unsigned LongLongSize =
4052 Context.getTargetInfo().getLongLongWidth();
4053 Diag(Tok.getLocation(),
4054 getLangOpts().CPlusPlus
4055 ? Literal.isLong
4056 ? diag::warn_old_implicitly_unsigned_long_cxx
4057 : /*C++98 UB*/ diag::
4058 ext_old_implicitly_unsigned_long_cxx
4059 : diag::warn_old_implicitly_unsigned_long)
4060 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4061 : /*will be ill-formed*/ 1);
4062 Ty = Context.UnsignedLongTy;
4063 }
4064 Width = LongSize;
4065 }
4066 }
4067
4068 // Check long long if needed.
4069 if (Ty.isNull() && !Literal.isSizeT) {
4070 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4071
4072 // Does it fit in a unsigned long long?
4073 if (ResultVal.isIntN(LongLongSize)) {
4074 // Does it fit in a signed long long?
4075 // To be compatible with MSVC, hex integer literals ending with the
4076 // LL or i64 suffix are always signed in Microsoft mode.
4077 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4078 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4079 Ty = Context.LongLongTy;
4080 else if (AllowUnsigned)
4081 Ty = Context.UnsignedLongLongTy;
4082 Width = LongLongSize;
4083 }
4084 }
4085
4086 // If we still couldn't decide a type, we either have 'size_t' literal
4087 // that is out of range, or a decimal literal that does not fit in a
4088 // signed long long and has no U suffix.
4089 if (Ty.isNull()) {
4090 if (Literal.isSizeT)
4091 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4092 << Literal.isUnsigned;
4093 else
4094 Diag(Tok.getLocation(),
4095 diag::ext_integer_literal_too_large_for_signed);
4096 Ty = Context.UnsignedLongLongTy;
4097 Width = Context.getTargetInfo().getLongLongWidth();
4098 }
4099
4100 if (ResultVal.getBitWidth() != Width)
4101 ResultVal = ResultVal.trunc(Width);
4102 }
4103 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4104 }
4105
4106 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4107 if (Literal.isImaginary) {
4108 Res = new (Context) ImaginaryLiteral(Res,
4109 Context.getComplexType(Res->getType()));
4110
4111 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4112 }
4113 return Res;
4114}
4115
4116ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4117 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", 4117, __extension__ __PRETTY_FUNCTION__
))
;
4118 QualType ExprTy = E->getType();
4119 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4120 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4121 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4122 return new (Context) ParenExpr(L, R, E);
4123}
4124
4125static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4126 SourceLocation Loc,
4127 SourceRange ArgRange) {
4128 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4129 // scalar or vector data type argument..."
4130 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4131 // type (C99 6.2.5p18) or void.
4132 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4133 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4134 << T << ArgRange;
4135 return true;
4136 }
4137
4138 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", 4139, __extension__ __PRETTY_FUNCTION__
))
4139 "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", 4139, __extension__ __PRETTY_FUNCTION__
))
;
4140 return false;
4141}
4142
4143static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4144 SourceLocation Loc,
4145 SourceRange ArgRange,
4146 UnaryExprOrTypeTrait TraitKind) {
4147 // Invalid types must be hard errors for SFINAE in C++.
4148 if (S.LangOpts.CPlusPlus)
4149 return true;
4150
4151 // C99 6.5.3.4p1:
4152 if (T->isFunctionType() &&
4153 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4154 TraitKind == UETT_PreferredAlignOf)) {
4155 // sizeof(function)/alignof(function) is allowed as an extension.
4156 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4157 << getTraitSpelling(TraitKind) << ArgRange;
4158 return false;
4159 }
4160
4161 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4162 // this is an error (OpenCL v1.1 s6.3.k)
4163 if (T->isVoidType()) {
4164 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4165 : diag::ext_sizeof_alignof_void_type;
4166 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4167 return false;
4168 }
4169
4170 return true;
4171}
4172
4173static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4174 SourceLocation Loc,
4175 SourceRange ArgRange,
4176 UnaryExprOrTypeTrait TraitKind) {
4177 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4178 // runtime doesn't allow it.
4179 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4180 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4181 << T << (TraitKind == UETT_SizeOf)
4182 << ArgRange;
4183 return true;
4184 }
4185
4186 return false;
4187}
4188
4189/// Check whether E is a pointer from a decayed array type (the decayed
4190/// pointer type is equal to T) and emit a warning if it is.
4191static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4192 Expr *E) {
4193 // Don't warn if the operation changed the type.
4194 if (T != E->getType())
4195 return;
4196
4197 // Now look for array decays.
4198 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4199 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4200 return;
4201
4202 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4203 << ICE->getType()
4204 << ICE->getSubExpr()->getType();
4205}
4206
4207/// Check the constraints on expression operands to unary type expression
4208/// and type traits.
4209///
4210/// Completes any types necessary and validates the constraints on the operand
4211/// expression. The logic mostly mirrors the type-based overload, but may modify
4212/// the expression as it completes the type for that expression through template
4213/// instantiation, etc.
4214bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4215 UnaryExprOrTypeTrait ExprKind) {
4216 QualType ExprTy = E->getType();
4217 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp"
, 4217, __extension__ __PRETTY_FUNCTION__))
;
4218
4219 bool IsUnevaluatedOperand =
4220 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4221 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4222 if (IsUnevaluatedOperand) {
4223 ExprResult Result = CheckUnevaluatedOperand(E);
4224 if (Result.isInvalid())
4225 return true;
4226 E = Result.get();
4227 }
4228
4229 // The operand for sizeof and alignof is in an unevaluated expression context,
4230 // so side effects could result in unintended consequences.
4231 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4232 // used to build SFINAE gadgets.
4233 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4234 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4235 !E->isInstantiationDependent() &&
4236 E->HasSideEffects(Context, false))
4237 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4238
4239 if (ExprKind == UETT_VecStep)
4240 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4241 E->getSourceRange());
4242
4243 // Explicitly list some types as extensions.
4244 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4245 E->getSourceRange(), ExprKind))
4246 return false;
4247
4248 // 'alignof' applied to an expression only requires the base element type of
4249 // the expression to be complete. 'sizeof' requires the expression's type to
4250 // be complete (and will attempt to complete it if it's an array of unknown
4251 // bound).
4252 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4253 if (RequireCompleteSizedType(
4254 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4255 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4256 getTraitSpelling(ExprKind), E->getSourceRange()))
4257 return true;
4258 } else {
4259 if (RequireCompleteSizedExprType(
4260 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4261 getTraitSpelling(ExprKind), E->getSourceRange()))
4262 return true;
4263 }
4264
4265 // Completing the expression's type may have changed it.
4266 ExprTy = E->getType();
4267 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp"
, 4267, __extension__ __PRETTY_FUNCTION__))
;
4268
4269 if (ExprTy->isFunctionType()) {
4270 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4271 << getTraitSpelling(ExprKind) << E->getSourceRange();
4272 return true;
4273 }
4274
4275 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4276 E->getSourceRange(), ExprKind))
4277 return true;
4278
4279 if (ExprKind == UETT_SizeOf) {
4280 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4281 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4282 QualType OType = PVD->getOriginalType();
4283 QualType Type = PVD->getType();
4284 if (Type->isPointerType() && OType->isArrayType()) {
4285 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4286 << Type << OType;
4287 Diag(PVD->getLocation(), diag::note_declared_at);
4288 }
4289 }
4290 }
4291
4292 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4293 // decays into a pointer and returns an unintended result. This is most
4294 // likely a typo for "sizeof(array) op x".
4295 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4296 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4297 BO->getLHS());
4298 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4299 BO->getRHS());
4300 }
4301 }
4302
4303 return false;
4304}
4305
4306/// Check the constraints on operands to unary expression and type
4307/// traits.
4308///
4309/// This will complete any types necessary, and validate the various constraints
4310/// on those operands.
4311///
4312/// The UsualUnaryConversions() function is *not* called by this routine.
4313/// C99 6.3.2.1p[2-4] all state:
4314/// Except when it is the operand of the sizeof operator ...
4315///
4316/// C++ [expr.sizeof]p4
4317/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4318/// standard conversions are not applied to the operand of sizeof.
4319///
4320/// This policy is followed for all of the unary trait expressions.
4321bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4322 SourceLocation OpLoc,
4323 SourceRange ExprRange,
4324 UnaryExprOrTypeTrait ExprKind) {
4325 if (ExprType->isDependentType())
4326 return false;
4327
4328 // C++ [expr.sizeof]p2:
4329 // When applied to a reference or a reference type, the result
4330 // is the size of the referenced type.
4331 // C++11 [expr.alignof]p3:
4332 // When alignof is applied to a reference type, the result
4333 // shall be the alignment of the referenced type.
4334 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4335 ExprType = Ref->getPointeeType();
4336
4337 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4338 // When alignof or _Alignof is applied to an array type, the result
4339 // is the alignment of the element type.
4340 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4341 ExprKind == UETT_OpenMPRequiredSimdAlign)
4342 ExprType = Context.getBaseElementType(ExprType);
4343
4344 if (ExprKind == UETT_VecStep)
4345 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4346
4347 // Explicitly list some types as extensions.
4348 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4349 ExprKind))
4350 return false;
4351
4352 if (RequireCompleteSizedType(
4353 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4354 getTraitSpelling(ExprKind), ExprRange))
4355 return true;
4356
4357 if (ExprType->isFunctionType()) {
4358 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4359 << getTraitSpelling(ExprKind) << ExprRange;
4360 return true;
4361 }
4362
4363 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4364 ExprKind))
4365 return true;
4366
4367 return false;
4368}
4369
4370static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4371 // Cannot know anything else if the expression is dependent.
4372 if (E->isTypeDependent())
4373 return false;
4374
4375 if (E->getObjectKind() == OK_BitField) {
4376 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4377 << 1 << E->getSourceRange();
4378 return true;
4379 }
4380
4381 ValueDecl *D = nullptr;
4382 Expr *Inner = E->IgnoreParens();
4383 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4384 D = DRE->getDecl();
4385 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4386 D = ME->getMemberDecl();
4387 }
4388
4389 // If it's a field, require the containing struct to have a
4390 // complete definition so that we can compute the layout.
4391 //
4392 // This can happen in C++11 onwards, either by naming the member
4393 // in a way that is not transformed into a member access expression
4394 // (in an unevaluated operand, for instance), or by naming the member
4395 // in a trailing-return-type.
4396 //
4397 // For the record, since __alignof__ on expressions is a GCC
4398 // extension, GCC seems to permit this but always gives the
4399 // nonsensical answer 0.
4400 //
4401 // We don't really need the layout here --- we could instead just
4402 // directly check for all the appropriate alignment-lowing
4403 // attributes --- but that would require duplicating a lot of
4404 // logic that just isn't worth duplicating for such a marginal
4405 // use-case.
4406 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4407 // Fast path this check, since we at least know the record has a
4408 // definition if we can find a member of it.
4409 if (!FD->getParent()->isCompleteDefinition()) {
4410 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4411 << E->getSourceRange();
4412 return true;
4413 }
4414
4415 // Otherwise, if it's a field, and the field doesn't have
4416 // reference type, then it must have a complete type (or be a
4417 // flexible array member, which we explicitly want to
4418 // white-list anyway), which makes the following checks trivial.
4419 if (!FD->getType()->isReferenceType())
4420 return false;
4421 }
4422
4423 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4424}
4425
4426bool Sema::CheckVecStepExpr(Expr *E) {
4427 E = E->IgnoreParens();
4428
4429 // Cannot know anything else if the expression is dependent.
4430 if (E->isTypeDependent())
4431 return false;
4432
4433 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4434}
4435
4436static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4437 CapturingScopeInfo *CSI) {
4438 assert(T->isVariablyModifiedType())(static_cast <bool> (T->isVariablyModifiedType()) ? void
(0) : __assert_fail ("T->isVariablyModifiedType()", "clang/lib/Sema/SemaExpr.cpp"
, 4438, __extension__ __PRETTY_FUNCTION__))
;
4439 assert(CSI != nullptr)(static_cast <bool> (CSI != nullptr) ? void (0) : __assert_fail
("CSI != nullptr", "clang/lib/Sema/SemaExpr.cpp", 4439, __extension__
__PRETTY_FUNCTION__))
;
4440
4441 // We're going to walk down into the type and look for VLA expressions.
4442 do {
4443 const Type *Ty = T.getTypePtr();
4444 switch (Ty->getTypeClass()) {
4445#define TYPE(Class, Base)
4446#define ABSTRACT_TYPE(Class, Base)
4447#define NON_CANONICAL_TYPE(Class, Base)
4448#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4449#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4450#include "clang/AST/TypeNodes.inc"
4451 T = QualType();
4452 break;
4453 // These types are never variably-modified.
4454 case Type::Builtin:
4455 case Type::Complex:
4456 case Type::Vector:
4457 case Type::ExtVector:
4458 case Type::ConstantMatrix:
4459 case Type::Record:
4460 case Type::Enum:
4461 case Type::Elaborated:
4462 case Type::TemplateSpecialization:
4463 case Type::ObjCObject:
4464 case Type::ObjCInterface:
4465 case Type::ObjCObjectPointer:
4466 case Type::ObjCTypeParam:
4467 case Type::Pipe:
4468 case Type::BitInt:
4469 llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!"
, "clang/lib/Sema/SemaExpr.cpp", 4469)
;
4470 case Type::Adjusted:
4471 T = cast<AdjustedType>(Ty)->getOriginalType();
4472 break;
4473 case Type::Decayed:
4474 T = cast<DecayedType>(Ty)->getPointeeType();
4475 break;
4476 case Type::Pointer:
4477 T = cast<PointerType>(Ty)->getPointeeType();
4478 break;
4479 case Type::BlockPointer:
4480 T = cast<BlockPointerType>(Ty)->getPointeeType();
4481 break;
4482 case Type::LValueReference:
4483 case Type::RValueReference:
4484 T = cast<ReferenceType>(Ty)->getPointeeType();
4485 break;
4486 case Type::MemberPointer:
4487 T = cast<MemberPointerType>(Ty)->getPointeeType();
4488 break;
4489 case Type::ConstantArray:
4490 case Type::IncompleteArray:
4491 // Losing element qualification here is fine.
4492 T = cast<ArrayType>(Ty)->getElementType();
4493 break;
4494 case Type::VariableArray: {
4495 // Losing element qualification here is fine.
4496 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4497
4498 // Unknown size indication requires no size computation.
4499 // Otherwise, evaluate and record it.
4500 auto Size = VAT->getSizeExpr();
4501 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4502 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4503 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4504
4505 T = VAT->getElementType();
4506 break;
4507 }
4508 case Type::FunctionProto:
4509 case Type::FunctionNoProto:
4510 T = cast<FunctionType>(Ty)->getReturnType();
4511 break;
4512 case Type::Paren:
4513 case Type::TypeOf:
4514 case Type::UnaryTransform:
4515 case Type::Attributed:
4516 case Type::BTFTagAttributed:
4517 case Type::SubstTemplateTypeParm:
4518 case Type::MacroQualified:
4519 // Keep walking after single level desugaring.
4520 T = T.getSingleStepDesugaredType(Context);
4521 break;
4522 case Type::Typedef:
4523 T = cast<TypedefType>(Ty)->desugar();
4524 break;
4525 case Type::Decltype:
4526 T = cast<DecltypeType>(Ty)->desugar();
4527 break;
4528 case Type::Using:
4529 T = cast<UsingType>(Ty)->desugar();
4530 break;
4531 case Type::Auto:
4532 case Type::DeducedTemplateSpecialization:
4533 T = cast<DeducedType>(Ty)->getDeducedType();
4534 break;
4535 case Type::TypeOfExpr:
4536 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4537 break;
4538 case Type::Atomic:
4539 T = cast<AtomicType>(Ty)->getValueType();
4540 break;
4541 }
4542 } while (!T.isNull() && T->isVariablyModifiedType());
4543}
4544
4545/// Build a sizeof or alignof expression given a type operand.
4546ExprResult
4547Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4548 SourceLocation OpLoc,
4549 UnaryExprOrTypeTrait ExprKind,
4550 SourceRange R) {
4551 if (!TInfo)
4552 return ExprError();
4553
4554 QualType T = TInfo->getType();
4555
4556 if (!T->isDependentType() &&
4557 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4558 return ExprError();
4559
4560 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4561 if (auto *TT = T->getAs<TypedefType>()) {
4562 for (auto I = FunctionScopes.rbegin(),
4563 E = std::prev(FunctionScopes.rend());
4564 I != E; ++I) {
4565 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4566 if (CSI == nullptr)
4567 break;
4568 DeclContext *DC = nullptr;
4569 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4570 DC = LSI->CallOperator;
4571 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4572 DC = CRSI->TheCapturedDecl;
4573 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4574 DC = BSI->TheDecl;
4575 if (DC) {
4576 if (DC->containsDecl(TT->getDecl()))
4577 break;
4578 captureVariablyModifiedType(Context, T, CSI);
4579 }
4580 }
4581 }
4582 }
4583
4584 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4585 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4586 TInfo->getType()->isVariablyModifiedType())
4587 TInfo = TransformToPotentiallyEvaluated(TInfo);
4588
4589 return new (Context) UnaryExprOrTypeTraitExpr(
4590 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4591}
4592
4593/// Build a sizeof or alignof expression given an expression
4594/// operand.
4595ExprResult
4596Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4597 UnaryExprOrTypeTrait ExprKind) {
4598 ExprResult PE = CheckPlaceholderExpr(E);
4599 if (PE.isInvalid())
4600 return ExprError();
4601
4602 E = PE.get();
4603
4604 // Verify that the operand is valid.
4605 bool isInvalid = false;
4606 if (E->isTypeDependent()) {
4607 // Delay type-checking for type-dependent expressions.
4608 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4609 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4610 } else if (ExprKind == UETT_VecStep) {
4611 isInvalid = CheckVecStepExpr(E);
4612 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4613 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4614 isInvalid = true;
4615 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4616 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4617 isInvalid = true;
4618 } else {
4619 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4620 }
4621
4622 if (isInvalid)
4623 return ExprError();
4624
4625 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4626 PE = TransformToPotentiallyEvaluated(E);
4627 if (PE.isInvalid()) return ExprError();
4628 E = PE.get();
4629 }
4630
4631 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4632 return new (Context) UnaryExprOrTypeTraitExpr(
4633 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4634}
4635
4636/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4637/// expr and the same for @c alignof and @c __alignof
4638/// Note that the ArgRange is invalid if isType is false.
4639ExprResult
4640Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4641 UnaryExprOrTypeTrait ExprKind, bool IsType,
4642 void *TyOrEx, SourceRange ArgRange) {
4643 // If error parsing type, ignore.
4644 if (!TyOrEx) return ExprError();
4645
4646 if (IsType) {
4647 TypeSourceInfo *TInfo;
4648 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4649 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4650 }
4651
4652 Expr *ArgEx = (Expr *)TyOrEx;
4653 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4654 return Result;
4655}
4656
4657static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4658 bool IsReal) {
4659 if (V.get()->isTypeDependent())
4660 return S.Context.DependentTy;
4661
4662 // _Real and _Imag are only l-values for normal l-values.
4663 if (V.get()->getObjectKind() != OK_Ordinary) {
4664 V = S.DefaultLvalueConversion(V.get());
4665 if (V.isInvalid())
4666 return QualType();
4667 }
4668
4669 // These operators return the element type of a complex type.
4670 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4671 return CT->getElementType();
4672
4673 // Otherwise they pass through real integer and floating point types here.
4674 if (V.get()->getType()->isArithmeticType())
4675 return V.get()->getType();
4676
4677 // Test for placeholders.
4678 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4679 if (PR.isInvalid()) return QualType();
4680 if (PR.get() != V.get()) {
4681 V = PR;
4682 return CheckRealImagOperand(S, V, Loc, IsReal);
4683 }
4684
4685 // Reject anything else.
4686 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4687 << (IsReal ? "__real" : "__imag");
4688 return QualType();
4689}
4690
4691
4692
4693ExprResult
4694Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4695 tok::TokenKind Kind, Expr *Input) {
4696 UnaryOperatorKind Opc;
4697 switch (Kind) {
4698 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp"
, 4698)
;
4699 case tok::plusplus: Opc = UO_PostInc; break;
4700 case tok::minusminus: Opc = UO_PostDec; break;
4701 }
4702
4703 // Since this might is a postfix expression, get rid of ParenListExprs.
4704 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4705 if (Result.isInvalid()) return ExprError();
4706 Input = Result.get();
4707
4708 return BuildUnaryOp(S, OpLoc, Opc, Input);
4709}
4710
4711/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4712///
4713/// \return true on error
4714static bool checkArithmeticOnObjCPointer(Sema &S,
4715 SourceLocation opLoc,
4716 Expr *op) {
4717 assert(op->getType()->isObjCObjectPointerType())(static_cast <bool> (op->getType()->isObjCObjectPointerType
()) ? void (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 4717, __extension__ __PRETTY_FUNCTION__
))
;
4718 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4719 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4720 return false;
4721
4722 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4723 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4724 << op->getSourceRange();
4725 return true;
4726}
4727
4728static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4729 auto *BaseNoParens = Base->IgnoreParens();
4730 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4731 return MSProp->getPropertyDecl()->getType()->isArrayType();
4732 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4733}
4734
4735// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4736// Typically this is DependentTy, but can sometimes be more precise.
4737//
4738// There are cases when we could determine a non-dependent type:
4739// - LHS and RHS may have non-dependent types despite being type-dependent
4740// (e.g. unbounded array static members of the current instantiation)
4741// - one may be a dependent-sized array with known element type
4742// - one may be a dependent-typed valid index (enum in current instantiation)
4743//
4744// We *always* return a dependent type, in such cases it is DependentTy.
4745// This avoids creating type-dependent expressions with non-dependent types.
4746// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4747static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4748 const ASTContext &Ctx) {
4749 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", 4749, __extension__ __PRETTY_FUNCTION__
))
;
4750 QualType LTy = LHS->getType(), RTy = RHS->getType();
4751 QualType Result = Ctx.DependentTy;
4752 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4753 if (const PointerType *PT = LTy->getAs<PointerType>())
4754 Result = PT->getPointeeType();
4755 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4756 Result = AT->getElementType();
4757 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4758 if (const PointerType *PT = RTy->getAs<PointerType>())
4759 Result = PT->getPointeeType();
4760 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4761 Result = AT->getElementType();
4762 }
4763 // Ensure we return a dependent type.
4764 return Result->isDependentType() ? Result : Ctx.DependentTy;
4765}
4766
4767static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4768
4769ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4770 SourceLocation lbLoc,
4771 MultiExprArg ArgExprs,
4772 SourceLocation rbLoc) {
4773
4774 if (base && !base->getType().isNull() &&
4775 base->hasPlaceholderType(BuiltinType::OMPArraySection))
4776 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4777 SourceLocation(), /*Length*/ nullptr,
4778 /*Stride=*/nullptr, rbLoc);
4779
4780 // Since this might be a postfix expression, get rid of ParenListExprs.
4781 if (isa<ParenListExpr>(base)) {
4782 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4783 if (result.isInvalid())
4784 return ExprError();
4785 base = result.get();
4786 }
4787
4788 // Check if base and idx form a MatrixSubscriptExpr.
4789 //
4790 // Helper to check for comma expressions, which are not allowed as indices for
4791 // matrix subscript expressions.
4792 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4793 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4794 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4795 << SourceRange(base->getBeginLoc(), rbLoc);
4796 return true;
4797 }
4798 return false;
4799 };
4800 // The matrix subscript operator ([][])is considered a single operator.
4801 // Separating the index expressions by parenthesis is not allowed.
4802 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4803 !isa<MatrixSubscriptExpr>(base)) {
4804 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4805 << SourceRange(base->getBeginLoc(), rbLoc);
4806 return ExprError();
4807 }
4808 // If the base is a MatrixSubscriptExpr, try to create a new
4809 // MatrixSubscriptExpr.
4810 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4811 if (matSubscriptE) {
4812 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4812, __extension__ __PRETTY_FUNCTION__))
;
4813 if (CheckAndReportCommaError(ArgExprs.front()))
4814 return ExprError();
4815
4816 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", 4817, __extension__ __PRETTY_FUNCTION__
))
4817 "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", 4817, __extension__ __PRETTY_FUNCTION__
))
;
4818 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4819 matSubscriptE->getRowIdx(),
4820 ArgExprs.front(), rbLoc);
4821 }
4822
4823 // Handle any non-overload placeholder types in the base and index
4824 // expressions. We can't handle overloads here because the other
4825 // operand might be an overloadable type, in which case the overload
4826 // resolution for the operator overload should get the first crack
4827 // at the overload.
4828 bool IsMSPropertySubscript = false;
4829 if (base->getType()->isNonOverloadPlaceholderType()) {
4830 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4831 if (!IsMSPropertySubscript) {
4832 ExprResult result = CheckPlaceholderExpr(base);
4833 if (result.isInvalid())
4834 return ExprError();
4835 base = result.get();
4836 }
4837 }
4838
4839 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4840 if (base->getType()->isMatrixType()) {
4841 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4841, __extension__ __PRETTY_FUNCTION__))
;
4842 if (CheckAndReportCommaError(ArgExprs.front()))
4843 return ExprError();
4844
4845 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4846 rbLoc);
4847 }
4848
4849 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4850 Expr *idx = ArgExprs[0];
4851 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4852 (isa<CXXOperatorCallExpr>(idx) &&
4853 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4854 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4855 << SourceRange(base->getBeginLoc(), rbLoc);
4856 }
4857 }
4858
4859 if (ArgExprs.size() == 1 &&
4860 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4861 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4862 if (result.isInvalid())
4863 return ExprError();
4864 ArgExprs[0] = result.get();
4865 } else {
4866 if (checkArgsForPlaceholders(*this, ArgExprs))
4867 return ExprError();
4868 }
4869
4870 // Build an unanalyzed expression if either operand is type-dependent.
4871 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4872 (base->isTypeDependent() ||
4873 Expr::hasAnyTypeDependentArguments(ArgExprs))) {
4874 return new (Context) ArraySubscriptExpr(
4875 base, ArgExprs.front(),
4876 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4877 VK_LValue, OK_Ordinary, rbLoc);
4878 }
4879
4880 // MSDN, property (C++)
4881 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4882 // This attribute can also be used in the declaration of an empty array in a
4883 // class or structure definition. For example:
4884 // __declspec(property(get=GetX, put=PutX)) int x[];
4885 // The above statement indicates that x[] can be used with one or more array
4886 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4887 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4888 if (IsMSPropertySubscript) {
4889 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4889, __extension__ __PRETTY_FUNCTION__))
;
4890 // Build MS property subscript expression if base is MS property reference
4891 // or MS property subscript.
4892 return new (Context)
4893 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4894 VK_LValue, OK_Ordinary, rbLoc);
4895 }
4896
4897 // Use C++ overloaded-operator rules if either operand has record
4898 // type. The spec says to do this if either type is *overloadable*,
4899 // but enum types can't declare subscript operators or conversion
4900 // operators, so there's nothing interesting for overload resolution
4901 // to do if there aren't any record types involved.
4902 //
4903 // ObjC pointers have their own subscripting logic that is not tied
4904 // to overload resolution and so should not take this path.
4905 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4906 ((base->getType()->isRecordType() ||
4907 (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4908 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4909 }
4910
4911 ExprResult Res =
4912 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4913
4914 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4915 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4916
4917 return Res;
4918}
4919
4920ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4921 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4922 InitializationKind Kind =
4923 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4924 InitializationSequence InitSeq(*this, Entity, Kind, E);
4925 return InitSeq.Perform(*this, Entity, Kind, E);
4926}
4927
4928ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4929 Expr *ColumnIdx,
4930 SourceLocation RBLoc) {
4931 ExprResult BaseR = CheckPlaceholderExpr(Base);
4932 if (BaseR.isInvalid())
4933 return BaseR;
4934 Base = BaseR.get();
4935
4936 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4937 if (RowR.isInvalid())
4938 return RowR;
4939 RowIdx = RowR.get();
4940
4941 if (!ColumnIdx)
4942 return new (Context) MatrixSubscriptExpr(
4943 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4944
4945 // Build an unanalyzed expression if any of the operands is type-dependent.
4946 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4947 ColumnIdx->isTypeDependent())
4948 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4949 Context.DependentTy, RBLoc);
4950
4951 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4952 if (ColumnR.isInvalid())
4953 return ColumnR;
4954 ColumnIdx = ColumnR.get();
4955
4956 // Check that IndexExpr is an integer expression. If it is a constant
4957 // expression, check that it is less than Dim (= the number of elements in the
4958 // corresponding dimension).
4959 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4960 bool IsColumnIdx) -> Expr * {
4961 if (!IndexExpr->getType()->isIntegerType() &&
4962 !IndexExpr->isTypeDependent()) {
4963 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4964 << IsColumnIdx;
4965 return nullptr;
4966 }
4967
4968 if (Optional<llvm::APSInt> Idx =
4969 IndexExpr->getIntegerConstantExpr(Context)) {
4970 if ((*Idx < 0 || *Idx >= Dim)) {
4971 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4972 << IsColumnIdx << Dim;
4973 return nullptr;
4974 }
4975 }
4976
4977 ExprResult ConvExpr =
4978 tryConvertExprToType(IndexExpr, Context.getSizeType());
4979 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", 4980, __extension__ __PRETTY_FUNCTION__
))
4980 "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", 4980, __extension__ __PRETTY_FUNCTION__
))
;
4981 return ConvExpr.get();
4982 };
4983
4984 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4985 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4986 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4987 if (!RowIdx || !ColumnIdx)
4988 return ExprError();
4989
4990 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4991 MTy->getElementType(), RBLoc);
4992}
4993
4994void Sema::CheckAddressOfNoDeref(const Expr *E) {
4995 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4996 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4997
4998 // For expressions like `&(*s).b`, the base is recorded and what should be
4999 // checked.
5000 const MemberExpr *Member = nullptr;
5001 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5002 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5003
5004 LastRecord.PossibleDerefs.erase(StrippedExpr);
5005}
5006
5007void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5008 if (isUnevaluatedContext())
5009 return;
5010
5011 QualType ResultTy = E->getType();
5012 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5013
5014 // Bail if the element is an array since it is not memory access.
5015 if (isa<ArrayType>(ResultTy))
5016 return;
5017
5018 if (ResultTy->hasAttr(attr::NoDeref)) {
5019 LastRecord.PossibleDerefs.insert(E);
5020 return;
5021 }
5022
5023 // Check if the base type is a pointer to a member access of a struct
5024 // marked with noderef.
5025 const Expr *Base = E->getBase();
5026 QualType BaseTy = Base->getType();
5027 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5028 // Not a pointer access
5029 return;
5030
5031 const MemberExpr *Member = nullptr;
5032 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5033 Member->isArrow())
5034 Base = Member->getBase();
5035
5036 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5037 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5038 LastRecord.PossibleDerefs.insert(E);
5039 }
5040}
5041
5042ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5043 Expr *LowerBound,
5044 SourceLocation ColonLocFirst,
5045 SourceLocation ColonLocSecond,
5046 Expr *Length, Expr *Stride,
5047 SourceLocation RBLoc) {
5048 if (Base->hasPlaceholderType() &&
5049 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5050 ExprResult Result = CheckPlaceholderExpr(Base);
5051 if (Result.isInvalid())
5052 return ExprError();
5053 Base = Result.get();
5054 }
5055 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5056 ExprResult Result = CheckPlaceholderExpr(LowerBound);
5057 if (Result.isInvalid())
5058 return ExprError();
5059 Result = DefaultLvalueConversion(Result.get());
5060 if (Result.isInvalid())
5061 return ExprError();
5062 LowerBound = Result.get();
5063 }
5064 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5065 ExprResult Result = CheckPlaceholderExpr(Length);
5066 if (Result.isInvalid())
5067 return ExprError();
5068 Result = DefaultLvalueConversion(Result.get());
5069 if (Result.isInvalid())
5070 return ExprError();
5071 Length = Result.get();
5072 }
5073 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5074 ExprResult Result = CheckPlaceholderExpr(Stride);
5075 if (Result.isInvalid())
5076 return ExprError();
5077 Result = DefaultLvalueConversion(Result.get());
5078 if (Result.isInvalid())
5079 return ExprError();
5080 Stride = Result.get();
5081 }
5082
5083 // Build an unanalyzed expression if either operand is type-dependent.
5084 if (Base->isTypeDependent() ||
5085 (LowerBound &&
5086 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5087 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5088 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5089 return new (Context) OMPArraySectionExpr(
5090 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5091 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5092 }
5093
5094 // Perform default conversions.
5095 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5096 QualType ResultTy;
5097 if (OriginalTy->isAnyPointerType()) {
5098 ResultTy = OriginalTy->getPointeeType();
5099 } else if (OriginalTy->isArrayType()) {
5100 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5101 } else {
5102 return ExprError(
5103 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5104 << Base->getSourceRange());
5105 }
5106 // C99 6.5.2.1p1
5107 if (LowerBound) {
5108 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5109 LowerBound);
5110 if (Res.isInvalid())
5111 return ExprError(Diag(LowerBound->getExprLoc(),
5112 diag::err_omp_typecheck_section_not_integer)
5113 << 0 << LowerBound->getSourceRange());
5114 LowerBound = Res.get();
5115
5116 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5117 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5118 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5119 << 0 << LowerBound->getSourceRange();
5120 }
5121 if (Length) {
5122 auto Res =
5123 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5124 if (Res.isInvalid())
5125 return ExprError(Diag(Length->getExprLoc(),
5126 diag::err_omp_typecheck_section_not_integer)
5127 << 1 << Length->getSourceRange());
5128 Length = Res.get();
5129
5130 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5131 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5132 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5133 << 1 << Length->getSourceRange();
5134 }
5135 if (Stride) {
5136 ExprResult Res =
5137 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5138 if (Res.isInvalid())
5139 return ExprError(Diag(Stride->getExprLoc(),
5140 diag::err_omp_typecheck_section_not_integer)
5141 << 1 << Stride->getSourceRange());
5142 Stride = Res.get();
5143
5144 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5145 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5146 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5147 << 1 << Stride->getSourceRange();
5148 }
5149
5150 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5151 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5152 // type. Note that functions are not objects, and that (in C99 parlance)
5153 // incomplete types are not object types.
5154 if (ResultTy->isFunctionType()) {
5155 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5156 << ResultTy << Base->getSourceRange();
5157 return ExprError();
5158 }
5159
5160 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5161 diag::err_omp_section_incomplete_type, Base))
5162 return ExprError();
5163
5164 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5165 Expr::EvalResult Result;
5166 if (LowerBound->EvaluateAsInt(Result, Context)) {
5167 // OpenMP 5.0, [2.1.5 Array Sections]
5168 // The array section must be a subset of the original array.
5169 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5170 if (LowerBoundValue.isNegative()) {
5171 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5172 << LowerBound->getSourceRange();
5173 return ExprError();
5174 }
5175 }
5176 }
5177
5178 if (Length) {
5179 Expr::EvalResult Result;
5180 if (Length->EvaluateAsInt(Result, Context)) {
5181 // OpenMP 5.0, [2.1.5 Array Sections]
5182 // The length must evaluate to non-negative integers.
5183 llvm::APSInt LengthValue = Result.Val.getInt();
5184 if (LengthValue.isNegative()) {
5185 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5186 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5187 << Length->getSourceRange();
5188 return ExprError();
5189 }
5190 }
5191 } else if (ColonLocFirst.isValid() &&
5192 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5193 !OriginalTy->isVariableArrayType()))) {
5194 // OpenMP 5.0, [2.1.5 Array Sections]
5195 // When the size of the array dimension is not known, the length must be
5196 // specified explicitly.
5197 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5198 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5199 return ExprError();
5200 }
5201
5202 if (Stride) {
5203 Expr::EvalResult Result;
5204 if (Stride->EvaluateAsInt(Result, Context)) {
5205 // OpenMP 5.0, [2.1.5 Array Sections]
5206 // The stride must evaluate to a positive integer.
5207 llvm::APSInt StrideValue = Result.Val.getInt();
5208 if (!StrideValue.isStrictlyPositive()) {
5209 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5210 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5211 << Stride->getSourceRange();
5212 return ExprError();
5213 }
5214 }
5215 }
5216
5217 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5218 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5219 if (Result.isInvalid())
5220 return ExprError();
5221 Base = Result.get();
5222 }
5223 return new (Context) OMPArraySectionExpr(
5224 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5225 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5226}
5227
5228ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5229 SourceLocation RParenLoc,
5230 ArrayRef<Expr *> Dims,
5231 ArrayRef<SourceRange> Brackets) {
5232 if (Base->hasPlaceholderType()) {
5233 ExprResult Result = CheckPlaceholderExpr(Base);
5234 if (Result.isInvalid())
5235 return ExprError();
5236 Result = DefaultLvalueConversion(Result.get());
5237 if (Result.isInvalid())
5238 return ExprError();
5239 Base = Result.get();
5240 }
5241 QualType BaseTy = Base->getType();
5242 // Delay analysis of the types/expressions if instantiation/specialization is
5243 // required.
5244 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5245 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5246 LParenLoc, RParenLoc, Dims, Brackets);
5247 if (!BaseTy->isPointerType() ||
5248 (!Base->isTypeDependent() &&
5249 BaseTy->getPointeeType()->isIncompleteType()))
5250 return ExprError(Diag(Base->getExprLoc(),
5251 diag::err_omp_non_pointer_type_array_shaping_base)
5252 << Base->getSourceRange());
5253
5254 SmallVector<Expr *, 4> NewDims;
5255 bool ErrorFound = false;
5256 for (Expr *Dim : Dims) {
5257 if (Dim->hasPlaceholderType()) {
5258 ExprResult Result = CheckPlaceholderExpr(Dim);
5259 if (Result.isInvalid()) {
5260 ErrorFound = true;
5261 continue;
5262 }
5263 Result = DefaultLvalueConversion(Result.get());
5264 if (Result.isInvalid()) {
5265 ErrorFound = true;
5266 continue;
5267 }
5268 Dim = Result.get();
5269 }
5270 if (!Dim->isTypeDependent()) {
5271 ExprResult Result =
5272 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5273 if (Result.isInvalid()) {
5274 ErrorFound = true;
5275 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5276 << Dim->getSourceRange();
5277 continue;
5278 }
5279 Dim = Result.get();
5280 Expr::EvalResult EvResult;
5281 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5282 // OpenMP 5.0, [2.1.4 Array Shaping]
5283 // Each si is an integral type expression that must evaluate to a
5284 // positive integer.
5285 llvm::APSInt Value = EvResult.Val.getInt();
5286 if (!Value.isStrictlyPositive()) {
5287 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5288 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5289 << Dim->getSourceRange();
5290 ErrorFound = true;
5291 continue;
5292 }
5293 }
5294 }
5295 NewDims.push_back(Dim);
5296 }
5297 if (ErrorFound)
5298 return ExprError();
5299 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5300 LParenLoc, RParenLoc, NewDims, Brackets);
5301}
5302
5303ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5304 SourceLocation LLoc, SourceLocation RLoc,
5305 ArrayRef<OMPIteratorData> Data) {
5306 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5307 bool IsCorrect = true;
5308 for (const OMPIteratorData &D : Data) {
5309 TypeSourceInfo *TInfo = nullptr;
5310 SourceLocation StartLoc;
5311 QualType DeclTy;
5312 if (!D.Type.getAsOpaquePtr()) {
5313 // OpenMP 5.0, 2.1.6 Iterators
5314 // In an iterator-specifier, if the iterator-type is not specified then
5315 // the type of that iterator is of int type.
5316 DeclTy = Context.IntTy;
5317 StartLoc = D.DeclIdentLoc;
5318 } else {
5319 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5320 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5321 }
5322
5323 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5324 DeclTy->containsUnexpandedParameterPack() ||
5325 DeclTy->isInstantiationDependentType();
5326 if (!IsDeclTyDependent) {
5327 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5328 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5329 // The iterator-type must be an integral or pointer type.
5330 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5331 << DeclTy;
5332 IsCorrect = false;
5333 continue;
5334 }
5335 if (DeclTy.isConstant(Context)) {
5336 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5337 // The iterator-type must not be const qualified.
5338 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5339 << DeclTy;
5340 IsCorrect = false;
5341 continue;
5342 }
5343 }
5344
5345 // Iterator declaration.
5346 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", 5346, __extension__ __PRETTY_FUNCTION__
))
;
5347 // Always try to create iterator declarator to avoid extra error messages
5348 // about unknown declarations use.
5349 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5350 D.DeclIdent, DeclTy, TInfo, SC_None);
5351 VD->setImplicit();
5352 if (S) {
5353 // Check for conflicting previous declaration.
5354 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5355 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5356 ForVisibleRedeclaration);
5357 Previous.suppressDiagnostics();
5358 LookupName(Previous, S);
5359
5360 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5361 /*AllowInlineNamespace=*/false);
5362 if (!Previous.empty()) {
5363 NamedDecl *Old = Previous.getRepresentativeDecl();
5364 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5365 Diag(Old->getLocation(), diag::note_previous_definition);
5366 } else {
5367 PushOnScopeChains(VD, S);
5368 }
5369 } else {
5370 CurContext->addDecl(VD);
5371 }
5372 Expr *Begin = D.Range.Begin;
5373 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5374 ExprResult BeginRes =
5375 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5376 Begin = BeginRes.get();
5377 }
5378 Expr *End = D.Range.End;
5379 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5380 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5381 End = EndRes.get();
5382 }
5383 Expr *Step = D.Range.Step;
5384 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5385 if (!Step->getType()->isIntegralType(Context)) {
5386 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5387 << Step << Step->getSourceRange();
5388 IsCorrect = false;
5389 continue;
5390 }
5391 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5392 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5393 // If the step expression of a range-specification equals zero, the
5394 // behavior is unspecified.
5395 if (Result && Result->isZero()) {
5396 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5397 << Step << Step->getSourceRange();
5398 IsCorrect = false;
5399 continue;
5400 }
5401 }
5402 if (!Begin || !End || !IsCorrect) {
5403 IsCorrect = false;
5404 continue;
5405 }
5406 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5407 IDElem.IteratorDecl = VD;
5408 IDElem.AssignmentLoc = D.AssignLoc;
5409 IDElem.Range.Begin = Begin;
5410 IDElem.Range.End = End;
5411 IDElem.Range.Step = Step;
5412 IDElem.ColonLoc = D.ColonLoc;
5413 IDElem.SecondColonLoc = D.SecColonLoc;
5414 }
5415 if (!IsCorrect) {
5416 // Invalidate all created iterator declarations if error is found.
5417 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5418 if (Decl *ID = D.IteratorDecl)
5419 ID->setInvalidDecl();
5420 }
5421 return ExprError();
5422 }
5423 SmallVector<OMPIteratorHelperData, 4> Helpers;
5424 if (!CurContext->isDependentContext()) {
5425 // Build number of ityeration for each iteration range.
5426 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5427 // ((Begini-Stepi-1-Endi) / -Stepi);
5428 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5429 // (Endi - Begini)
5430 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5431 D.Range.Begin);
5432 if(!Res.isUsable()) {
5433 IsCorrect = false;
5434 continue;
5435 }
5436 ExprResult St, St1;
5437 if (D.Range.Step) {
5438 St = D.Range.Step;
5439 // (Endi - Begini) + Stepi
5440 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5441 if (!Res.isUsable()) {
5442 IsCorrect = false;
5443 continue;
5444 }
5445 // (Endi - Begini) + Stepi - 1
5446 Res =
5447 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5448 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5449 if (!Res.isUsable()) {
5450 IsCorrect = false;
5451 continue;
5452 }
5453 // ((Endi - Begini) + Stepi - 1) / Stepi
5454 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5455 if (!Res.isUsable()) {
5456 IsCorrect = false;
5457 continue;
5458 }
5459 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5460 // (Begini - Endi)
5461 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5462 D.Range.Begin, D.Range.End);
5463 if (!Res1.isUsable()) {
5464 IsCorrect = false;
5465 continue;
5466 }
5467 // (Begini - Endi) - Stepi
5468 Res1 =
5469 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5470 if (!Res1.isUsable()) {
5471 IsCorrect = false;
5472 continue;
5473 }
5474 // (Begini - Endi) - Stepi - 1
5475 Res1 =
5476 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5477 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5478 if (!Res1.isUsable()) {
5479 IsCorrect = false;
5480 continue;
5481 }
5482 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5483 Res1 =
5484 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5485 if (!Res1.isUsable()) {
5486 IsCorrect = false;
5487 continue;
5488 }
5489 // Stepi > 0.
5490 ExprResult CmpRes =
5491 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5492 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5493 if (!CmpRes.isUsable()) {
5494 IsCorrect = false;
5495 continue;
5496 }
5497 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5498 Res.get(), Res1.get());
5499 if (!Res.isUsable()) {
5500 IsCorrect = false;
5501 continue;
5502 }
5503 }
5504 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5505 if (!Res.isUsable()) {
5506 IsCorrect = false;
5507 continue;
5508 }
5509
5510 // Build counter update.
5511 // Build counter.
5512 auto *CounterVD =
5513 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5514 D.IteratorDecl->getBeginLoc(), nullptr,
5515 Res.get()->getType(), nullptr, SC_None);
5516 CounterVD->setImplicit();
5517 ExprResult RefRes =
5518 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5519 D.IteratorDecl->getBeginLoc());
5520 // Build counter update.
5521 // I = Begini + counter * Stepi;
5522 ExprResult UpdateRes;
5523 if (D.Range.Step) {
5524 UpdateRes = CreateBuiltinBinOp(
5525 D.AssignmentLoc, BO_Mul,
5526 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5527 } else {
5528 UpdateRes = DefaultLvalueConversion(RefRes.get());
5529 }
5530 if (!UpdateRes.isUsable()) {
5531 IsCorrect = false;
5532 continue;
5533 }
5534 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5535 UpdateRes.get());
5536 if (!UpdateRes.isUsable()) {
5537 IsCorrect = false;
5538 continue;
5539 }
5540 ExprResult VDRes =
5541 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5542 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5543 D.IteratorDecl->getBeginLoc());
5544 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5545 UpdateRes.get());
5546 if (!UpdateRes.isUsable()) {
5547 IsCorrect = false;
5548 continue;
5549 }
5550 UpdateRes =
5551 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5552 if (!UpdateRes.isUsable()) {
5553 IsCorrect = false;
5554 continue;
5555 }
5556 ExprResult CounterUpdateRes =
5557 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5558 if (!CounterUpdateRes.isUsable()) {
5559 IsCorrect = false;
5560 continue;
5561 }
5562 CounterUpdateRes =
5563 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5564 if (!CounterUpdateRes.isUsable()) {
5565 IsCorrect = false;
5566 continue;
5567 }
5568 OMPIteratorHelperData &HD = Helpers.emplace_back();
5569 HD.CounterVD = CounterVD;
5570 HD.Upper = Res.get();
5571 HD.Update = UpdateRes.get();
5572 HD.CounterUpdate = CounterUpdateRes.get();
5573 }
5574 } else {
5575 Helpers.assign(ID.size(), {});
5576 }
5577 if (!IsCorrect) {
5578 // Invalidate all created iterator declarations if error is found.
5579 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5580 if (Decl *ID = D.IteratorDecl)
5581 ID->setInvalidDecl();
5582 }
5583 return ExprError();
5584 }
5585 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5586 LLoc, RLoc, ID, Helpers);
5587}
5588
5589ExprResult
5590Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5591 Expr *Idx, SourceLocation RLoc) {
5592 Expr *LHSExp = Base;
5593 Expr *RHSExp = Idx;
5594
5595 ExprValueKind VK = VK_LValue;
5596 ExprObjectKind OK = OK_Ordinary;
5597
5598 // Per C++ core issue 1213, the result is an xvalue if either operand is
5599 // a non-lvalue array, and an lvalue otherwise.
5600 if (getLangOpts().CPlusPlus11) {
5601 for (auto *Op : {LHSExp, RHSExp}) {
5602 Op = Op->IgnoreImplicit();
5603 if (Op->getType()->isArrayType() && !Op->isLValue())
5604 VK = VK_XValue;
5605 }
5606 }
5607
5608 // Perform default conversions.
5609 if (!LHSExp->getType()->getAs<VectorType>()) {
5610 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5611 if (Result.isInvalid())
5612 return ExprError();
5613 LHSExp = Result.get();
5614 }
5615 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5616 if (Result.isInvalid())
5617 return ExprError();
5618 RHSExp = Result.get();
5619
5620 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5621
5622 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5623 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5624 // in the subscript position. As a result, we need to derive the array base
5625 // and index from the expression types.
5626 Expr *BaseExpr, *IndexExpr;
5627 QualType ResultType;
5628 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5629 BaseExpr = LHSExp;
5630 IndexExpr = RHSExp;
5631 ResultType =
5632 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5633 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5634 BaseExpr = LHSExp;
5635 IndexExpr = RHSExp;
5636 ResultType = PTy->getPointeeType();
5637 } else if (const ObjCObjectPointerType *PTy =
5638 LHSTy->getAs<ObjCObjectPointerType>()) {
5639 BaseExpr = LHSExp;
5640 IndexExpr = RHSExp;
5641
5642 // Use custom logic if this should be the pseudo-object subscript
5643 // expression.
5644 if (!LangOpts.isSubscriptPointerArithmetic())
5645 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5646 nullptr);
5647
5648 ResultType = PTy->getPointeeType();
5649 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5650 // Handle the uncommon case of "123[Ptr]".
5651 BaseExpr = RHSExp;
5652 IndexExpr = LHSExp;
5653 ResultType = PTy->getPointeeType();
5654 } else if (const ObjCObjectPointerType *PTy =
5655 RHSTy->getAs<ObjCObjectPointerType>()) {
5656 // Handle the uncommon case of "123[Ptr]".
5657 BaseExpr = RHSExp;
5658 IndexExpr = LHSExp;
5659 ResultType = PTy->getPointeeType();
5660 if (!LangOpts.isSubscriptPointerArithmetic()) {
5661 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5662 << ResultType << BaseExpr->getSourceRange();
5663 return ExprError();
5664 }
5665 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5666 BaseExpr = LHSExp; // vectors: V[123]
5667 IndexExpr = RHSExp;
5668 // We apply C++ DR1213 to vector subscripting too.
5669 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5670 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5671 if (Materialized.isInvalid())
5672 return ExprError();
5673 LHSExp = Materialized.get();
5674 }
5675 VK = LHSExp->getValueKind();
5676 if (VK != VK_PRValue)
5677 OK = OK_VectorComponent;
5678
5679 ResultType = VTy->getElementType();
5680 QualType BaseType = BaseExpr->getType();
5681 Qualifiers BaseQuals = BaseType.getQualifiers();
5682 Qualifiers MemberQuals = ResultType.getQualifiers();
5683 Qualifiers Combined = BaseQuals + MemberQuals;
5684 if (Combined != MemberQuals)
5685 ResultType = Context.getQualifiedType(ResultType, Combined);
5686 } else if (LHSTy->isArrayType()) {
5687 // If we see an array that wasn't promoted by
5688 // DefaultFunctionArrayLvalueConversion, it must be an array that
5689 // wasn't promoted because of the C90 rule that doesn't
5690 // allow promoting non-lvalue arrays. Warn, then
5691 // force the promotion here.
5692 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5693 << LHSExp->getSourceRange();
5694 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5695 CK_ArrayToPointerDecay).get();
5696 LHSTy = LHSExp->getType();
5697
5698 BaseExpr = LHSExp;
5699 IndexExpr = RHSExp;
5700 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5701 } else if (RHSTy->isArrayType()) {
5702 // Same as previous, except for 123[f().a] case
5703 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5704 << RHSExp->getSourceRange();
5705 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5706 CK_ArrayToPointerDecay).get();
5707 RHSTy = RHSExp->getType();
5708
5709 BaseExpr = RHSExp;
5710 IndexExpr = LHSExp;
5711 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5712 } else {
5713 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5714 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5715 }
5716 // C99 6.5.2.1p1
5717 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5718 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5719 << IndexExpr->getSourceRange());
5720
5721 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5722 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5723 && !IndexExpr->isTypeDependent())
5724 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5725
5726 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5727 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5728 // type. Note that Functions are not objects, and that (in C99 parlance)
5729 // incomplete types are not object types.
5730 if (ResultType->isFunctionType()) {
5731 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5732 << ResultType << BaseExpr->getSourceRange();
5733 return ExprError();
5734 }
5735
5736 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5737 // GNU extension: subscripting on pointer to void
5738 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5739 << BaseExpr->getSourceRange();
5740
5741 // C forbids expressions of unqualified void type from being l-values.
5742 // See IsCForbiddenLValueType.
5743 if (!ResultType.hasQualifiers())
5744 VK = VK_PRValue;
5745 } else if (!ResultType->isDependentType() &&
5746 RequireCompleteSizedType(
5747 LLoc, ResultType,
5748 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5749 return ExprError();
5750
5751 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", 5752, __extension__ __PRETTY_FUNCTION__
))
5752 !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", 5752, __extension__ __PRETTY_FUNCTION__
))
;
5753
5754 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5755 FunctionScopes.size() > 1) {
5756 if (auto *TT =
5757 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5758 for (auto I = FunctionScopes.rbegin(),
5759 E = std::prev(FunctionScopes.rend());
5760 I != E; ++I) {
5761 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5762 if (CSI == nullptr)
5763 break;
5764 DeclContext *DC = nullptr;
5765 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5766 DC = LSI->CallOperator;
5767 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5768 DC = CRSI->TheCapturedDecl;
5769 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5770 DC = BSI->TheDecl;
5771 if (DC) {
5772 if (DC->containsDecl(TT->getDecl()))
5773 break;
5774 captureVariablyModifiedType(
5775 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5776 }
5777 }
5778 }
5779 }
5780
5781 return new (Context)
5782 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5783}
5784
5785bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5786 ParmVarDecl *Param) {
5787 if (Param->hasUnparsedDefaultArg()) {
5788 // If we've already cleared out the location for the default argument,
5789 // that means we're parsing it right now.
5790 if (!UnparsedDefaultArgLocs.count(Param)) {
5791 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5792 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5793 Param->setInvalidDecl();
5794 return true;
5795 }
5796
5797 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5798 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5799 Diag(UnparsedDefaultArgLocs[Param],
5800 diag::note_default_argument_declared_here);
5801 return true;
5802 }
5803
5804 if (Param->hasUninstantiatedDefaultArg() &&
5805 InstantiateDefaultArgument(CallLoc, FD, Param))
5806 return true;
5807
5808 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", 5808, __extension__ __PRETTY_FUNCTION__
))
;
5809
5810 // If the default expression creates temporaries, we need to
5811 // push them to the current stack of expression temporaries so they'll
5812 // be properly destroyed.
5813 // FIXME: We should really be rebuilding the default argument with new
5814 // bound temporaries; see the comment in PR5810.
5815 // We don't need to do that with block decls, though, because
5816 // blocks in default argument expression can never capture anything.
5817 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5818 // Set the "needs cleanups" bit regardless of whether there are
5819 // any explicit objects.
5820 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5821
5822 // Append all the objects to the cleanup list. Right now, this
5823 // should always be a no-op, because blocks in default argument
5824 // expressions should never be able to capture anything.
5825 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", 5826, __extension__ __PRETTY_FUNCTION__
))
5826 "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", 5826, __extension__ __PRETTY_FUNCTION__
))
;
5827 }
5828
5829 // We already type-checked the argument, so we know it works.
5830 // Just mark all of the declarations in this potentially-evaluated expression
5831 // as being "referenced".
5832 EnterExpressionEvaluationContext EvalContext(
5833 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5834 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5835 /*SkipLocalVariables=*/true);
5836 return false;
5837}
5838
5839ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5840 FunctionDecl *FD, ParmVarDecl *Param) {
5841 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", 5841, __extension__ __PRETTY_FUNCTION__
))
;
5842 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5843 return ExprError();
5844 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5845}
5846
5847Sema::VariadicCallType
5848Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5849 Expr *Fn) {
5850 if (Proto && Proto->isVariadic()) {
5851 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5852 return VariadicConstructor;
5853 else if (Fn && Fn->getType()->isBlockPointerType())
5854 return VariadicBlock;
5855 else if (FDecl) {
5856 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5857 if (Method->isInstance())
5858 return VariadicMethod;
5859 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5860 return VariadicMethod;
5861 return VariadicFunction;
5862 }
5863 return VariadicDoesNotApply;
5864}
5865
5866namespace {
5867class FunctionCallCCC final : public FunctionCallFilterCCC {
5868public:
5869 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5870 unsigned NumArgs, MemberExpr *ME)
5871 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5872 FunctionName(FuncName) {}
5873
5874 bool ValidateCandidate(const TypoCorrection &candidate) override {
5875 if (!candidate.getCorrectionSpecifier() ||
5876 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5877 return false;
5878 }
5879
5880 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5881 }
5882
5883 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5884 return std::make_unique<FunctionCallCCC>(*this);
5885 }
5886
5887private:
5888 const IdentifierInfo *const FunctionName;
5889};
5890}
5891
5892static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5893 FunctionDecl *FDecl,
5894 ArrayRef<Expr *> Args) {
5895 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5896 DeclarationName FuncName = FDecl->getDeclName();
5897 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5898
5899 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5900 if (TypoCorrection Corrected = S.CorrectTypo(
5901 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5902 S.getScopeForContext(S.CurContext), nullptr, CCC,
5903 Sema::CTK_ErrorRecovery)) {
5904 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5905 if (Corrected.isOverloaded()) {
5906 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5907 OverloadCandidateSet::iterator Best;
5908 for (NamedDecl *CD : Corrected) {
5909 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5910 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5911 OCS);
5912 }
5913 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5914 case OR_Success:
5915 ND = Best->FoundDecl;
5916 Corrected.setCorrectionDecl(ND);
5917 break;
5918 default:
5919 break;
5920 }
5921 }
5922 ND = ND->getUnderlyingDecl();
5923 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5924 return Corrected;
5925 }
5926 }
5927 return TypoCorrection();
5928}
5929
5930/// ConvertArgumentsForCall - Converts the arguments specified in
5931/// Args/NumArgs to the parameter types of the function FDecl with
5932/// function prototype Proto. Call is the call expression itself, and
5933/// Fn is the function expression. For a C++ member function, this
5934/// routine does not attempt to convert the object argument. Returns
5935/// true if the call is ill-formed.
5936bool
5937Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5938 FunctionDecl *FDecl,
5939 const FunctionProtoType *Proto,
5940 ArrayRef<Expr *> Args,
5941 SourceLocation RParenLoc,
5942 bool IsExecConfig) {
5943 // Bail out early if calling a builtin with custom typechecking.
5944 if (FDecl)
5945 if (unsigned ID = FDecl->getBuiltinID())
5946 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5947 return false;
5948
5949 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5950 // assignment, to the types of the corresponding parameter, ...
5951 unsigned NumParams = Proto->getNumParams();
5952 bool Invalid = false;
5953 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5954 unsigned FnKind = Fn->getType()->isBlockPointerType()
5955 ? 1 /* block */
5956 : (IsExecConfig ? 3 /* kernel function (exec config) */
5957 : 0 /* function */);
5958
5959 // If too few arguments are available (and we don't have default
5960 // arguments for the remaining parameters), don't make the call.
5961 if (Args.size() < NumParams) {
5962 if (Args.size() < MinArgs) {
5963 TypoCorrection TC;
5964 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5965 unsigned diag_id =
5966 MinArgs == NumParams && !Proto->isVariadic()
5967 ? diag::err_typecheck_call_too_few_args_suggest
5968 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5969 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5970 << static_cast<unsigned>(Args.size())
5971 << TC.getCorrectionRange());
5972 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5973 Diag(RParenLoc,
5974 MinArgs == NumParams && !Proto->isVariadic()
5975 ? diag::err_typecheck_call_too_few_args_one
5976 : diag::err_typecheck_call_too_few_args_at_least_one)
5977 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5978 else
5979 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5980 ? diag::err_typecheck_call_too_few_args
5981 : diag::err_typecheck_call_too_few_args_at_least)
5982 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5983 << Fn->getSourceRange();
5984
5985 // Emit the location of the prototype.
5986 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5987 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5988
5989 return true;
5990 }
5991 // We reserve space for the default arguments when we create
5992 // the call expression, before calling ConvertArgumentsForCall.
5993 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", 5994, __extension__ __PRETTY_FUNCTION__
))
5994 "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", 5994, __extension__ __PRETTY_FUNCTION__
))
;
5995 }
5996
5997 // If too many are passed and not variadic, error on the extras and drop
5998 // them.
5999 if (Args.size() > NumParams) {
6000 if (!Proto->isVariadic()) {
6001 TypoCorrection TC;
6002 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6003 unsigned diag_id =
6004 MinArgs == NumParams && !Proto->isVariadic()
6005 ? diag::err_typecheck_call_too_many_args_suggest
6006 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6007 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6008 << static_cast<unsigned>(Args.size())
6009 << TC.getCorrectionRange());
6010 } else if (NumParams == 1 && FDecl &&
6011 FDecl->getParamDecl(0)->getDeclName())
6012 Diag(Args[NumParams]->getBeginLoc(),
6013 MinArgs == NumParams
6014 ? diag::err_typecheck_call_too_many_args_one
6015 : diag::err_typecheck_call_too_many_args_at_most_one)
6016 << FnKind << FDecl->getParamDecl(0)
6017 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6018 << SourceRange(Args[NumParams]->getBeginLoc(),
6019 Args.back()->getEndLoc());
6020 else
6021 Diag(Args[NumParams]->getBeginLoc(),
6022 MinArgs == NumParams
6023 ? diag::err_typecheck_call_too_many_args
6024 : diag::err_typecheck_call_too_many_args_at_most)
6025 << FnKind << NumParams << static_cast<unsigned>(Args.size())
6026 << Fn->getSourceRange()
6027 << SourceRange(Args[NumParams]->getBeginLoc(),
6028 Args.back()->getEndLoc());
6029
6030 // Emit the location of the prototype.
6031 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6032 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6033
6034 // This deletes the extra arguments.
6035 Call->shrinkNumArgs(NumParams);
6036 return true;
6037 }
6038 }
6039 SmallVector<Expr *, 8> AllArgs;
6040 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6041
6042 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6043 AllArgs, CallType);
6044 if (Invalid)
6045 return true;
6046 unsigned TotalNumArgs = AllArgs.size();
6047 for (unsigned i = 0; i < TotalNumArgs; ++i)
6048 Call->setArg(i, AllArgs[i]);
6049
6050 Call->computeDependence();
6051 return false;
6052}
6053
6054bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6055 const FunctionProtoType *Proto,
6056 unsigned FirstParam, ArrayRef<Expr *> Args,
6057 SmallVectorImpl<Expr *> &AllArgs,
6058 VariadicCallType CallType, bool AllowExplicit,
6059 bool IsListInitialization) {
6060 unsigned NumParams = Proto->getNumParams();
6061 bool Invalid = false;
6062 size_t ArgIx = 0;
6063 // Continue to check argument types (even if we have too few/many args).
6064 for (unsigned i = FirstParam; i < NumParams; i++) {
6065 QualType ProtoArgType = Proto->getParamType(i);
6066
6067 Expr *Arg;
6068 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6069 if (ArgIx < Args.size()) {
6070 Arg = Args[ArgIx++];
6071
6072 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6073 diag::err_call_incomplete_argument, Arg))
6074 return true;
6075
6076 // Strip the unbridged-cast placeholder expression off, if applicable.
6077 bool CFAudited = false;
6078 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6079 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6080 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6081 Arg = stripARCUnbridgedCast(Arg);
6082 else if (getLangOpts().ObjCAutoRefCount &&
6083 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6084 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6085 CFAudited = true;
6086
6087 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6088 ProtoArgType->isBlockPointerType())
6089 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6090 BE->getBlockDecl()->setDoesNotEscape();
6091
6092 InitializedEntity Entity =
6093 Param ? InitializedEntity::InitializeParameter(Context, Param,
6094 ProtoArgType)
6095 : InitializedEntity::InitializeParameter(
6096 Context, ProtoArgType, Proto->isParamConsumed(i));
6097
6098 // Remember that parameter belongs to a CF audited API.
6099 if (CFAudited)
6100 Entity.setParameterCFAudited();
6101
6102 ExprResult ArgE = PerformCopyInitialization(
6103 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6104 if (ArgE.isInvalid())
6105 return true;
6106
6107 Arg = ArgE.getAs<Expr>();
6108 } else {
6109 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", 6109, __extension__ __PRETTY_FUNCTION__
))
;
6110
6111 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6112 if (ArgExpr.isInvalid())
6113 return true;
6114
6115 Arg = ArgExpr.getAs<Expr>();
6116 }
6117
6118 // Check for array bounds violations for each argument to the call. This
6119 // check only triggers warnings when the argument isn't a more complex Expr
6120 // with its own checking, such as a BinaryOperator.
6121 CheckArrayAccess(Arg);
6122
6123 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6124 CheckStaticArrayArgument(CallLoc, Param, Arg);
6125
6126 AllArgs.push_back(Arg);
6127 }
6128
6129 // If this is a variadic call, handle args passed through "...".
6130 if (CallType != VariadicDoesNotApply) {
6131 // Assume that extern "C" functions with variadic arguments that
6132 // return __unknown_anytype aren't *really* variadic.
6133 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6134 FDecl->isExternC()) {
6135 for (Expr *A : Args.slice(ArgIx)) {
6136 QualType paramType; // ignored
6137 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6138 Invalid |= arg.isInvalid();
6139 AllArgs.push_back(arg.get());
6140 }
6141
6142 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6143 } else {
6144 for (Expr *A : Args.slice(ArgIx)) {
6145 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6146 Invalid |= Arg.isInvalid();
6147 AllArgs.push_back(Arg.get());
6148 }
6149 }
6150
6151 // Check for array bounds violations.
6152 for (Expr *A : Args.slice(ArgIx))
6153 CheckArrayAccess(A);
6154 }
6155 return Invalid;
6156}
6157
6158static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6159 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6160 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6161 TL = DTL.getOriginalLoc();
6162 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6163 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6164 << ATL.getLocalSourceRange();
6165}
6166
6167/// CheckStaticArrayArgument - If the given argument corresponds to a static
6168/// array parameter, check that it is non-null, and that if it is formed by
6169/// array-to-pointer decay, the underlying array is sufficiently large.
6170///
6171/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6172/// array type derivation, then for each call to the function, the value of the
6173/// corresponding actual argument shall provide access to the first element of
6174/// an array with at least as many elements as specified by the size expression.
6175void
6176Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6177 ParmVarDecl *Param,
6178 const Expr *ArgExpr) {
6179 // Static array parameters are not supported in C++.
6180 if (!Param || getLangOpts().CPlusPlus)
6181 return;
6182
6183 QualType OrigTy = Param->getOriginalType();
6184
6185 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6186 if (!AT || AT->getSizeModifier() != ArrayType::Static)
6187 return;
6188
6189 if (ArgExpr->isNullPointerConstant(Context,
6190 Expr::NPC_NeverValueDependent)) {
6191 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6192 DiagnoseCalleeStaticArrayParam(*this, Param);
6193 return;
6194 }
6195
6196 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6197 if (!CAT)
6198 return;
6199
6200 const ConstantArrayType *ArgCAT =
6201 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6202 if (!ArgCAT)
6203 return;
6204
6205 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6206 ArgCAT->getElementType())) {
6207 if (ArgCAT->getSize().ult(CAT->getSize())) {
6208 Diag(CallLoc, diag::warn_static_array_too_small)
6209 << ArgExpr->getSourceRange()
6210 << (unsigned)ArgCAT->getSize().getZExtValue()
6211 << (unsigned)CAT->getSize().getZExtValue() << 0;
6212 DiagnoseCalleeStaticArrayParam(*this, Param);
6213 }
6214 return;
6215 }
6216
6217 Optional<CharUnits> ArgSize =
6218 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6219 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6220 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6221 Diag(CallLoc, diag::warn_static_array_too_small)
6222 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6223 << (unsigned)ParmSize->getQuantity() << 1;
6224 DiagnoseCalleeStaticArrayParam(*this, Param);
6225 }
6226}
6227
6228/// Given a function expression of unknown-any type, try to rebuild it
6229/// to have a function type.
6230static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6231
6232/// Is the given type a placeholder that we need to lower out
6233/// immediately during argument processing?
6234static bool isPlaceholderToRemoveAsArg(QualType type) {
6235 // Placeholders are never sugared.
6236 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6237 if (!placeholder) return false;
6238
6239 switch (placeholder->getKind()) {
6240 // Ignore all the non-placeholder types.
6241#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6242 case BuiltinType::Id:
6243#include "clang/Basic/OpenCLImageTypes.def"
6244#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6245 case BuiltinType::Id:
6246#include "clang/Basic/OpenCLExtensionTypes.def"
6247 // In practice we'll never use this, since all SVE types are sugared
6248 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6249#define SVE_TYPE(Name, Id, SingletonId) \
6250 case BuiltinType::Id:
6251#include "clang/Basic/AArch64SVEACLETypes.def"
6252#define PPC_VECTOR_TYPE(Name, Id, Size) \
6253 case BuiltinType::Id:
6254#include "clang/Basic/PPCTypes.def"
6255#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6256#include "clang/Basic/RISCVVTypes.def"
6257#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6258#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6259#include "clang/AST/BuiltinTypes.def"
6260 return false;
6261
6262 // We cannot lower out overload sets; they might validly be resolved
6263 // by the call machinery.
6264 case BuiltinType::Overload:
6265 return false;
6266
6267 // Unbridged casts in ARC can be handled in some call positions and
6268 // should be left in place.
6269 case BuiltinType::ARCUnbridgedCast:
6270 return false;
6271
6272 // Pseudo-objects should be converted as soon as possible.
6273 case BuiltinType::PseudoObject:
6274 return true;
6275
6276 // The debugger mode could theoretically but currently does not try
6277 // to resolve unknown-typed arguments based on known parameter types.
6278 case BuiltinType::UnknownAny:
6279 return true;
6280
6281 // These are always invalid as call arguments and should be reported.
6282 case BuiltinType::BoundMember:
6283 case BuiltinType::BuiltinFn:
6284 case BuiltinType::IncompleteMatrixIdx:
6285 case BuiltinType::OMPArraySection:
6286 case BuiltinType::OMPArrayShaping:
6287 case BuiltinType::OMPIterator:
6288 return true;
6289
6290 }
6291 llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "clang/lib/Sema/SemaExpr.cpp"
, 6291)
;
6292}
6293
6294/// Check an argument list for placeholders that we won't try to
6295/// handle later.
6296static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6297 // Apply this processing to all the arguments at once instead of
6298 // dying at the first failure.
6299 bool hasInvalid = false;
6300 for (size_t i = 0, e = args.size(); i != e; i++) {
6301 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6302 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6303 if (result.isInvalid()) hasInvalid = true;
6304 else args[i] = result.get();
6305 }
6306 }
6307 return hasInvalid;
6308}
6309
6310/// If a builtin function has a pointer argument with no explicit address
6311/// space, then it should be able to accept a pointer to any address
6312/// space as input. In order to do this, we need to replace the
6313/// standard builtin declaration with one that uses the same address space
6314/// as the call.
6315///
6316/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6317/// it does not contain any pointer arguments without
6318/// an address space qualifer. Otherwise the rewritten
6319/// FunctionDecl is returned.
6320/// TODO: Handle pointer return types.
6321static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6322 FunctionDecl *FDecl,
6323 MultiExprArg ArgExprs) {
6324
6325 QualType DeclType = FDecl->getType();
6326 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6327
6328 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6329 ArgExprs.size() < FT->getNumParams())
6330 return nullptr;
6331
6332 bool NeedsNewDecl = false;
6333 unsigned i = 0;
6334 SmallVector<QualType, 8> OverloadParams;
6335
6336 for (QualType ParamType : FT->param_types()) {
6337
6338 // Convert array arguments to pointer to simplify type lookup.
6339 ExprResult ArgRes =
6340 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6341 if (ArgRes.isInvalid())
6342 return nullptr;
6343 Expr *Arg = ArgRes.get();
6344 QualType ArgType = Arg->getType();
6345 if (!ParamType->isPointerType() ||
6346 ParamType.hasAddressSpace() ||
6347 !ArgType->isPointerType() ||
6348 !ArgType->getPointeeType().hasAddressSpace()) {
6349 OverloadParams.push_back(ParamType);
6350 continue;
6351 }
6352
6353 QualType PointeeType = ParamType->getPointeeType();
6354 if (PointeeType.hasAddressSpace())
6355 continue;
6356
6357 NeedsNewDecl = true;
6358 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6359
6360 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6361 OverloadParams.push_back(Context.getPointerType(PointeeType));
6362 }
6363
6364 if (!NeedsNewDecl)
6365 return nullptr;
6366
6367 FunctionProtoType::ExtProtoInfo EPI;
6368 EPI.Variadic = FT->isVariadic();
6369 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6370 OverloadParams, EPI);
6371 DeclContext *Parent = FDecl->getParent();
6372 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6373 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6374 FDecl->getIdentifier(), OverloadTy,
6375 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6376 false,
6377 /*hasPrototype=*/true);
6378 SmallVector<ParmVarDecl*, 16> Params;
6379 FT = cast<FunctionProtoType>(OverloadTy);
6380 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6381 QualType ParamType = FT->getParamType(i);
6382 ParmVarDecl *Parm =
6383 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6384 SourceLocation(), nullptr, ParamType,
6385 /*TInfo=*/nullptr, SC_None, nullptr);
6386 Parm->setScopeInfo(0, i);
6387 Params.push_back(Parm);
6388 }
6389 OverloadDecl->setParams(Params);
6390 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6391 return OverloadDecl;
6392}
6393
6394static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6395 FunctionDecl *Callee,
6396 MultiExprArg ArgExprs) {
6397 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6398 // similar attributes) really don't like it when functions are called with an
6399 // invalid number of args.
6400 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6401 /*PartialOverloading=*/false) &&
6402 !Callee->isVariadic())
6403 return;
6404 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6405 return;
6406
6407 if (const EnableIfAttr *Attr =
6408 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6409 S.Diag(Fn->getBeginLoc(),
6410 isa<CXXMethodDecl>(Callee)
6411 ? diag::err_ovl_no_viable_member_function_in_call
6412 : diag::err_ovl_no_viable_function_in_call)
6413 << Callee << Callee->getSourceRange();
6414 S.Diag(Callee->getLocation(),
6415 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6416 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6417 return;
6418 }
6419}
6420
6421static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6422 const UnresolvedMemberExpr *const UME, Sema &S) {
6423
6424 const auto GetFunctionLevelDCIfCXXClass =
6425 [](Sema &S) -> const CXXRecordDecl * {
6426 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6427 if (!DC || !DC->getParent())
6428 return nullptr;
6429
6430 // If the call to some member function was made from within a member
6431 // function body 'M' return return 'M's parent.
6432 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6433 return MD->getParent()->getCanonicalDecl();
6434 // else the call was made from within a default member initializer of a
6435 // class, so return the class.
6436 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6437 return RD->getCanonicalDecl();
6438 return nullptr;
6439 };
6440 // If our DeclContext is neither a member function nor a class (in the
6441 // case of a lambda in a default member initializer), we can't have an
6442 // enclosing 'this'.
6443
6444 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6445 if (!CurParentClass)
6446 return false;
6447
6448 // The naming class for implicit member functions call is the class in which
6449 // name lookup starts.
6450 const CXXRecordDecl *const NamingClass =
6451 UME->getNamingClass()->getCanonicalDecl();
6452 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", 6452, __extension__ __PRETTY_FUNCTION__
))
;
6453
6454 // If the unresolved member functions were found in a 'naming class' that is
6455 // related (either the same or derived from) to the class that contains the
6456 // member function that itself contained the implicit member access.
6457
6458 return CurParentClass == NamingClass ||
6459 CurParentClass->isDerivedFrom(NamingClass);
6460}
6461
6462static void
6463tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6464 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6465
6466 if (!UME)
6467 return;
6468
6469 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6470 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6471 // already been captured, or if this is an implicit member function call (if
6472 // it isn't, an attempt to capture 'this' should already have been made).
6473 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6474 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6475 return;
6476
6477 // Check if the naming class in which the unresolved members were found is
6478 // related (same as or is a base of) to the enclosing class.
6479
6480 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6481 return;
6482
6483
6484 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6485 // If the enclosing function is not dependent, then this lambda is
6486 // capture ready, so if we can capture this, do so.
6487 if (!EnclosingFunctionCtx->isDependentContext()) {
6488 // If the current lambda and all enclosing lambdas can capture 'this' -
6489 // then go ahead and capture 'this' (since our unresolved overload set
6490 // contains at least one non-static member function).
6491 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6492 S.CheckCXXThisCapture(CallLoc);
6493 } else if (S.CurContext->isDependentContext()) {
6494 // ... since this is an implicit member reference, that might potentially
6495 // involve a 'this' capture, mark 'this' for potential capture in
6496 // enclosing lambdas.
6497 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6498 CurLSI->addPotentialThisCapture(CallLoc);
6499 }
6500}
6501
6502// Once a call is fully resolved, warn for unqualified calls to specific
6503// C++ standard functions, like move and forward.
6504static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6505 // We are only checking unary move and forward so exit early here.
6506 if (Call->getNumArgs() != 1)
6507 return;
6508
6509 Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6510 if (!E || isa<UnresolvedLookupExpr>(E))
6511 return;
6512 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6513 if (!DRE || !DRE->getLocation().isValid())
6514 return;
6515
6516 if (DRE->getQualifier())
6517 return;
6518
6519 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Call->getCalleeDecl());
6520 if (!D || !D->isInStdNamespace())
6521 return;
6522
6523 // Only warn for some functions deemed more frequent or problematic.
6524 static constexpr llvm::StringRef SpecialFunctions[] = {"move", "forward"};
6525 auto it = llvm::find(SpecialFunctions, D->getName());
6526 if (it == std::end(SpecialFunctions))
6527 return;
6528
6529 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6530 << D->getQualifiedNameAsString()
6531 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6532}
6533
6534ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6535 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6536 Expr *ExecConfig) {
6537 ExprResult Call =
6538 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6539 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6540 if (Call.isInvalid())
6541 return Call;
6542
6543 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6544 // language modes.
6545 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6546 if (ULE->hasExplicitTemplateArgs() &&
6547 ULE->decls_begin() == ULE->decls_end()) {
6548 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6549 ? diag::warn_cxx17_compat_adl_only_template_id
6550 : diag::ext_adl_only_template_id)
6551 << ULE->getName();
6552 }
6553 }
6554
6555 if (LangOpts.OpenMP)
6556 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6557 ExecConfig);
6558 if (LangOpts.CPlusPlus) {
6559 CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6560 if (CE)
6561 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6562 }
6563 return Call;
6564}
6565
6566/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6567/// This provides the location of the left/right parens and a list of comma
6568/// locations.
6569ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6570 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6571 Expr *ExecConfig, bool IsExecConfig,
6572 bool AllowRecovery) {
6573 // Since this might be a postfix expression, get rid of ParenListExprs.
6574 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6575 if (Result.isInvalid()) return ExprError();
6576 Fn = Result.get();
6577
6578 if (checkArgsForPlaceholders(*this, ArgExprs))
6579 return ExprError();
6580
6581 if (getLangOpts().CPlusPlus) {
6582 // If this is a pseudo-destructor expression, build the call immediately.
6583 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6584 if (!ArgExprs.empty()) {
6585 // Pseudo-destructor calls should not have any arguments.
6586 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6587 << FixItHint::CreateRemoval(
6588 SourceRange(ArgExprs.front()->getBeginLoc(),
6589 ArgExprs.back()->getEndLoc()));
6590 }
6591
6592 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6593 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6594 }
6595 if (Fn->getType() == Context.PseudoObjectTy) {
6596 ExprResult result = CheckPlaceholderExpr(Fn);
6597 if (result.isInvalid()) return ExprError();
6598 Fn = result.get();
6599 }
6600
6601 // Determine whether this is a dependent call inside a C++ template,
6602 // in which case we won't do any semantic analysis now.
6603 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6604 if (ExecConfig) {
6605 return CUDAKernelCallExpr::Create(Context, Fn,
6606 cast<CallExpr>(ExecConfig), ArgExprs,
6607 Context.DependentTy, VK_PRValue,
6608 RParenLoc, CurFPFeatureOverrides());
6609 } else {
6610
6611 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6612 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6613 Fn->getBeginLoc());
6614
6615 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6616 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6617 }
6618 }
6619
6620 // Determine whether this is a call to an object (C++ [over.call.object]).
6621 if (Fn->getType()->isRecordType())
6622 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6623 RParenLoc);
6624
6625 if (Fn->getType() == Context.UnknownAnyTy) {
6626 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6627 if (result.isInvalid()) return ExprError();
6628 Fn = result.get();
6629 }
6630
6631 if (Fn->getType() == Context.BoundMemberTy) {
6632 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6633 RParenLoc, ExecConfig, IsExecConfig,
6634 AllowRecovery);
6635 }
6636 }
6637
6638 // Check for overloaded calls. This can happen even in C due to extensions.
6639 if (Fn->getType() == Context.OverloadTy) {
6640 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6641
6642 // We aren't supposed to apply this logic if there's an '&' involved.
6643 if (!find.HasFormOfMemberPointer) {
6644 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6645 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6646 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6647 OverloadExpr *ovl = find.Expression;
6648 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6649 return BuildOverloadedCallExpr(
6650 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6651 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6652 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6653 RParenLoc, ExecConfig, IsExecConfig,
6654 AllowRecovery);
6655 }
6656 }
6657
6658 // If we're directly calling a function, get the appropriate declaration.
6659 if (Fn->getType() == Context.UnknownAnyTy) {
6660 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6661 if (result.isInvalid()) return ExprError();
6662 Fn = result.get();
6663 }
6664
6665 Expr *NakedFn = Fn->IgnoreParens();
6666
6667 bool CallingNDeclIndirectly = false;
6668 NamedDecl *NDecl = nullptr;
6669 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6670 if (UnOp->getOpcode() == UO_AddrOf) {
6671 CallingNDeclIndirectly = true;
6672 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6673 }
6674 }
6675
6676 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6677 NDecl = DRE->getDecl();
6678
6679 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6680 if (FDecl && FDecl->getBuiltinID()) {
6681 // Rewrite the function decl for this builtin by replacing parameters
6682 // with no explicit address space with the address space of the arguments
6683 // in ArgExprs.
6684 if ((FDecl =
6685 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6686 NDecl = FDecl;
6687 Fn = DeclRefExpr::Create(
6688 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6689 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6690 nullptr, DRE->isNonOdrUse());
6691 }
6692 }
6693 } else if (isa<MemberExpr>(NakedFn))
6694 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6695
6696 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6697 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6698 FD, /*Complain=*/true, Fn->getBeginLoc()))
6699 return ExprError();
6700
6701 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6702
6703 // If this expression is a call to a builtin function in HIP device
6704 // compilation, allow a pointer-type argument to default address space to be
6705 // passed as a pointer-type parameter to a non-default address space.
6706 // If Arg is declared in the default address space and Param is declared
6707 // in a non-default address space, perform an implicit address space cast to
6708 // the parameter type.
6709 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6710 FD->getBuiltinID()) {
6711 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6712 ParmVarDecl *Param = FD->getParamDecl(Idx);
6713 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6714 !ArgExprs[Idx]->getType()->isPointerType())
6715 continue;
6716
6717 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6718 auto ArgTy = ArgExprs[Idx]->getType();
6719 auto ArgPtTy = ArgTy->getPointeeType();
6720 auto ArgAS = ArgPtTy.getAddressSpace();
6721
6722 // Add address space cast if target address spaces are different
6723 bool NeedImplicitASC =
6724 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6725 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6726 // or from specific AS which has target AS matching that of Param.
6727 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6728 if (!NeedImplicitASC)
6729 continue;
6730
6731 // First, ensure that the Arg is an RValue.
6732 if (ArgExprs[Idx]->isGLValue()) {
6733 ArgExprs[Idx] = ImplicitCastExpr::Create(
6734 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6735 nullptr, VK_PRValue, FPOptionsOverride());
6736 }
6737
6738 // Construct a new arg type with address space of Param
6739 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6740 ArgPtQuals.setAddressSpace(ParamAS);
6741 auto NewArgPtTy =
6742 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6743 auto NewArgTy =
6744 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6745 ArgTy.getQualifiers());
6746
6747 // Finally perform an implicit address space cast
6748 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6749 CK_AddressSpaceConversion)
6750 .get();
6751 }
6752 }
6753 }
6754
6755 if (Context.isDependenceAllowed() &&
6756 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6757 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 6757, __extension__ __PRETTY_FUNCTION__))
;
6758 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", 6761, __extension__ __PRETTY_FUNCTION__
))
6759 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", 6761, __extension__ __PRETTY_FUNCTION__
))
6760 [](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", 6761, __extension__ __PRETTY_FUNCTION__
))
6761 "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", 6761, __extension__ __PRETTY_FUNCTION__
))
;
6762 QualType ReturnType =
6763 llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6764 ? cast<FunctionDecl>(NDecl)->getCallResultType()
6765 : Context.DependentTy;
6766 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6767 Expr::getValueKindForType(ReturnType), RParenLoc,
6768 CurFPFeatureOverrides());
6769 }
6770 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6771 ExecConfig, IsExecConfig);
6772}
6773
6774/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6775// with the specified CallArgs
6776Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6777 MultiExprArg CallArgs) {
6778 StringRef Name = Context.BuiltinInfo.getName(Id);
6779 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6780 Sema::LookupOrdinaryName);
6781 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6782
6783 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6784 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", 6784, __extension__ __PRETTY_FUNCTION__
))
;
6785
6786 ExprResult DeclRef =
6787 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6788 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", 6788, __extension__ __PRETTY_FUNCTION__
))
;
6789
6790 ExprResult Call =
6791 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6792
6793 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", 6793, __extension__ __PRETTY_FUNCTION__
))
;
6794 return Call.get();
6795}
6796
6797/// Parse a __builtin_astype expression.
6798///
6799/// __builtin_astype( value, dst type )
6800///
6801ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6802 SourceLocation BuiltinLoc,
6803 SourceLocation RParenLoc) {
6804 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6805 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6806}
6807
6808/// Create a new AsTypeExpr node (bitcast) from the arguments.
6809ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6810 SourceLocation BuiltinLoc,
6811 SourceLocation RParenLoc) {
6812 ExprValueKind VK = VK_PRValue;
6813 ExprObjectKind OK = OK_Ordinary;
6814 QualType SrcTy = E->getType();
6815 if (!SrcTy->isDependentType() &&
6816 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6817 return ExprError(
6818 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6819 << DestTy << SrcTy << E->getSourceRange());
6820 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6821}
6822
6823/// ActOnConvertVectorExpr - create a new convert-vector expression from the
6824/// provided arguments.
6825///
6826/// __builtin_convertvector( value, dst type )
6827///
6828ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6829 SourceLocation BuiltinLoc,
6830 SourceLocation RParenLoc) {
6831 TypeSourceInfo *TInfo;
6832 GetTypeFromParser(ParsedDestTy, &TInfo);
6833 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6834}
6835
6836/// BuildResolvedCallExpr - Build a call to a resolved expression,
6837/// i.e. an expression not of \p OverloadTy. The expression should
6838/// unary-convert to an expression of function-pointer or
6839/// block-pointer type.
6840///
6841/// \param NDecl the declaration being called, if available
6842ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6843 SourceLocation LParenLoc,
6844 ArrayRef<Expr *> Args,
6845 SourceLocation RParenLoc, Expr *Config,
6846 bool IsExecConfig, ADLCallKind UsesADL) {
6847 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6848 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6849
6850 // Functions with 'interrupt' attribute cannot be called directly.
6851 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6852 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6853 return ExprError();
6854 }
6855
6856 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6857 // so there's some risk when calling out to non-interrupt handler functions
6858 // that the callee might not preserve them. This is easy to diagnose here,
6859 // but can be very challenging to debug.
6860 // Likewise, X86 interrupt handlers may only call routines with attribute
6861 // no_caller_saved_registers since there is no efficient way to
6862 // save and restore the non-GPR state.
6863 if (auto *Caller = getCurFunctionDecl()) {
6864 if (Caller->hasAttr<ARMInterruptAttr>()) {
6865 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6866 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6867 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6868 if (FDecl)
6869 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6870 }
6871 }
6872 if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6873 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6874 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6875 if (FDecl)
6876 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6877 }
6878 }
6879
6880 // Promote the function operand.
6881 // We special-case function promotion here because we only allow promoting
6882 // builtin functions to function pointers in the callee of a call.
6883 ExprResult Result;
6884 QualType ResultTy;
6885 if (BuiltinID &&
6886 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6887 // Extract the return type from the (builtin) function pointer type.
6888 // FIXME Several builtins still have setType in
6889 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6890 // Builtins.def to ensure they are correct before removing setType calls.
6891 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6892 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6893 ResultTy = FDecl->getCallResultType();
6894 } else {
6895 Result = CallExprUnaryConversions(Fn);
6896 ResultTy = Context.BoolTy;
6897 }
6898 if (Result.isInvalid())
6899 return ExprError();
6900 Fn = Result.get();
6901
6902 // Check for a valid function type, but only if it is not a builtin which
6903 // requires custom type checking. These will be handled by
6904 // CheckBuiltinFunctionCall below just after creation of the call expression.
6905 const FunctionType *FuncT = nullptr;
6906 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6907 retry:
6908 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6909 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6910 // have type pointer to function".
6911 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6912 if (!FuncT)
6913 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6914 << Fn->getType() << Fn->getSourceRange());
6915 } else if (const BlockPointerType *BPT =
6916 Fn->getType()->getAs<BlockPointerType>()) {
6917 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6918 } else {
6919 // Handle calls to expressions of unknown-any type.
6920 if (Fn->getType() == Context.UnknownAnyTy) {
6921 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6922 if (rewrite.isInvalid())
6923 return ExprError();
6924 Fn = rewrite.get();
6925 goto retry;
6926 }
6927
6928 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6929 << Fn->getType() << Fn->getSourceRange());
6930 }
6931 }
6932
6933 // Get the number of parameters in the function prototype, if any.
6934 // We will allocate space for max(Args.size(), NumParams) arguments
6935 // in the call expression.
6936 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6937 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6938
6939 CallExpr *TheCall;
6940 if (Config) {
6941 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", 6942, __extension__ __PRETTY_FUNCTION__
))
6942 "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", 6942, __extension__ __PRETTY_FUNCTION__
))
;
6943 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6944 Args, ResultTy, VK_PRValue, RParenLoc,
6945 CurFPFeatureOverrides(), NumParams);
6946 } else {
6947 TheCall =
6948 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6949 CurFPFeatureOverrides(), NumParams, UsesADL);
6950 }
6951
6952 if (!Context.isDependenceAllowed()) {
6953 // Forget about the nulled arguments since typo correction
6954 // do not handle them well.
6955 TheCall->shrinkNumArgs(Args.size());
6956 // C cannot always handle TypoExpr nodes in builtin calls and direct
6957 // function calls as their argument checking don't necessarily handle
6958 // dependent types properly, so make sure any TypoExprs have been
6959 // dealt with.
6960 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6961 if (!Result.isUsable()) return ExprError();
6962 CallExpr *TheOldCall = TheCall;
6963 TheCall = dyn_cast<CallExpr>(Result.get());
6964 bool CorrectedTypos = TheCall != TheOldCall;
6965 if (!TheCall) return Result;
6966 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6967
6968 // A new call expression node was created if some typos were corrected.
6969 // However it may not have been constructed with enough storage. In this
6970 // case, rebuild the node with enough storage. The waste of space is
6971 // immaterial since this only happens when some typos were corrected.
6972 if (CorrectedTypos && Args.size() < NumParams) {
6973 if (Config)
6974 TheCall = CUDAKernelCallExpr::Create(
6975 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6976 RParenLoc, CurFPFeatureOverrides(), NumParams);
6977 else
6978 TheCall =
6979 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6980 CurFPFeatureOverrides(), NumParams, UsesADL);
6981 }
6982 // We can now handle the nulled arguments for the default arguments.
6983 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6984 }
6985
6986 // Bail out early if calling a builtin with custom type checking.
6987 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6988 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6989
6990 if (getLangOpts().CUDA) {
6991 if (Config) {
6992 // CUDA: Kernel calls must be to global functions
6993 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6994 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6995 << FDecl << Fn->getSourceRange());
6996
6997 // CUDA: Kernel function must have 'void' return type
6998 if (!FuncT->getReturnType()->isVoidType() &&
6999 !FuncT->getReturnType()->getAs<AutoType>() &&
7000 !FuncT->getReturnType()->isInstantiationDependentType())
7001 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7002 << Fn->getType() << Fn->getSourceRange());
7003 } else {
7004 // CUDA: Calls to global functions must be configured
7005 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7006 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7007 << FDecl << Fn->getSourceRange());
7008 }
7009 }
7010
7011 // Check for a valid return type
7012 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7013 FDecl))
7014 return ExprError();
7015
7016 // We know the result type of the call, set it.
7017 TheCall->setType(FuncT->getCallResultType(Context));
7018 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7019
7020 if (Proto) {
7021 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7022 IsExecConfig))
7023 return ExprError();
7024 } else {
7025 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", 7025, __extension__ __PRETTY_FUNCTION__
))
;
7026
7027 if (FDecl) {
7028 // Check if we have too few/too many template arguments, based
7029 // on our knowledge of the function definition.
7030 const FunctionDecl *Def = nullptr;
7031 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7032 Proto = Def->getType()->getAs<FunctionProtoType>();
7033 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7034 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7035 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7036 }
7037
7038 // If the function we're calling isn't a function prototype, but we have
7039 // a function prototype from a prior declaratiom, use that prototype.
7040 if (!FDecl->hasPrototype())
7041 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7042 }
7043
7044 // Promote the arguments (C99 6.5.2.2p6).
7045 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7046 Expr *Arg = Args[i];
7047
7048 if (Proto && i < Proto->getNumParams()) {
7049 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7050 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7051 ExprResult ArgE =
7052 PerformCopyInitialization(Entity, SourceLocation(), Arg);
7053 if (ArgE.isInvalid())
7054 return true;
7055
7056 Arg = ArgE.getAs<Expr>();
7057
7058 } else {
7059 ExprResult ArgE = DefaultArgumentPromotion(Arg);
7060
7061 if (ArgE.isInvalid())
7062 return true;
7063
7064 Arg = ArgE.getAs<Expr>();
7065 }
7066
7067 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7068 diag::err_call_incomplete_argument, Arg))
7069 return ExprError();
7070
7071 TheCall->setArg(i, Arg);
7072 }
7073 TheCall->computeDependence();
7074 }
7075
7076 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7077 if (!Method->isStatic())
7078 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7079 << Fn->getSourceRange());
7080
7081 // Check for sentinels
7082 if (NDecl)
7083 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7084
7085 // Warn for unions passing across security boundary (CMSE).
7086 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7087 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7088 if (const auto *RT =
7089 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7090 if (RT->getDecl()->isOrContainsUnion())
7091 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7092 << 0 << i;
7093 }
7094 }
7095 }
7096
7097 // Do special checking on direct calls to functions.
7098 if (FDecl) {
7099 if (CheckFunctionCall(FDecl, TheCall, Proto))
7100 return ExprError();
7101
7102 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7103
7104 if (BuiltinID)
7105 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7106 } else if (NDecl) {
7107 if (CheckPointerCall(NDecl, TheCall, Proto))
7108 return ExprError();
7109 } else {
7110 if (CheckOtherCall(TheCall, Proto))
7111 return ExprError();
7112 }
7113
7114 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7115}
7116
7117ExprResult
7118Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7119 SourceLocation RParenLoc, Expr *InitExpr) {
7120 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", 7120, __extension__ __PRETTY_FUNCTION__
))
;
7121 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", 7121, __extension__ __PRETTY_FUNCTION__
))
;
7122
7123 TypeSourceInfo *TInfo;
7124 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7125 if (!TInfo)
7126 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7127
7128 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7129}
7130
7131ExprResult
7132Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7133 SourceLocation RParenLoc, Expr *LiteralExpr) {
7134 QualType literalType = TInfo->getType();
7135
7136 if (literalType->isArrayType()) {
7137 if (RequireCompleteSizedType(
7138 LParenLoc, Context.getBaseElementType(literalType),
7139 diag::err_array_incomplete_or_sizeless_type,
7140 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7141 return ExprError();
7142 if (literalType->isVariableArrayType()) {
7143 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7144 diag::err_variable_object_no_init)) {
7145 return ExprError();
7146 }
7147 }
7148 } else if (!literalType->isDependentType() &&
7149 RequireCompleteType(LParenLoc, literalType,
7150 diag::err_typecheck_decl_incomplete_type,
7151 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7152 return ExprError();
7153
7154 InitializedEntity Entity
7155 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7156 InitializationKind Kind
7157 = InitializationKind::CreateCStyleCast(LParenLoc,
7158 SourceRange(LParenLoc, RParenLoc),
7159 /*InitList=*/true);
7160 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7161 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7162 &literalType);
7163 if (Result.isInvalid())
7164 return ExprError();
7165 LiteralExpr = Result.get();
7166
7167 bool isFileScope = !CurContext->isFunctionOrMethod();
7168
7169 // In C, compound literals are l-values for some reason.
7170 // For GCC compatibility, in C++, file-scope array compound literals with
7171 // constant initializers are also l-values, and compound literals are
7172 // otherwise prvalues.
7173 //
7174 // (GCC also treats C++ list-initialized file-scope array prvalues with
7175 // constant initializers as l-values, but that's non-conforming, so we don't
7176 // follow it there.)
7177 //
7178 // FIXME: It would be better to handle the lvalue cases as materializing and
7179 // lifetime-extending a temporary object, but our materialized temporaries
7180 // representation only supports lifetime extension from a variable, not "out
7181 // of thin air".
7182 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7183 // is bound to the result of applying array-to-pointer decay to the compound
7184 // literal.
7185 // FIXME: GCC supports compound literals of reference type, which should
7186 // obviously have a value kind derived from the kind of reference involved.
7187 ExprValueKind VK =
7188 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7189 ? VK_PRValue
7190 : VK_LValue;
7191
7192 if (isFileScope)
7193 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7194 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7195 Expr *Init = ILE->getInit(i);
7196 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7197 }
7198
7199 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7200 VK, LiteralExpr, isFileScope);
7201 if (isFileScope) {
7202 if (!LiteralExpr->isTypeDependent() &&
7203 !LiteralExpr->isValueDependent() &&
7204 !literalType->isDependentType()) // C99 6.5.2.5p3
7205 if (CheckForConstantInitializer(LiteralExpr, literalType))
7206 return ExprError();
7207 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7208 literalType.getAddressSpace() != LangAS::Default) {
7209 // Embedded-C extensions to C99 6.5.2.5:
7210 // "If the compound literal occurs inside the body of a function, the
7211 // type name shall not be qualified by an address-space qualifier."
7212 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7213 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7214 return ExprError();
7215 }
7216
7217 if (!isFileScope && !getLangOpts().CPlusPlus) {
7218 // Compound literals that have automatic storage duration are destroyed at
7219 // the end of the scope in C; in C++, they're just temporaries.
7220
7221 // Emit diagnostics if it is or contains a C union type that is non-trivial
7222 // to destruct.
7223 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7224 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7225 NTCUC_CompoundLiteral, NTCUK_Destruct);
7226
7227 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7228 if (literalType.isDestructedType()) {
7229 Cleanup.setExprNeedsCleanups(true);
7230 ExprCleanupObjects.push_back(E);
7231 getCurFunction()->setHasBranchProtectedScope();
7232 }
7233 }
7234
7235 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7236 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7237 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7238 E->getInitializer()->getExprLoc());
7239
7240 return MaybeBindToTemporary(E);
7241}
7242
7243ExprResult
7244Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7245 SourceLocation RBraceLoc) {
7246 // Only produce each kind of designated initialization diagnostic once.
7247 SourceLocation FirstDesignator;
7248 bool DiagnosedArrayDesignator = false;
7249 bool DiagnosedNestedDesignator = false;
7250 bool DiagnosedMixedDesignator = false;
7251
7252 // Check that any designated initializers are syntactically valid in the
7253 // current language mode.
7254 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7255 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7256 if (FirstDesignator.isInvalid())
7257 FirstDesignator = DIE->getBeginLoc();
7258
7259 if (!getLangOpts().CPlusPlus)
7260 break;
7261
7262 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7263 DiagnosedNestedDesignator = true;
7264 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7265 << DIE->getDesignatorsSourceRange();
7266 }
7267
7268 for (auto &Desig : DIE->designators()) {
7269 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7270 DiagnosedArrayDesignator = true;
7271 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7272 << Desig.getSourceRange();
7273 }
7274 }
7275
7276 if (!DiagnosedMixedDesignator &&
7277 !isa<DesignatedInitExpr>(InitArgList[0])) {
7278 DiagnosedMixedDesignator = true;
7279 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7280 << DIE->getSourceRange();
7281 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7282 << InitArgList[0]->getSourceRange();
7283 }
7284 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7285 isa<DesignatedInitExpr>(InitArgList[0])) {
7286 DiagnosedMixedDesignator = true;
7287 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7288 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7289 << DIE->getSourceRange();
7290 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7291 << InitArgList[I]->getSourceRange();
7292 }
7293 }
7294
7295 if (FirstDesignator.isValid()) {
7296 // Only diagnose designated initiaization as a C++20 extension if we didn't
7297 // already diagnose use of (non-C++20) C99 designator syntax.
7298 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7299 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7300 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7301 ? diag::warn_cxx17_compat_designated_init
7302 : diag::ext_cxx_designated_init);
7303 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7304 Diag(FirstDesignator, diag::ext_designated_init);
7305 }
7306 }
7307
7308 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7309}
7310
7311ExprResult
7312Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7313 SourceLocation RBraceLoc) {
7314 // Semantic analysis for initializers is done by ActOnDeclarator() and
7315 // CheckInitializer() - it requires knowledge of the object being initialized.
7316
7317 // Immediately handle non-overload placeholders. Overloads can be
7318 // resolved contextually, but everything else here can't.
7319 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7320 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7321 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7322
7323 // Ignore failures; dropping the entire initializer list because
7324 // of one failure would be terrible for indexing/etc.
7325 if (result.isInvalid()) continue;
7326
7327 InitArgList[I] = result.get();
7328 }
7329 }
7330
7331 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7332 RBraceLoc);
7333 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7334 return E;
7335}
7336
7337/// Do an explicit extend of the given block pointer if we're in ARC.
7338void Sema::maybeExtendBlockObject(ExprResult &E) {
7339 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", 7339, __extension__ __PRETTY_FUNCTION__
))
;
7340 assert(E.get()->isPRValue())(static_cast <bool> (E.get()->isPRValue()) ? void (0
) : __assert_fail ("E.get()->isPRValue()", "clang/lib/Sema/SemaExpr.cpp"
, 7340, __extension__ __PRETTY_FUNCTION__))
;
7341
7342 // Only do this in an r-value context.
7343 if (!getLangOpts().ObjCAutoRefCount) return;
7344
7345 E = ImplicitCastExpr::Create(
7346 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7347 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7348 Cleanup.setExprNeedsCleanups(true);
7349}
7350
7351/// Prepare a conversion of the given expression to an ObjC object
7352/// pointer type.
7353CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7354 QualType type = E.get()->getType();
7355 if (type->isObjCObjectPointerType()) {
7356 return CK_BitCast;
7357 } else if (type->isBlockPointerType()) {
7358 maybeExtendBlockObject(E);
7359 return CK_BlockPointerToObjCPointerCast;
7360 } else {
7361 assert(type->isPointerType())(static_cast <bool> (type->isPointerType()) ? void (
0) : __assert_fail ("type->isPointerType()", "clang/lib/Sema/SemaExpr.cpp"
, 7361, __extension__ __PRETTY_FUNCTION__))
;
7362 return CK_CPointerToObjCPointerCast;
7363 }
7364}
7365
7366/// Prepares for a scalar cast, performing all the necessary stages
7367/// except the final cast and returning the kind required.
7368CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7369 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7370 // Also, callers should have filtered out the invalid cases with
7371 // pointers. Everything else should be possible.
7372
7373 QualType SrcTy = Src.get()->getType();
7374 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7375 return CK_NoOp;
7376
7377 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7378 case Type::STK_MemberPointer:
7379 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7379)
;
7380
7381 case Type::STK_CPointer:
7382 case Type::STK_BlockPointer:
7383 case Type::STK_ObjCObjectPointer:
7384 switch (DestTy->getScalarTypeKind()) {
7385 case Type::STK_CPointer: {
7386 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7387 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7388 if (SrcAS != DestAS)
7389 return CK_AddressSpaceConversion;
7390 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7391 return CK_NoOp;
7392 return CK_BitCast;
7393 }
7394 case Type::STK_BlockPointer:
7395 return (SrcKind == Type::STK_BlockPointer
7396 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7397 case Type::STK_ObjCObjectPointer:
7398 if (SrcKind == Type::STK_ObjCObjectPointer)
7399 return CK_BitCast;
7400 if (SrcKind == Type::STK_CPointer)
7401 return CK_CPointerToObjCPointerCast;
7402 maybeExtendBlockObject(Src);
7403 return CK_BlockPointerToObjCPointerCast;
7404 case Type::STK_Bool:
7405 return CK_PointerToBoolean;
7406 case Type::STK_Integral:
7407 return CK_PointerToIntegral;
7408 case Type::STK_Floating:
7409 case Type::STK_FloatingComplex:
7410 case Type::STK_IntegralComplex:
7411 case Type::STK_MemberPointer:
7412 case Type::STK_FixedPoint:
7413 llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer"
, "clang/lib/Sema/SemaExpr.cpp", 7413)
;
7414 }
7415 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7415)
;
7416
7417 case Type::STK_FixedPoint:
7418 switch (DestTy->getScalarTypeKind()) {
7419 case Type::STK_FixedPoint:
7420 return CK_FixedPointCast;
7421 case Type::STK_Bool:
7422 return CK_FixedPointToBoolean;
7423 case Type::STK_Integral:
7424 return CK_FixedPointToIntegral;
7425 case Type::STK_Floating:
7426 return CK_FixedPointToFloating;
7427 case Type::STK_IntegralComplex:
7428 case Type::STK_FloatingComplex:
7429 Diag(Src.get()->getExprLoc(),
7430 diag::err_unimplemented_conversion_with_fixed_point_type)
7431 << DestTy;
7432 return CK_IntegralCast;
7433 case Type::STK_CPointer:
7434 case Type::STK_ObjCObjectPointer:
7435 case Type::STK_BlockPointer:
7436 case Type::STK_MemberPointer:
7437 llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type"
, "clang/lib/Sema/SemaExpr.cpp", 7437)
;
7438 }
7439 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7439)
;
7440
7441 case Type::STK_Bool: // casting from bool is like casting from an integer
7442 case Type::STK_Integral:
7443 switch (DestTy->getScalarTypeKind()) {
7444 case Type::STK_CPointer:
7445 case Type::STK_ObjCObjectPointer:
7446 case Type::STK_BlockPointer:
7447 if (Src.get()->isNullPointerConstant(Context,
7448 Expr::NPC_ValueDependentIsNull))
7449 return CK_NullToPointer;
7450 return CK_IntegralToPointer;
7451 case Type::STK_Bool:
7452 return CK_IntegralToBoolean;
7453 case Type::STK_Integral:
7454 return CK_IntegralCast;
7455 case Type::STK_Floating:
7456 return CK_IntegralToFloating;
7457 case Type::STK_IntegralComplex:
7458 Src = ImpCastExprToType(Src.get(),
7459 DestTy->castAs<ComplexType>()->getElementType(),
7460 CK_IntegralCast);
7461 return CK_IntegralRealToComplex;
7462 case Type::STK_FloatingComplex:
7463 Src = ImpCastExprToType(Src.get(),
7464 DestTy->castAs<ComplexType>()->getElementType(),
7465 CK_IntegralToFloating);
7466 return CK_FloatingRealToComplex;
7467 case Type::STK_MemberPointer:
7468 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7468)
;
7469 case Type::STK_FixedPoint:
7470 return CK_IntegralToFixedPoint;
7471 }
7472 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7472)
;
7473
7474 case Type::STK_Floating:
7475 switch (DestTy->getScalarTypeKind()) {
7476 case Type::STK_Floating:
7477 return CK_FloatingCast;
7478 case Type::STK_Bool:
7479 return CK_FloatingToBoolean;
7480 case Type::STK_Integral:
7481 return CK_FloatingToIntegral;
7482 case Type::STK_FloatingComplex:
7483 Src = ImpCastExprToType(Src.get(),
7484 DestTy->castAs<ComplexType>()->getElementType(),
7485 CK_FloatingCast);
7486 return CK_FloatingRealToComplex;
7487 case Type::STK_IntegralComplex:
7488 Src = ImpCastExprToType(Src.get(),
7489 DestTy->castAs<ComplexType>()->getElementType(),
7490 CK_FloatingToIntegral);
7491 return CK_IntegralRealToComplex;
7492 case Type::STK_CPointer:
7493 case Type::STK_ObjCObjectPointer:
7494 case Type::STK_BlockPointer:
7495 llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7495)
;
7496 case Type::STK_MemberPointer:
7497 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7497)
;
7498 case Type::STK_FixedPoint:
7499 return CK_FloatingToFixedPoint;
7500 }
7501 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7501)
;
7502
7503 case Type::STK_FloatingComplex:
7504 switch (DestTy->getScalarTypeKind()) {
7505 case Type::STK_FloatingComplex:
7506 return CK_FloatingComplexCast;
7507 case Type::STK_IntegralComplex:
7508 return CK_FloatingComplexToIntegralComplex;
7509 case Type::STK_Floating: {
7510 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7511 if (Context.hasSameType(ET, DestTy))
7512 return CK_FloatingComplexToReal;
7513 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7514 return CK_FloatingCast;
7515 }
7516 case Type::STK_Bool:
7517 return CK_FloatingComplexToBoolean;
7518 case Type::STK_Integral:
7519 Src = ImpCastExprToType(Src.get(),
7520 SrcTy->castAs<ComplexType>()->getElementType(),
7521 CK_FloatingComplexToReal);
7522 return CK_FloatingToIntegral;
7523 case Type::STK_CPointer:
7524 case Type::STK_ObjCObjectPointer:
7525 case Type::STK_BlockPointer:
7526 llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7526)
;
7527 case Type::STK_MemberPointer:
7528 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7528)
;
7529 case Type::STK_FixedPoint:
7530 Diag(Src.get()->getExprLoc(),
7531 diag::err_unimplemented_conversion_with_fixed_point_type)
7532 << SrcTy;
7533 return CK_IntegralCast;
7534 }
7535 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7535)
;
7536
7537 case Type::STK_IntegralComplex:
7538 switch (DestTy->getScalarTypeKind()) {
7539 case Type::STK_FloatingComplex:
7540 return CK_IntegralComplexToFloatingComplex;
7541 case Type::STK_IntegralComplex:
7542 return CK_IntegralComplexCast;
7543 case Type::STK_Integral: {
7544 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7545 if (Context.hasSameType(ET, DestTy))
7546 return CK_IntegralComplexToReal;
7547 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7548 return CK_IntegralCast;
7549 }
7550 case Type::STK_Bool:
7551 return CK_IntegralComplexToBoolean;
7552 case Type::STK_Floating:
7553 Src = ImpCastExprToType(Src.get(),
7554 SrcTy->castAs<ComplexType>()->getElementType(),
7555 CK_IntegralComplexToReal);
7556 return CK_IntegralToFloating;
7557 case Type::STK_CPointer:
7558 case Type::STK_ObjCObjectPointer:
7559 case Type::STK_BlockPointer:
7560 llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7560)
;
7561 case Type::STK_MemberPointer:
7562 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7562)
;
7563 case Type::STK_FixedPoint:
7564 Diag(Src.get()->getExprLoc(),
7565 diag::err_unimplemented_conversion_with_fixed_point_type)
7566 << SrcTy;
7567 return CK_IntegralCast;
7568 }
7569 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7569)
;
7570 }
7571
7572 llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "clang/lib/Sema/SemaExpr.cpp"
, 7572)
;
7573}
7574
7575static bool breakDownVectorType(QualType type, uint64_t &len,
7576 QualType &eltType) {
7577 // Vectors are simple.
7578 if (const VectorType *vecType = type->getAs<VectorType>()) {
7579 len = vecType->getNumElements();
7580 eltType = vecType->getElementType();
7581 assert(eltType->isScalarType())(static_cast <bool> (eltType->isScalarType()) ? void
(0) : __assert_fail ("eltType->isScalarType()", "clang/lib/Sema/SemaExpr.cpp"
, 7581, __extension__ __PRETTY_FUNCTION__))
;
7582 return true;
7583 }
7584
7585 // We allow lax conversion to and from non-vector types, but only if
7586 // they're real types (i.e. non-complex, non-pointer scalar types).
7587 if (!type->isRealType()) return false;
7588
7589 len = 1;
7590 eltType = type;
7591 return true;
7592}
7593
7594/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7595/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7596/// allowed?
7597///
7598/// This will also return false if the two given types do not make sense from
7599/// the perspective of SVE bitcasts.
7600bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7601 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", 7601, __extension__ __PRETTY_FUNCTION__
))
;
7602
7603 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7604 if (!FirstType->isSizelessBuiltinType())
7605 return false;
7606
7607 const auto *VecTy = SecondType->getAs<VectorType>();
7608 return VecTy &&
7609 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7610 };
7611
7612 return ValidScalableConversion(srcTy, destTy) ||
7613 ValidScalableConversion(destTy, srcTy);
7614}
7615
7616/// Are the two types matrix types and do they have the same dimensions i.e.
7617/// do they have the same number of rows and the same number of columns?
7618bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7619 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7620 return false;
7621
7622 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7623 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7624
7625 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7626 matSrcType->getNumColumns() == matDestType->getNumColumns();
7627}
7628
7629bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7630 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", 7630, __extension__ __PRETTY_FUNCTION__
))
;
7631
7632 uint64_t SrcLen, DestLen;
7633 QualType SrcEltTy, DestEltTy;
7634 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7635 return false;
7636 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7637 return false;
7638
7639 // ASTContext::getTypeSize will return the size rounded up to a
7640 // power of 2, so instead of using that, we need to use the raw
7641 // element size multiplied by the element count.
7642 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7643 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7644
7645 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7646}
7647
7648/// Are the two types lax-compatible vector types? That is, given
7649/// that one of them is a vector, do they have equal storage sizes,
7650/// where the storage size is the number of elements times the element
7651/// size?
7652///
7653/// This will also return false if either of the types is neither a
7654/// vector nor a real type.
7655bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7656 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", 7656, __extension__ __PRETTY_FUNCTION__
))
;
7657
7658 // Disallow lax conversions between scalars and ExtVectors (these
7659 // conversions are allowed for other vector types because common headers
7660 // depend on them). Most scalar OP ExtVector cases are handled by the
7661 // splat path anyway, which does what we want (convert, not bitcast).
7662 // What this rules out for ExtVectors is crazy things like char4*float.
7663 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7664 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7665
7666 return areVectorTypesSameSize(srcTy, destTy);
7667}
7668
7669/// Is this a legal conversion between two types, one of which is
7670/// known to be a vector type?
7671bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7672 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", 7672, __extension__ __PRETTY_FUNCTION__
))
;
7673
7674 switch (Context.getLangOpts().getLaxVectorConversions()) {
7675 case LangOptions::LaxVectorConversionKind::None:
7676 return false;
7677
7678 case LangOptions::LaxVectorConversionKind::Integer:
7679 if (!srcTy->isIntegralOrEnumerationType()) {
7680 auto *Vec = srcTy->getAs<VectorType>();
7681 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7682 return false;
7683 }
7684 if (!destTy->isIntegralOrEnumerationType()) {
7685 auto *Vec = destTy->getAs<VectorType>();
7686 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7687 return false;
7688 }
7689 // OK, integer (vector) -> integer (vector) bitcast.
7690 break;
7691
7692 case LangOptions::LaxVectorConversionKind::All:
7693 break;
7694 }
7695
7696 return areLaxCompatibleVectorTypes(srcTy, destTy);
7697}
7698
7699bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7700 CastKind &Kind) {
7701 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7702 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7703 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7704 << DestTy << SrcTy << R;
7705 }
7706 } else if (SrcTy->isMatrixType()) {
7707 return Diag(R.getBegin(),
7708 diag::err_invalid_conversion_between_matrix_and_type)
7709 << SrcTy << DestTy << R;
7710 } else if (DestTy->isMatrixType()) {
7711 return Diag(R.getBegin(),
7712 diag::err_invalid_conversion_between_matrix_and_type)
7713 << DestTy << SrcTy << R;
7714 }
7715
7716 Kind = CK_MatrixCast;
7717 return false;
7718}
7719
7720bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7721 CastKind &Kind) {
7722 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", 7722, __extension__ __PRETTY_FUNCTION__
))
;
7723
7724 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7725 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7726 return Diag(R.getBegin(),
7727 Ty->isVectorType() ?
7728 diag::err_invalid_conversion_between_vectors :
7729 diag::err_invalid_conversion_between_vector_and_integer)
7730 << VectorTy << Ty << R;
7731 } else
7732 return Diag(R.getBegin(),
7733 diag::err_invalid_conversion_between_vector_and_scalar)
7734 << VectorTy << Ty << R;
7735
7736 Kind = CK_BitCast;
7737 return false;
7738}
7739
7740ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7741 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7742
7743 if (DestElemTy == SplattedExpr->getType())
7744 return SplattedExpr;
7745
7746 assert(DestElemTy->isFloatingType() ||(static_cast <bool> (DestElemTy->isFloatingType() ||
DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "clang/lib/Sema/SemaExpr.cpp", 7747, __extension__ __PRETTY_FUNCTION__
))
7747 DestElemTy->isIntegralOrEnumerationType())(static_cast <bool> (DestElemTy->isFloatingType() ||
DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "clang/lib/Sema/SemaExpr.cpp", 7747, __extension__ __PRETTY_FUNCTION__
))
;
7748
7749 CastKind CK;
7750 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7751 // OpenCL requires that we convert `true` boolean expressions to -1, but
7752 // only when splatting vectors.
7753 if (DestElemTy->isFloatingType()) {
7754 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7755 // in two steps: boolean to signed integral, then to floating.
7756 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7757 CK_BooleanToSignedIntegral);
7758 SplattedExpr = CastExprRes.get();
7759 CK = CK_IntegralToFloating;
7760 } else {
7761 CK = CK_BooleanToSignedIntegral;
7762 }
7763 } else {
7764 ExprResult CastExprRes = SplattedExpr;
7765 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7766 if (CastExprRes.isInvalid())
7767 return ExprError();
7768 SplattedExpr = CastExprRes.get();
7769 }
7770 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7771}
7772
7773ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7774 Expr *CastExpr, CastKind &Kind) {
7775 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", 7775, __extension__ __PRETTY_FUNCTION__
))
;
7776
7777 QualType SrcTy = CastExpr->getType();
7778
7779 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7780 // an ExtVectorType.
7781 // In OpenCL, casts between vectors of different types are not allowed.
7782 // (See OpenCL 6.2).
7783 if (SrcTy->isVectorType()) {
7784 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7785 (getLangOpts().OpenCL &&
7786 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7787 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7788 << DestTy << SrcTy << R;
7789 return ExprError();
7790 }
7791 Kind = CK_BitCast;
7792 return CastExpr;
7793 }
7794
7795 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7796 // conversion will take place first from scalar to elt type, and then
7797 // splat from elt type to vector.
7798 if (SrcTy->isPointerType())
7799 return Diag(R.getBegin(),
7800 diag::err_invalid_conversion_between_vector_and_scalar)
7801 << DestTy << SrcTy << R;
7802
7803 Kind = CK_VectorSplat;
7804 return prepareVectorSplat(DestTy, CastExpr);
7805}
7806
7807ExprResult
7808Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7809 Declarator &D, ParsedType &Ty,
7810 SourceLocation RParenLoc, Expr *CastExpr) {
7811 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", 7812, __extension__ __PRETTY_FUNCTION__
))
7812 "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", 7812, __extension__ __PRETTY_FUNCTION__
))
;
7813
7814 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7815 if (D.isInvalidType())
7816 return ExprError();
7817
7818 if (getLangOpts().CPlusPlus) {
7819 // Check that there are no default arguments (C++ only).
7820 CheckExtraCXXDefaultArguments(D);
7821 } else {
7822 // Make sure any TypoExprs have been dealt with.
7823 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7824 if (!Res.isUsable())
7825 return ExprError();
7826 CastExpr = Res.get();
7827 }
7828
7829 checkUnusedDeclAttributes(D);
7830
7831 QualType castType = castTInfo->getType();
7832 Ty = CreateParsedType(castType, castTInfo);
7833
7834 bool isVectorLiteral = false;
7835
7836 // Check for an altivec or OpenCL literal,
7837 // i.e. all the elements are integer constants.
7838 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7839 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7840 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7841 && castType->isVectorType() && (PE || PLE)) {
7842 if (PLE && PLE->getNumExprs() == 0) {
7843 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7844 return ExprError();
7845 }
7846 if (PE || PLE->getNumExprs() == 1) {
7847 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7848 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7849 isVectorLiteral = true;
7850 }
7851 else
7852 isVectorLiteral = true;
7853 }
7854
7855 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7856 // then handle it as such.
7857 if (isVectorLiteral)
7858 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7859
7860 // If the Expr being casted is a ParenListExpr, handle it specially.
7861 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7862 // sequence of BinOp comma operators.
7863 if (isa<ParenListExpr>(CastExpr)) {
7864 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7865 if (Result.isInvalid()) return ExprError();
7866 CastExpr = Result.get();
7867 }
7868
7869 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7870 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7871
7872 CheckTollFreeBridgeCast(castType, CastExpr);
7873
7874 CheckObjCBridgeRelatedCast(castType, CastExpr);
7875
7876 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7877
7878 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7879}
7880
7881ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7882 SourceLocation RParenLoc, Expr *E,
7883 TypeSourceInfo *TInfo) {
7884 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", 7885, __extension__ __PRETTY_FUNCTION__
))
7885 "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", 7885, __extension__ __PRETTY_FUNCTION__
))
;
7886
7887 Expr **exprs;
7888 unsigned numExprs;
7889 Expr *subExpr;
7890 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7891 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7892 LiteralLParenLoc = PE->getLParenLoc();
7893 LiteralRParenLoc = PE->getRParenLoc();
7894 exprs = PE->getExprs();
7895 numExprs = PE->getNumExprs();
7896 } else { // isa<ParenExpr> by assertion at function entrance
7897 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7898 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7899 subExpr = cast<ParenExpr>(E)->getSubExpr();
7900 exprs = &subExpr;
7901 numExprs = 1;
7902 }
7903
7904 QualType Ty = TInfo->getType();
7905 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", 7905, __extension__ __PRETTY_FUNCTION__
))
;
7906
7907 SmallVector<Expr *, 8> initExprs;
7908 const VectorType *VTy = Ty->castAs<VectorType>();
7909 unsigned numElems = VTy->getNumElements();
7910
7911 // '(...)' form of vector initialization in AltiVec: the number of
7912 // initializers must be one or must match the size of the vector.
7913 // If a single value is specified in the initializer then it will be
7914 // replicated to all the components of the vector
7915 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
7916 VTy->getElementType()))
7917 return ExprError();
7918 if (ShouldSplatAltivecScalarInCast(VTy)) {
7919 // The number of initializers must be one or must match the size of the
7920 // vector. If a single value is specified in the initializer then it will
7921 // be replicated to all the components of the vector
7922 if (numExprs == 1) {
7923 QualType ElemTy = VTy->getElementType();
7924 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7925 if (Literal.isInvalid())
7926 return ExprError();
7927 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7928 PrepareScalarCast(Literal, ElemTy));
7929 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7930 }
7931 else if (numExprs < numElems) {
7932 Diag(E->getExprLoc(),
7933 diag::err_incorrect_number_of_vector_initializers);
7934 return ExprError();
7935 }
7936 else
7937 initExprs.append(exprs, exprs + numExprs);
7938 }
7939 else {
7940 // For OpenCL, when the number of initializers is a single value,
7941 // it will be replicated to all components of the vector.
7942 if (getLangOpts().OpenCL &&
7943 VTy->getVectorKind() == VectorType::GenericVector &&
7944 numExprs == 1) {
7945 QualType ElemTy = VTy->getElementType();
7946 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7947 if (Literal.isInvalid())
7948 return ExprError();
7949 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7950 PrepareScalarCast(Literal, ElemTy));
7951 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7952 }
7953
7954 initExprs.append(exprs, exprs + numExprs);
7955 }
7956 // FIXME: This means that pretty-printing the final AST will produce curly
7957 // braces instead of the original commas.
7958 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7959 initExprs, LiteralRParenLoc);
7960 initE->setType(Ty);
7961 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7962}
7963
7964/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7965/// the ParenListExpr into a sequence of comma binary operators.
7966ExprResult
7967Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7968 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7969 if (!E)
7970 return OrigExpr;
7971
7972 ExprResult Result(E->getExpr(0));
7973
7974 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7975 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7976 E->getExpr(i));
7977
7978 if (Result.isInvalid()) return ExprError();
7979
7980 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7981}
7982
7983ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7984 SourceLocation R,
7985 MultiExprArg Val) {
7986 return ParenListExpr::Create(Context, L, Val, R);
7987}
7988
7989/// Emit a specialized diagnostic when one expression is a null pointer
7990/// constant and the other is not a pointer. Returns true if a diagnostic is
7991/// emitted.
7992bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7993 SourceLocation QuestionLoc) {
7994 Expr *NullExpr = LHSExpr;
7995 Expr *NonPointerExpr = RHSExpr;
7996 Expr::NullPointerConstantKind NullKind =
7997 NullExpr->isNullPointerConstant(Context,
7998 Expr::NPC_ValueDependentIsNotNull);
7999
8000 if (NullKind == Expr::NPCK_NotNull) {
8001 NullExpr = RHSExpr;
8002 NonPointerExpr = LHSExpr;
8003 NullKind =
8004 NullExpr->isNullPointerConstant(Context,
8005 Expr::NPC_ValueDependentIsNotNull);
8006 }
8007
8008 if (NullKind == Expr::NPCK_NotNull)
8009 return false;
8010
8011 if (NullKind == Expr::NPCK_ZeroExpression)
8012 return false;
8013
8014 if (NullKind == Expr::NPCK_ZeroLiteral) {
8015 // In this case, check to make sure that we got here from a "NULL"
8016 // string in the source code.
8017 NullExpr = NullExpr->IgnoreParenImpCasts();
8018 SourceLocation loc = NullExpr->getExprLoc();
8019 if (!findMacroSpelling(loc, "NULL"))
8020 return false;
8021 }
8022
8023 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8024 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8025 << NonPointerExpr->getType() << DiagType
8026 << NonPointerExpr->getSourceRange();
8027 return true;
8028}
8029
8030/// Return false if the condition expression is valid, true otherwise.
8031static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8032 QualType CondTy = Cond->getType();
8033
8034 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8035 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8036 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8037 << CondTy << Cond->getSourceRange();
8038 return true;
8039 }
8040
8041 // C99 6.5.15p2
8042 if (CondTy->isScalarType()) return false;
8043
8044 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8045 << CondTy << Cond->getSourceRange();
8046 return true;
8047}
8048
8049/// Handle when one or both operands are void type.
8050static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
8051 ExprResult &RHS) {
8052 Expr *LHSExpr = LHS.get();
8053 Expr *RHSExpr = RHS.get();
8054
8055 if (!LHSExpr->getType()->isVoidType())
8056 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8057 << RHSExpr->getSourceRange();
8058 if (!RHSExpr->getType()->isVoidType())
8059 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8060 << LHSExpr->getSourceRange();
8061 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
8062 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
8063 return S.Context.VoidTy;
8064}
8065
8066/// Return false if the NullExpr can be promoted to PointerTy,
8067/// true otherwise.
8068static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8069 QualType PointerTy) {
8070 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8071 !NullExpr.get()->isNullPointerConstant(S.Context,
8072 Expr::NPC_ValueDependentIsNull))
8073 return true;
8074
8075 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8076 return false;
8077}
8078
8079/// Checks compatibility between two pointers and return the resulting
8080/// type.
8081static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8082 ExprResult &RHS,
8083 SourceLocation Loc) {
8084 QualType LHSTy = LHS.get()->getType();
8085 QualType RHSTy = RHS.get()->getType();
8086
8087 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8088 // Two identical pointers types are always compatible.
8089 return LHSTy;
8090 }
8091
8092 QualType lhptee, rhptee;
8093
8094 // Get the pointee types.
8095 bool IsBlockPointer = false;
8096 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8097 lhptee = LHSBTy->getPointeeType();
8098 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8099 IsBlockPointer = true;
8100 } else {
8101 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8102 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8103 }
8104
8105 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8106 // differently qualified versions of compatible types, the result type is
8107 // a pointer to an appropriately qualified version of the composite
8108 // type.
8109
8110 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8111 // clause doesn't make sense for our extensions. E.g. address space 2 should
8112 // be incompatible with address space 3: they may live on different devices or
8113 // anything.
8114 Qualifiers lhQual = lhptee.getQualifiers();
8115 Qualifiers rhQual = rhptee.getQualifiers();
8116
8117 LangAS ResultAddrSpace = LangAS::Default;
8118 LangAS LAddrSpace = lhQual.getAddressSpace();
8119 LangAS RAddrSpace = rhQual.getAddressSpace();
8120
8121 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8122 // spaces is disallowed.
8123 if (lhQual.isAddressSpaceSupersetOf(rhQual))
8124 ResultAddrSpace = LAddrSpace;
8125 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8126 ResultAddrSpace = RAddrSpace;
8127 else {
8128 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8129 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8130 << RHS.get()->getSourceRange();
8131 return QualType();
8132 }
8133
8134 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8135 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8136 lhQual.removeCVRQualifiers();
8137 rhQual.removeCVRQualifiers();
8138
8139 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8140 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8141 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8142 // qual types are compatible iff
8143 // * corresponded types are compatible
8144 // * CVR qualifiers are equal
8145 // * address spaces are equal
8146 // Thus for conditional operator we merge CVR and address space unqualified
8147 // pointees and if there is a composite type we return a pointer to it with
8148 // merged qualifiers.
8149 LHSCastKind =
8150 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8151 RHSCastKind =
8152 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8153 lhQual.removeAddressSpace();
8154 rhQual.removeAddressSpace();
8155
8156 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8157 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8158
8159 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
8160
8161 if (CompositeTy.isNull()) {
8162 // In this situation, we assume void* type. No especially good
8163 // reason, but this is what gcc does, and we do have to pick
8164 // to get a consistent AST.
8165 QualType incompatTy;
8166 incompatTy = S.Context.getPointerType(
8167 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8168 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8169 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8170
8171 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8172 // for casts between types with incompatible address space qualifiers.
8173 // For the following code the compiler produces casts between global and
8174 // local address spaces of the corresponded innermost pointees:
8175 // local int *global *a;
8176 // global int *global *b;
8177 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8178 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8179 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8180 << RHS.get()->getSourceRange();
8181
8182 return incompatTy;
8183 }
8184
8185 // The pointer types are compatible.
8186 // In case of OpenCL ResultTy should have the address space qualifier
8187 // which is a superset of address spaces of both the 2nd and the 3rd
8188 // operands of the conditional operator.
8189 QualType ResultTy = [&, ResultAddrSpace]() {
8190 if (S.getLangOpts().OpenCL) {
8191 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8192 CompositeQuals.setAddressSpace(ResultAddrSpace);
8193 return S.Context
8194 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8195 .withCVRQualifiers(MergedCVRQual);
8196 }
8197 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8198 }();
8199 if (IsBlockPointer)
8200 ResultTy = S.Context.getBlockPointerType(ResultTy);
8201 else
8202 ResultTy = S.Context.getPointerType(ResultTy);
8203
8204 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8205 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8206 return ResultTy;
8207}
8208
8209/// Return the resulting type when the operands are both block pointers.
8210static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8211 ExprResult &LHS,
8212 ExprResult &RHS,
8213 SourceLocation Loc) {
8214 QualType LHSTy = LHS.get()->getType();
8215 QualType RHSTy = RHS.get()->getType();
8216
8217 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8218 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8219 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8220 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8221 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8222 return destType;
8223 }
8224 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8225 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8226 << RHS.get()->getSourceRange();
8227 return QualType();
8228 }
8229
8230 // We have 2 block pointer types.
8231 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8232}
8233
8234/// Return the resulting type when the operands are both pointers.
8235static QualType
8236checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8237 ExprResult &RHS,
8238 SourceLocation Loc) {
8239 // get the pointer types
8240 QualType LHSTy = LHS.get()->getType();
8241 QualType RHSTy = RHS.get()->getType();
8242
8243 // get the "pointed to" types
8244 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8245 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8246
8247 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8248 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8249 // Figure out necessary qualifiers (C99 6.5.15p6)
8250 QualType destPointee
8251 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8252 QualType destType = S.Context.getPointerType(destPointee);
8253 // Add qualifiers if necessary.
8254 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8255 // Promote to void*.
8256 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8257 return destType;
8258 }
8259 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8260 QualType destPointee
8261 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8262 QualType destType = S.Context.getPointerType(destPointee);
8263 // Add qualifiers if necessary.
8264 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8265 // Promote to void*.
8266 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8267 return destType;
8268 }
8269
8270 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8271}
8272
8273/// Return false if the first expression is not an integer and the second
8274/// expression is not a pointer, true otherwise.
8275static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8276 Expr* PointerExpr, SourceLocation Loc,
8277 bool IsIntFirstExpr) {
8278 if (!PointerExpr->getType()->isPointerType() ||
8279 !Int.get()->getType()->isIntegerType())
8280 return false;
8281
8282 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8283 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8284
8285 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8286 << Expr1->getType() << Expr2->getType()
8287 << Expr1->getSourceRange() << Expr2->getSourceRange();
8288 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8289 CK_IntegralToPointer);
8290 return true;
8291}
8292
8293/// Simple conversion between integer and floating point types.
8294///
8295/// Used when handling the OpenCL conditional operator where the
8296/// condition is a vector while the other operands are scalar.
8297///
8298/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8299/// types are either integer or floating type. Between the two
8300/// operands, the type with the higher rank is defined as the "result
8301/// type". The other operand needs to be promoted to the same type. No
8302/// other type promotion is allowed. We cannot use
8303/// UsualArithmeticConversions() for this purpose, since it always
8304/// promotes promotable types.
8305static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8306 ExprResult &RHS,
8307 SourceLocation QuestionLoc) {
8308 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8309 if (LHS.isInvalid())
8310 return QualType();
8311 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8312 if (RHS.isInvalid())
8313 return QualType();
8314
8315 // For conversion purposes, we ignore any qualifiers.
8316 // For example, "const float" and "float" are equivalent.
8317 QualType LHSType =
8318 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8319 QualType RHSType =
8320 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8321
8322 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8323 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8324 << LHSType << LHS.get()->getSourceRange();
8325 return QualType();
8326 }
8327
8328 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8329 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8330 << RHSType << RHS.get()->getSourceRange();
8331 return QualType();
8332 }
8333
8334 // If both types are identical, no conversion is needed.
8335 if (LHSType == RHSType)
8336 return LHSType;
8337
8338 // Now handle "real" floating types (i.e. float, double, long double).
8339 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8340 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8341 /*IsCompAssign = */ false);
8342
8343 // Finally, we have two differing integer types.
8344 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8345 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8346}
8347
8348/// Convert scalar operands to a vector that matches the
8349/// condition in length.
8350///
8351/// Used when handling the OpenCL conditional operator where the
8352/// condition is a vector while the other operands are scalar.
8353///
8354/// We first compute the "result type" for the scalar operands
8355/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8356/// into a vector of that type where the length matches the condition
8357/// vector type. s6.11.6 requires that the element types of the result
8358/// and the condition must have the same number of bits.
8359static QualType
8360OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8361 QualType CondTy, SourceLocation QuestionLoc) {
8362 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8363 if (ResTy.isNull()) return QualType();
8364
8365 const VectorType *CV = CondTy->getAs<VectorType>();
8366 assert(CV)(static_cast <bool> (CV) ? void (0) : __assert_fail ("CV"
, "clang/lib/Sema/SemaExpr.cpp", 8366, __extension__ __PRETTY_FUNCTION__
))
;
8367
8368 // Determine the vector result type
8369 unsigned NumElements = CV->getNumElements();
8370 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8371
8372 // Ensure that all types have the same number of bits
8373 if (S.Context.getTypeSize(CV->getElementType())
8374 != S.Context.getTypeSize(ResTy)) {
8375 // Since VectorTy is created internally, it does not pretty print
8376 // with an OpenCL name. Instead, we just print a description.
8377 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8378 SmallString<64> Str;
8379 llvm::raw_svector_ostream OS(Str);
8380 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8381 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8382 << CondTy << OS.str();
8383 return QualType();
8384 }
8385
8386 // Convert operands to the vector result type
8387 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8388 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8389
8390 return VectorTy;
8391}
8392
8393/// Return false if this is a valid OpenCL condition vector
8394static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8395 SourceLocation QuestionLoc) {
8396 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8397 // integral type.
8398 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8399 assert(CondTy)(static_cast <bool> (CondTy) ? void (0) : __assert_fail
("CondTy", "clang/lib/Sema/SemaExpr.cpp", 8399, __extension__
__PRETTY_FUNCTION__))
;
8400 QualType EleTy = CondTy->getElementType();
8401 if (EleTy->isIntegerType()) return false;
8402
8403 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8404 << Cond->getType() << Cond->getSourceRange();
8405 return true;
8406}
8407
8408/// Return false if the vector condition type and the vector
8409/// result type are compatible.
8410///
8411/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8412/// number of elements, and their element types have the same number
8413/// of bits.
8414static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8415 SourceLocation QuestionLoc) {
8416 const VectorType *CV = CondTy->getAs<VectorType>();
8417 const VectorType *RV = VecResTy->getAs<VectorType>();
8418 assert(CV && RV)(static_cast <bool> (CV && RV) ? void (0) : __assert_fail
("CV && RV", "clang/lib/Sema/SemaExpr.cpp", 8418, __extension__
__PRETTY_FUNCTION__))
;
8419
8420 if (CV->getNumElements() != RV->getNumElements()) {
8421 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8422 << CondTy << VecResTy;
8423 return true;
8424 }
8425
8426 QualType CVE = CV->getElementType();
8427 QualType RVE = RV->getElementType();
8428
8429 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8430 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8431 << CondTy << VecResTy;
8432 return true;
8433 }
8434
8435 return false;
8436}
8437
8438/// Return the resulting type for the conditional operator in
8439/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8440/// s6.3.i) when the condition is a vector type.
8441static QualType
8442OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8443 ExprResult &LHS, ExprResult &RHS,
8444 SourceLocation QuestionLoc) {
8445 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8446 if (Cond.isInvalid())
8447 return QualType();
8448 QualType CondTy = Cond.get()->getType();
8449
8450 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8451 return QualType();
8452
8453 // If either operand is a vector then find the vector type of the
8454 // result as specified in OpenCL v1.1 s6.3.i.
8455 if (LHS.get()->getType()->isVectorType() ||
8456 RHS.get()->getType()->isVectorType()) {
8457 bool IsBoolVecLang =
8458 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8459 QualType VecResTy =
8460 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8461 /*isCompAssign*/ false,
8462 /*AllowBothBool*/ true,
8463 /*AllowBoolConversions*/ false,
8464 /*AllowBooleanOperation*/ IsBoolVecLang,
8465 /*ReportInvalid*/ true);
8466 if (VecResTy.isNull())
8467 return QualType();
8468 // The result type must match the condition type as specified in
8469 // OpenCL v1.1 s6.11.6.
8470 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8471 return QualType();
8472 return VecResTy;
8473 }
8474
8475 // Both operands are scalar.
8476 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8477}
8478
8479/// Return true if the Expr is block type
8480static bool checkBlockType(Sema &S, const Expr *E) {
8481 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8482 QualType Ty = CE->getCallee()->getType();
8483 if (Ty->isBlockPointerType()) {
8484 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8485 return true;
8486 }
8487 }
8488 return false;
8489}
8490
8491/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8492/// In that case, LHS = cond.
8493/// C99 6.5.15
8494QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8495 ExprResult &RHS, ExprValueKind &VK,
8496 ExprObjectKind &OK,
8497 SourceLocation QuestionLoc) {
8498
8499 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8500 if (!LHSResult.isUsable()) return QualType();
8501 LHS = LHSResult;
8502
8503 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8504 if (!RHSResult.isUsable()) return QualType();
8505 RHS = RHSResult;
8506
8507 // C++ is sufficiently different to merit its own checker.
8508 if (getLangOpts().CPlusPlus)
8509 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8510
8511 VK = VK_PRValue;
8512 OK = OK_Ordinary;
8513
8514 if (Context.isDependenceAllowed() &&
8515 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8516 RHS.get()->isTypeDependent())) {
8517 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 8517, __extension__ __PRETTY_FUNCTION__))
;
8518 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", 8520, __extension__ __PRETTY_FUNCTION__
))
8519 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", 8520, __extension__ __PRETTY_FUNCTION__
))
8520 "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", 8520, __extension__ __PRETTY_FUNCTION__
))
;
8521 return Context.DependentTy;
8522 }
8523
8524 // The OpenCL operator with a vector condition is sufficiently
8525 // different to merit its own checker.
8526 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8527 Cond.get()->getType()->isExtVectorType())
8528 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8529
8530 // First, check the condition.
8531 Cond = UsualUnaryConversions(Cond.get());
8532 if (Cond.isInvalid())
8533 return QualType();
8534 if (checkCondition(*this, Cond.get(), QuestionLoc))
8535 return QualType();
8536
8537 // Now check the two expressions.
8538 if (LHS.get()->getType()->isVectorType() ||
8539 RHS.get()->getType()->isVectorType())
8540 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8541 /*AllowBothBool*/ true,
8542 /*AllowBoolConversions*/ false,
8543 /*AllowBooleanOperation*/ false,
8544 /*ReportInvalid*/ true);
8545
8546 QualType ResTy =
8547 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8548 if (LHS.isInvalid() || RHS.isInvalid())
8549 return QualType();
8550
8551 QualType LHSTy = LHS.get()->getType();
8552 QualType RHSTy = RHS.get()->getType();
8553
8554 // Diagnose attempts to convert between __ibm128, __float128 and long double
8555 // where such conversions currently can't be handled.
8556 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8557 Diag(QuestionLoc,
8558 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8559 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8560 return QualType();
8561 }
8562
8563 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8564 // selection operator (?:).
8565 if (getLangOpts().OpenCL &&
8566 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8567 return QualType();
8568 }
8569
8570 // If both operands have arithmetic type, do the usual arithmetic conversions
8571 // to find a common type: C99 6.5.15p3,5.
8572 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8573 // Disallow invalid arithmetic conversions, such as those between bit-
8574 // precise integers types of different sizes, or between a bit-precise
8575 // integer and another type.
8576 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8577 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8578 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8579 << RHS.get()->getSourceRange();
8580 return QualType();
8581 }
8582
8583 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8584 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8585
8586 return ResTy;
8587 }
8588
8589 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8590 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8591 return LHSTy;
8592 }
8593
8594 // If both operands are the same structure or union type, the result is that
8595 // type.
8596 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8597 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8598 if (LHSRT->getDecl() == RHSRT->getDecl())
8599 // "If both the operands have structure or union type, the result has
8600 // that type." This implies that CV qualifiers are dropped.
8601 return LHSTy.getUnqualifiedType();
8602 // FIXME: Type of conditional expression must be complete in C mode.
8603 }
8604
8605 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8606 // The following || allows only one side to be void (a GCC-ism).
8607 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8608 return checkConditionalVoidType(*this, LHS, RHS);
8609 }
8610
8611 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8612 // the type of the other operand."
8613 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8614 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8615
8616 // All objective-c pointer type analysis is done here.
8617 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8618 QuestionLoc);
8619 if (LHS.isInvalid() || RHS.isInvalid())
8620 return QualType();
8621 if (!compositeType.isNull())
8622 return compositeType;
8623
8624
8625 // Handle block pointer types.
8626 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8627 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8628 QuestionLoc);
8629
8630 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8631 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8632 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8633 QuestionLoc);
8634
8635 // GCC compatibility: soften pointer/integer mismatch. Note that
8636 // null pointers have been filtered out by this point.
8637 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8638 /*IsIntFirstExpr=*/true))
8639 return RHSTy;
8640 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8641 /*IsIntFirstExpr=*/false))
8642 return LHSTy;
8643
8644 // Allow ?: operations in which both operands have the same
8645 // built-in sizeless type.
8646 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8647 return LHSTy;
8648
8649 // Emit a better diagnostic if one of the expressions is a null pointer
8650 // constant and the other is not a pointer type. In this case, the user most
8651 // likely forgot to take the address of the other expression.
8652 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8653 return QualType();
8654
8655 // Otherwise, the operands are not compatible.
8656 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8657 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8658 << RHS.get()->getSourceRange();
8659 return QualType();
8660}
8661
8662/// FindCompositeObjCPointerType - Helper method to find composite type of
8663/// two objective-c pointer types of the two input expressions.
8664QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8665 SourceLocation QuestionLoc) {
8666 QualType LHSTy = LHS.get()->getType();
8667 QualType RHSTy = RHS.get()->getType();
8668
8669 // Handle things like Class and struct objc_class*. Here we case the result
8670 // to the pseudo-builtin, because that will be implicitly cast back to the
8671 // redefinition type if an attempt is made to access its fields.
8672 if (LHSTy->isObjCClassType() &&
8673 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8674 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8675 return LHSTy;
8676 }
8677 if (RHSTy->isObjCClassType() &&
8678 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8679 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8680 return RHSTy;
8681 }
8682 // And the same for struct objc_object* / id
8683 if (LHSTy->isObjCIdType() &&
8684 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8685 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8686 return LHSTy;
8687 }
8688 if (RHSTy->isObjCIdType() &&
8689 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8690 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8691 return RHSTy;
8692 }
8693 // And the same for struct objc_selector* / SEL
8694 if (Context.isObjCSelType(LHSTy) &&
8695 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8696 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8697 return LHSTy;
8698 }
8699 if (Context.isObjCSelType(RHSTy) &&
8700 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8701 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8702 return RHSTy;
8703 }
8704 // Check constraints for Objective-C object pointers types.
8705 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8706
8707 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8708 // Two identical object pointer types are always compatible.
8709 return LHSTy;
8710 }
8711 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8712 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8713 QualType compositeType = LHSTy;
8714
8715 // If both operands are interfaces and either operand can be
8716 // assigned to the other, use that type as the composite
8717 // type. This allows
8718 // xxx ? (A*) a : (B*) b
8719 // where B is a subclass of A.
8720 //
8721 // Additionally, as for assignment, if either type is 'id'
8722 // allow silent coercion. Finally, if the types are
8723 // incompatible then make sure to use 'id' as the composite
8724 // type so the result is acceptable for sending messages to.
8725
8726 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8727 // It could return the composite type.
8728 if (!(compositeType =
8729 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8730 // Nothing more to do.
8731 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8732 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8733 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8734 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8735 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8736 RHSOPT->isObjCQualifiedIdType()) &&
8737 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8738 true)) {
8739 // Need to handle "id<xx>" explicitly.
8740 // GCC allows qualified id and any Objective-C type to devolve to
8741 // id. Currently localizing to here until clear this should be
8742 // part of ObjCQualifiedIdTypesAreCompatible.
8743 compositeType = Context.getObjCIdType();
8744 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8745 compositeType = Context.getObjCIdType();
8746 } else {
8747 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8748 << LHSTy << RHSTy
8749 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8750 QualType incompatTy = Context.getObjCIdType();
8751 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8752 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8753 return incompatTy;
8754 }
8755 // The object pointer types are compatible.
8756 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8757 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8758 return compositeType;
8759 }
8760 // Check Objective-C object pointer types and 'void *'
8761 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8762 if (getLangOpts().ObjCAutoRefCount) {
8763 // ARC forbids the implicit conversion of object pointers to 'void *',
8764 // so these types are not compatible.
8765 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8766 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8767 LHS = RHS = true;
8768 return QualType();
8769 }
8770 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8771 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8772 QualType destPointee
8773 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8774 QualType destType = Context.getPointerType(destPointee);
8775 // Add qualifiers if necessary.
8776 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8777 // Promote to void*.
8778 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8779 return destType;
8780 }
8781 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8782 if (getLangOpts().ObjCAutoRefCount) {
8783 // ARC forbids the implicit conversion of object pointers to 'void *',
8784 // so these types are not compatible.
8785 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8786 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8787 LHS = RHS = true;
8788 return QualType();
8789 }
8790 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8791 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8792 QualType destPointee
8793 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8794 QualType destType = Context.getPointerType(destPointee);
8795 // Add qualifiers if necessary.
8796 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8797 // Promote to void*.
8798 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8799 return destType;
8800 }
8801 return QualType();
8802}
8803
8804/// SuggestParentheses - Emit a note with a fixit hint that wraps
8805/// ParenRange in parentheses.
8806static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8807 const PartialDiagnostic &Note,
8808 SourceRange ParenRange) {
8809 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8810 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8811 EndLoc.isValid()) {
8812 Self.Diag(Loc, Note)
8813 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8814 << FixItHint::CreateInsertion(EndLoc, ")");
8815 } else {
8816 // We can't display the parentheses, so just show the bare note.
8817 Self.Diag(Loc, Note) << ParenRange;
8818 }
8819}
8820
8821static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8822 return BinaryOperator::isAdditiveOp(Opc) ||
8823 BinaryOperator::isMultiplicativeOp(Opc) ||
8824 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8825 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8826 // not any of the logical operators. Bitwise-xor is commonly used as a
8827 // logical-xor because there is no logical-xor operator. The logical
8828 // operators, including uses of xor, have a high false positive rate for
8829 // precedence warnings.
8830}
8831
8832/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8833/// expression, either using a built-in or overloaded operator,
8834/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8835/// expression.
8836static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8837 Expr **RHSExprs) {
8838 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8839 E = E->IgnoreImpCasts();
8840 E = E->IgnoreConversionOperatorSingleStep();
8841 E = E->IgnoreImpCasts();
8842 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8843 E = MTE->getSubExpr();
8844 E = E->IgnoreImpCasts();
8845 }
8846
8847 // Built-in binary operator.
8848 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8849 if (IsArithmeticOp(OP->getOpcode())) {
8850 *Opcode = OP->getOpcode();
8851 *RHSExprs = OP->getRHS();
8852 return true;
8853 }
8854 }
8855
8856 // Overloaded operator.
8857 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8858 if (Call->getNumArgs() != 2)
8859 return false;
8860
8861 // Make sure this is really a binary operator that is safe to pass into
8862 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8863 OverloadedOperatorKind OO = Call->getOperator();
8864 if (OO < OO_Plus || OO > OO_Arrow ||
8865 OO == OO_PlusPlus || OO == OO_MinusMinus)
8866 return false;
8867
8868 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8869 if (IsArithmeticOp(OpKind)) {
8870 *Opcode = OpKind;
8871 *RHSExprs = Call->getArg(1);
8872 return true;
8873 }
8874 }
8875
8876 return false;
8877}
8878
8879/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8880/// or is a logical expression such as (x==y) which has int type, but is
8881/// commonly interpreted as boolean.
8882static bool ExprLooksBoolean(Expr *E) {
8883 E = E->IgnoreParenImpCasts();
8884
8885 if (E->getType()->isBooleanType())
8886 return true;
8887 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8888 return OP->isComparisonOp() || OP->isLogicalOp();
8889 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8890 return OP->getOpcode() == UO_LNot;
8891 if (E->getType()->isPointerType())
8892 return true;
8893 // FIXME: What about overloaded operator calls returning "unspecified boolean
8894 // type"s (commonly pointer-to-members)?
8895
8896 return false;
8897}
8898
8899/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8900/// and binary operator are mixed in a way that suggests the programmer assumed
8901/// the conditional operator has higher precedence, for example:
8902/// "int x = a + someBinaryCondition ? 1 : 2".
8903static void DiagnoseConditionalPrecedence(Sema &Self,
8904 SourceLocation OpLoc,
8905 Expr *Condition,
8906 Expr *LHSExpr,
8907 Expr *RHSExpr) {
8908 BinaryOperatorKind CondOpcode;
8909 Expr *CondRHS;
8910
8911 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8912 return;
8913 if (!ExprLooksBoolean(CondRHS))
8914 return;
8915
8916 // The condition is an arithmetic binary expression, with a right-
8917 // hand side that looks boolean, so warn.
8918
8919 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8920 ? diag::warn_precedence_bitwise_conditional
8921 : diag::warn_precedence_conditional;
8922
8923 Self.Diag(OpLoc, DiagID)
8924 << Condition->getSourceRange()
8925 << BinaryOperator::getOpcodeStr(CondOpcode);
8926
8927 SuggestParentheses(
8928 Self, OpLoc,
8929 Self.PDiag(diag::note_precedence_silence)
8930 << BinaryOperator::getOpcodeStr(CondOpcode),
8931 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8932
8933 SuggestParentheses(Self, OpLoc,
8934 Self.PDiag(diag::note_precedence_conditional_first),
8935 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8936}
8937
8938/// Compute the nullability of a conditional expression.
8939static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8940 QualType LHSTy, QualType RHSTy,
8941 ASTContext &Ctx) {
8942 if (!ResTy->isAnyPointerType())
8943 return ResTy;
8944
8945 auto GetNullability = [&Ctx](QualType Ty) {
8946 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8947 if (Kind) {
8948 // For our purposes, treat _Nullable_result as _Nullable.
8949 if (*Kind == NullabilityKind::NullableResult)
8950 return NullabilityKind::Nullable;
8951 return *Kind;
8952 }
8953 return NullabilityKind::Unspecified;
8954 };
8955
8956 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8957 NullabilityKind MergedKind;
8958
8959 // Compute nullability of a binary conditional expression.
8960 if (IsBin) {
8961 if (LHSKind == NullabilityKind::NonNull)
8962 MergedKind = NullabilityKind::NonNull;
8963 else
8964 MergedKind = RHSKind;
8965 // Compute nullability of a normal conditional expression.
8966 } else {
8967 if (LHSKind == NullabilityKind::Nullable ||
8968 RHSKind == NullabilityKind::Nullable)
8969 MergedKind = NullabilityKind::Nullable;
8970 else if (LHSKind == NullabilityKind::NonNull)
8971 MergedKind = RHSKind;
8972 else if (RHSKind == NullabilityKind::NonNull)
8973 MergedKind = LHSKind;
8974 else
8975 MergedKind = NullabilityKind::Unspecified;
8976 }
8977
8978 // Return if ResTy already has the correct nullability.
8979 if (GetNullability(ResTy) == MergedKind)
8980 return ResTy;
8981
8982 // Strip all nullability from ResTy.
8983 while (ResTy->getNullability(Ctx))
8984 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8985
8986 // Create a new AttributedType with the new nullability kind.
8987 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8988 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8989}
8990
8991/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
8992/// in the case of a the GNU conditional expr extension.
8993ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8994 SourceLocation ColonLoc,
8995 Expr *CondExpr, Expr *LHSExpr,
8996 Expr *RHSExpr) {
8997 if (!Context.isDependenceAllowed()) {
8998 // C cannot handle TypoExpr nodes in the condition because it
8999 // doesn't handle dependent types properly, so make sure any TypoExprs have
9000 // been dealt with before checking the operands.
9001 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9002 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9003 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9004
9005 if (!CondResult.isUsable())
9006 return ExprError();
9007
9008 if (LHSExpr) {
9009 if (!LHSResult.isUsable())
9010 return ExprError();
9011 }
9012
9013 if (!RHSResult.isUsable())
9014 return ExprError();
9015
9016 CondExpr = CondResult.get();
9017 LHSExpr = LHSResult.get();
9018 RHSExpr = RHSResult.get();
9019 }
9020
9021 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9022 // was the condition.
9023 OpaqueValueExpr *opaqueValue = nullptr;
9024 Expr *commonExpr = nullptr;
9025 if (!LHSExpr) {
9026 commonExpr = CondExpr;
9027 // Lower out placeholder types first. This is important so that we don't
9028 // try to capture a placeholder. This happens in few cases in C++; such
9029 // as Objective-C++'s dictionary subscripting syntax.
9030 if (commonExpr->hasPlaceholderType()) {
9031 ExprResult result = CheckPlaceholderExpr(commonExpr);
9032 if (!result.isUsable()) return ExprError();
9033 commonExpr = result.get();
9034 }
9035 // We usually want to apply unary conversions *before* saving, except
9036 // in the special case of a C++ l-value conditional.
9037 if (!(getLangOpts().CPlusPlus
9038 && !commonExpr->isTypeDependent()
9039 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9040 && commonExpr->isGLValue()
9041 && commonExpr->isOrdinaryOrBitFieldObject()
9042 && RHSExpr->isOrdinaryOrBitFieldObject()
9043 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9044 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9045 if (commonRes.isInvalid())
9046 return ExprError();
9047 commonExpr = commonRes.get();
9048 }
9049
9050 // If the common expression is a class or array prvalue, materialize it
9051 // so that we can safely refer to it multiple times.
9052 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9053 commonExpr->getType()->isArrayType())) {
9054 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9055 if (MatExpr.isInvalid())
9056 return ExprError();
9057 commonExpr = MatExpr.get();
9058 }
9059
9060 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9061 commonExpr->getType(),
9062 commonExpr->getValueKind(),
9063 commonExpr->getObjectKind(),
9064 commonExpr);
9065 LHSExpr = CondExpr = opaqueValue;
9066 }
9067
9068 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9069 ExprValueKind VK = VK_PRValue;
9070 ExprObjectKind OK = OK_Ordinary;
9071 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9072 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9073 VK, OK, QuestionLoc);
9074 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9075 RHS.isInvalid())
9076 return ExprError();
9077
9078 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9079 RHS.get());
9080
9081 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9082
9083 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9084 Context);
9085
9086 if (!commonExpr)
9087 return new (Context)
9088 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9089 RHS.get(), result, VK, OK);
9090
9091 return new (Context) BinaryConditionalOperator(
9092 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9093 ColonLoc, result, VK, OK);
9094}
9095
9096// Check if we have a conversion between incompatible cmse function pointer
9097// types, that is, a conversion between a function pointer with the
9098// cmse_nonsecure_call attribute and one without.
9099static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9100 QualType ToType) {
9101 if (const auto *ToFn =
9102 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9103 if (const auto *FromFn =
9104 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9105 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9106 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9107
9108 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9109 }
9110 }
9111 return false;
9112}
9113
9114// checkPointerTypesForAssignment - This is a very tricky routine (despite
9115// being closely modeled after the C99 spec:-). The odd characteristic of this
9116// routine is it effectively iqnores the qualifiers on the top level pointee.
9117// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9118// FIXME: add a couple examples in this comment.
9119static Sema::AssignConvertType
9120checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
9121 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", 9121, __extension__ __PRETTY_FUNCTION__
))
;
9122 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", 9122, __extension__ __PRETTY_FUNCTION__
))
;
9123
9124 // get the "pointed to" type (ignoring qualifiers at the top level)
9125 const Type *lhptee, *rhptee;
9126 Qualifiers lhq, rhq;
9127 std::tie(lhptee, lhq) =
9128 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9129 std::tie(rhptee, rhq) =
9130 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9131
9132 Sema::AssignConvertType ConvTy = Sema::Compatible;
9133
9134 // C99 6.5.16.1p1: This following citation is common to constraints
9135 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9136 // qualifiers of the type *pointed to* by the right;
9137
9138 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9139 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9140 lhq.compatiblyIncludesObjCLifetime(rhq)) {
9141 // Ignore lifetime for further calculation.
9142 lhq.removeObjCLifetime();
9143 rhq.removeObjCLifetime();
9144 }
9145
9146 if (!lhq.compatiblyIncludes(rhq)) {
9147 // Treat address-space mismatches as fatal.
9148 if (!lhq.isAddressSpaceSupersetOf(rhq))
9149 return Sema::IncompatiblePointerDiscardsQualifiers;
9150
9151 // It's okay to add or remove GC or lifetime qualifiers when converting to
9152 // and from void*.
9153 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9154 .compatiblyIncludes(
9155 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9156 && (lhptee->isVoidType() || rhptee->isVoidType()))
9157 ; // keep old
9158
9159 // Treat lifetime mismatches as fatal.
9160 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9161 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9162
9163 // For GCC/MS compatibility, other qualifier mismatches are treated
9164 // as still compatible in C.
9165 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9166 }
9167
9168 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9169 // incomplete type and the other is a pointer to a qualified or unqualified
9170 // version of void...
9171 if (lhptee->isVoidType()) {
9172 if (rhptee->isIncompleteOrObjectType())
9173 return ConvTy;
9174
9175 // As an extension, we allow cast to/from void* to function pointer.
9176 assert(rhptee->isFunctionType())(static_cast <bool> (rhptee->isFunctionType()) ? void
(0) : __assert_fail ("rhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp"
, 9176, __extension__ __PRETTY_FUNCTION__))
;
9177 return Sema::FunctionVoidPointer;
9178 }
9179
9180 if (rhptee->isVoidType()) {
9181 if (lhptee->isIncompleteOrObjectType())
9182 return ConvTy;
9183
9184 // As an extension, we allow cast to/from void* to function pointer.
9185 assert(lhptee->isFunctionType())(static_cast <bool> (lhptee->isFunctionType()) ? void
(0) : __assert_fail ("lhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp"
, 9185, __extension__ __PRETTY_FUNCTION__))
;
9186 return Sema::FunctionVoidPointer;
9187 }
9188
9189 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9190 // unqualified versions of compatible types, ...
9191 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9192 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9193 // Check if the pointee types are compatible ignoring the sign.
9194 // We explicitly check for char so that we catch "char" vs
9195 // "unsigned char" on systems where "char" is unsigned.
9196 if (lhptee->isCharType())
9197 ltrans = S.Context.UnsignedCharTy;
9198 else if (lhptee->hasSignedIntegerRepresentation())
9199 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9200
9201 if (rhptee->isCharType())
9202 rtrans = S.Context.UnsignedCharTy;
9203 else if (rhptee->hasSignedIntegerRepresentation())
9204 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9205
9206 if (ltrans == rtrans) {
9207 // Types are compatible ignoring the sign. Qualifier incompatibility
9208 // takes priority over sign incompatibility because the sign
9209 // warning can be disabled.
9210 if (ConvTy != Sema::Compatible)
9211 return ConvTy;
9212
9213 return Sema::IncompatiblePointerSign;
9214 }
9215
9216 // If we are a multi-level pointer, it's possible that our issue is simply
9217 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9218 // the eventual target type is the same and the pointers have the same
9219 // level of indirection, this must be the issue.
9220 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9221 do {
9222 std::tie(lhptee, lhq) =
9223 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9224 std::tie(rhptee, rhq) =
9225 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9226
9227 // Inconsistent address spaces at this point is invalid, even if the
9228 // address spaces would be compatible.
9229 // FIXME: This doesn't catch address space mismatches for pointers of
9230 // different nesting levels, like:
9231 // __local int *** a;
9232 // int ** b = a;
9233 // It's not clear how to actually determine when such pointers are
9234 // invalidly incompatible.
9235 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9236 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9237
9238 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9239
9240 if (lhptee == rhptee)
9241 return Sema::IncompatibleNestedPointerQualifiers;
9242 }
9243
9244 // General pointer incompatibility takes priority over qualifiers.
9245 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9246 return Sema::IncompatibleFunctionPointer;
9247 return Sema::IncompatiblePointer;
9248 }
9249 if (!S.getLangOpts().CPlusPlus &&
9250 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9251 return Sema::IncompatibleFunctionPointer;
9252 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9253 return Sema::IncompatibleFunctionPointer;
9254 return ConvTy;
9255}
9256
9257/// checkBlockPointerTypesForAssignment - This routine determines whether two
9258/// block pointer types are compatible or whether a block and normal pointer
9259/// are compatible. It is more restrict than comparing two function pointer
9260// types.
9261static Sema::AssignConvertType
9262checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9263 QualType RHSType) {
9264 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", 9264, __extension__ __PRETTY_FUNCTION__
))
;
9265 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", 9265, __extension__ __PRETTY_FUNCTION__
))
;
9266
9267 QualType lhptee, rhptee;
9268
9269 // get the "pointed to" type (ignoring qualifiers at the top level)
9270 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9271 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9272
9273 // In C++, the types have to match exactly.
9274 if (S.getLangOpts().CPlusPlus)
9275 return Sema::IncompatibleBlockPointer;
9276
9277 Sema::AssignConvertType ConvTy = Sema::Compatible;
9278
9279 // For blocks we enforce that qualifiers are identical.
9280 Qualifiers LQuals = lhptee.getLocalQualifiers();
9281 Qualifiers RQuals = rhptee.getLocalQualifiers();
9282 if (S.getLangOpts().OpenCL) {
9283 LQuals.removeAddressSpace();
9284 RQuals.removeAddressSpace();
9285 }
9286 if (LQuals != RQuals)
9287 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9288
9289 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9290 // assignment.
9291 // The current behavior is similar to C++ lambdas. A block might be
9292 // assigned to a variable iff its return type and parameters are compatible
9293 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9294 // an assignment. Presumably it should behave in way that a function pointer
9295 // assignment does in C, so for each parameter and return type:
9296 // * CVR and address space of LHS should be a superset of CVR and address
9297 // space of RHS.
9298 // * unqualified types should be compatible.
9299 if (S.getLangOpts().OpenCL) {
9300 if (!S.Context.typesAreBlockPointerCompatible(
9301 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9302 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9303 return Sema::IncompatibleBlockPointer;
9304 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9305 return Sema::IncompatibleBlockPointer;
9306
9307 return ConvTy;
9308}
9309
9310/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9311/// for assignment compatibility.
9312static Sema::AssignConvertType
9313checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9314 QualType RHSType) {
9315 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", 9315, __extension__ __PRETTY_FUNCTION__
))
;
9316 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", 9316, __extension__ __PRETTY_FUNCTION__
))
;
9317
9318 if (LHSType->isObjCBuiltinType()) {
9319 // Class is not compatible with ObjC object pointers.
9320 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9321 !RHSType->isObjCQualifiedClassType())
9322 return Sema::IncompatiblePointer;
9323 return Sema::Compatible;
9324 }
9325 if (RHSType->isObjCBuiltinType()) {
9326 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9327 !LHSType->isObjCQualifiedClassType())
9328 return Sema::IncompatiblePointer;
9329 return Sema::Compatible;
9330 }
9331 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9332 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9333
9334 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9335 // make an exception for id<P>
9336 !LHSType->isObjCQualifiedIdType())
9337 return Sema::CompatiblePointerDiscardsQualifiers;
9338
9339 if (S.Context.typesAreCompatible(LHSType, RHSType))
9340 return Sema::Compatible;
9341 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9342 return Sema::IncompatibleObjCQualifiedId;
9343 return Sema::IncompatiblePointer;
9344}
9345
9346Sema::AssignConvertType
9347Sema::CheckAssignmentConstraints(SourceLocation Loc,
9348 QualType LHSType, QualType RHSType) {
9349 // Fake up an opaque expression. We don't actually care about what
9350 // cast operations are required, so if CheckAssignmentConstraints
9351 // adds casts to this they'll be wasted, but fortunately that doesn't
9352 // usually happen on valid code.
9353 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9354 ExprResult RHSPtr = &RHSExpr;
9355 CastKind K;
9356
9357 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9358}
9359
9360/// This helper function returns true if QT is a vector type that has element
9361/// type ElementType.
9362static bool isVector(QualType QT, QualType ElementType) {
9363 if (const VectorType *VT = QT->getAs<VectorType>())
9364 return VT->getElementType().getCanonicalType() == ElementType;
9365 return false;
9366}
9367
9368/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9369/// has code to accommodate several GCC extensions when type checking
9370/// pointers. Here are some objectionable examples that GCC considers warnings:
9371///
9372/// int a, *pint;
9373/// short *pshort;
9374/// struct foo *pfoo;
9375///
9376/// pint = pshort; // warning: assignment from incompatible pointer type
9377/// a = pint; // warning: assignment makes integer from pointer without a cast
9378/// pint = a; // warning: assignment makes pointer from integer without a cast
9379/// pint = pfoo; // warning: assignment from incompatible pointer type
9380///
9381/// As a result, the code for dealing with pointers is more complex than the
9382/// C99 spec dictates.
9383///
9384/// Sets 'Kind' for any result kind except Incompatible.
9385Sema::AssignConvertType
9386Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9387 CastKind &Kind, bool ConvertRHS) {
9388 QualType RHSType = RHS.get()->getType();
9389 QualType OrigLHSType = LHSType;
9390
9391 // Get canonical types. We're not formatting these types, just comparing
9392 // them.
9393 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9394 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9395
9396 // Common case: no conversion required.
9397 if (LHSType == RHSType) {
1
Calling 'operator=='
7
Returning from 'operator=='
8
Taking false branch
9398 Kind = CK_NoOp;
9399 return Compatible;
9400 }
9401
9402 // If we have an atomic type, try a non-atomic assignment, then just add an
9403 // atomic qualification step.
9404 if (const AtomicType *AtomicTy
13.1
'AtomicTy' is null
13.1
'AtomicTy' is null
13.1
'AtomicTy' is null
13.1
'AtomicTy' is null
= dyn_cast<AtomicType>(LHSType)) {
9
Calling 'dyn_cast<clang::AtomicType, clang::QualType>'
13
Returning from 'dyn_cast<clang::AtomicType, clang::QualType>'
14
Taking false branch
9405 Sema::AssignConvertType result =
9406 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9407 if (result != Compatible)
9408 return result;
9409 if (Kind != CK_NoOp && ConvertRHS)
9410 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9411 Kind = CK_NonAtomicToAtomic;
9412 return Compatible;
9413 }
9414
9415 // If the left-hand side is a reference type, then we are in a
9416 // (rare!) case where we've allowed the use of references in C,
9417 // e.g., as a parameter type in a built-in function. In this case,
9418 // just make sure that the type referenced is compatible with the
9419 // right-hand side type. The caller is responsible for adjusting
9420 // LHSType so that the resulting expression does not have reference
9421 // type.
9422 if (const ReferenceType *LHSTypeRef
15.1
'LHSTypeRef' is null
15.1
'LHSTypeRef' is null
15.1
'LHSTypeRef' is null
15.1
'LHSTypeRef' is null
= LHSType->getAs<ReferenceType>()) {
15
Assuming the object is not a 'ReferenceType'
16
Taking false branch
9423 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9424 Kind = CK_LValueBitCast;
9425 return Compatible;
9426 }
9427 return Incompatible;
9428 }
9429
9430 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9431 // to the same ExtVector type.
9432 if (LHSType->isExtVectorType()) {
17
Calling 'Type::isExtVectorType'
20
Returning from 'Type::isExtVectorType'
9433 if (RHSType->isExtVectorType())
9434 return Incompatible;
9435 if (RHSType->isArithmeticType()) {
9436 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9437 if (ConvertRHS)
9438 RHS = prepareVectorSplat(LHSType, RHS.get());
9439 Kind = CK_VectorSplat;
9440 return Compatible;
9441 }
9442 }
9443
9444 // Conversions to or from vector type.
9445 if (LHSType->isVectorType() || RHSType->isVectorType()) {
21
Calling 'Type::isVectorType'
24
Returning from 'Type::isVectorType'
25
Calling 'Type::isVectorType'
28
Returning from 'Type::isVectorType'
29
Taking false branch
9446 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9447 // Allow assignments of an AltiVec vector type to an equivalent GCC
9448 // vector type and vice versa
9449 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9450 Kind = CK_BitCast;
9451 return Compatible;
9452 }
9453
9454 // If we are allowing lax vector conversions, and LHS and RHS are both
9455 // vectors, the total size only needs to be the same. This is a bitcast;
9456 // no bits are changed but the result type is different.
9457 if (isLaxVectorConversion(RHSType, LHSType)) {
9458 Kind = CK_BitCast;
9459 return IncompatibleVectors;
9460 }
9461 }
9462
9463 // When the RHS comes from another lax conversion (e.g. binops between
9464 // scalars and vectors) the result is canonicalized as a vector. When the
9465 // LHS is also a vector, the lax is allowed by the condition above. Handle
9466 // the case where LHS is a scalar.
9467 if (LHSType->isScalarType()) {
9468 const VectorType *VecType = RHSType->getAs<VectorType>();
9469 if (VecType && VecType->getNumElements() == 1 &&
9470 isLaxVectorConversion(RHSType, LHSType)) {
9471 ExprResult *VecExpr = &RHS;
9472 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9473 Kind = CK_BitCast;
9474 return Compatible;
9475 }
9476 }
9477
9478 // Allow assignments between fixed-length and sizeless SVE vectors.
9479 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9480 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9481 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9482 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9483 Kind = CK_BitCast;
9484 return Compatible;
9485 }
9486
9487 return Incompatible;
9488 }
9489
9490 // Diagnose attempts to convert between __ibm128, __float128 and long double
9491 // where such conversions currently can't be handled.
9492 if (unsupportedTypeConversion(*this, LHSType, RHSType))
30
Calling 'unsupportedTypeConversion'
44
Returning from 'unsupportedTypeConversion'
9493 return Incompatible;
9494
9495 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9496 // discards the imaginary part.
9497 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
45
Assuming field 'CPlusPlus' is 0
9498 !LHSType->getAs<ComplexType>())
9499 return Incompatible;
9500
9501 // Arithmetic conversions.
9502 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
46
Assuming the condition is false
9503 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9504 if (ConvertRHS)
9505 Kind = PrepareScalarCast(RHS, LHSType);
9506 return Compatible;
9507 }
9508
9509 // Conversions to normal pointers.
9510 if (const PointerType *LHSPointer
51.1
'LHSPointer' is null
51.1
'LHSPointer' is null
51.1
'LHSPointer' is null
51.1
'LHSPointer' is null
= dyn_cast<PointerType>(LHSType)) {
47
Calling 'dyn_cast<clang::PointerType, clang::QualType>'
51
Returning from 'dyn_cast<clang::PointerType, clang::QualType>'
52
Taking false branch
9511 // U* -> T*
9512 if (isa<PointerType>(RHSType)) {
9513 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9514 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9515 if (AddrSpaceL != AddrSpaceR)
9516 Kind = CK_AddressSpaceConversion;
9517 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9518 Kind = CK_NoOp;
9519 else
9520 Kind = CK_BitCast;
9521 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9522 }
9523
9524 // int -> T*
9525 if (RHSType->isIntegerType()) {
9526 Kind = CK_IntegralToPointer; // FIXME: null?
9527 return IntToPointer;
9528 }
9529
9530 // C pointers are not compatible with ObjC object pointers,
9531 // with two exceptions:
9532 if (isa<ObjCObjectPointerType>(RHSType)) {
9533 // - conversions to void*
9534 if (LHSPointer->getPointeeType()->isVoidType()) {
9535 Kind = CK_BitCast;
9536 return Compatible;
9537 }
9538
9539 // - conversions from 'Class' to the redefinition type
9540 if (RHSType->isObjCClassType() &&
9541 Context.hasSameType(LHSType,
9542 Context.getObjCClassRedefinitionType())) {
9543 Kind = CK_BitCast;
9544 return Compatible;
9545 }
9546
9547 Kind = CK_BitCast;
9548 return IncompatiblePointer;
9549 }
9550
9551 // U^ -> void*
9552 if (RHSType->getAs<BlockPointerType>()) {
9553 if (LHSPointer->getPointeeType()->isVoidType()) {
9554 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9555 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9556 ->getPointeeType()
9557 .getAddressSpace();
9558 Kind =
9559 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9560 return Compatible;
9561 }
9562 }
9563
9564 return Incompatible;
9565 }
9566
9567 // Conversions to block pointers.
9568 if (isa<BlockPointerType>(LHSType)) {
53
Assuming 'LHSType' is a 'BlockPointerType'
54
Taking true branch
9569 // U^ -> T^
9570 if (RHSType->isBlockPointerType()) {
55
Calling 'Type::isBlockPointerType'
58
Returning from 'Type::isBlockPointerType'
59
Taking true branch
9571 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
60
Assuming the object is not a 'BlockPointerType'
61
Called C++ object pointer is null
9572 ->getPointeeType()
9573 .getAddressSpace();
9574 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9575 ->getPointeeType()
9576 .getAddressSpace();
9577 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9578 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9579 }
9580
9581 // int or null -> T^
9582 if (RHSType->isIntegerType()) {
9583 Kind = CK_IntegralToPointer; // FIXME: null
9584 return IntToBlockPointer;
9585 }
9586
9587 // id -> T^
9588 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9589 Kind = CK_AnyPointerToBlockPointerCast;
9590 return Compatible;
9591 }
9592
9593 // void* -> T^
9594 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9595 if (RHSPT->getPointeeType()->isVoidType()) {
9596 Kind = CK_AnyPointerToBlockPointerCast;
9597 return Compatible;
9598 }
9599
9600 return Incompatible;
9601 }
9602
9603 // Conversions to Objective-C pointers.
9604 if (isa<ObjCObjectPointerType>(LHSType)) {
9605 // A* -> B*
9606 if (RHSType->isObjCObjectPointerType()) {
9607 Kind = CK_BitCast;
9608 Sema::AssignConvertType result =
9609 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9610 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9611 result == Compatible &&
9612 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9613 result = IncompatibleObjCWeakRef;
9614 return result;
9615 }
9616
9617 // int or null -> A*
9618 if (RHSType->isIntegerType()) {
9619 Kind = CK_IntegralToPointer; // FIXME: null
9620 return IntToPointer;
9621 }
9622
9623 // In general, C pointers are not compatible with ObjC object pointers,
9624 // with two exceptions:
9625 if (isa<PointerType>(RHSType)) {
9626 Kind = CK_CPointerToObjCPointerCast;
9627
9628 // - conversions from 'void*'
9629 if (RHSType->isVoidPointerType()) {
9630 return Compatible;
9631 }
9632
9633 // - conversions to 'Class' from its redefinition type
9634 if (LHSType->isObjCClassType() &&
9635 Context.hasSameType(RHSType,
9636 Context.getObjCClassRedefinitionType())) {
9637 return Compatible;
9638 }
9639
9640 return IncompatiblePointer;
9641 }
9642
9643 // Only under strict condition T^ is compatible with an Objective-C pointer.
9644 if (RHSType->isBlockPointerType() &&
9645 LHSType->isBlockCompatibleObjCPointerType(Context)) {
9646 if (ConvertRHS)
9647 maybeExtendBlockObject(RHS);
9648 Kind = CK_BlockPointerToObjCPointerCast;
9649 return Compatible;
9650 }
9651
9652 return Incompatible;
9653 }
9654
9655 // Conversions from pointers that are not covered by the above.
9656 if (isa<PointerType>(RHSType)) {
9657 // T* -> _Bool
9658 if (LHSType == Context.BoolTy) {
9659 Kind = CK_PointerToBoolean;
9660 return Compatible;
9661 }
9662
9663 // T* -> int
9664 if (LHSType->isIntegerType()) {
9665 Kind = CK_PointerToIntegral;
9666 return PointerToInt;
9667 }
9668
9669 return Incompatible;
9670 }
9671
9672 // Conversions from Objective-C pointers that are not covered by the above.
9673 if (isa<ObjCObjectPointerType>(RHSType)) {
9674 // T* -> _Bool
9675 if (LHSType == Context.BoolTy) {
9676 Kind = CK_PointerToBoolean;
9677 return Compatible;
9678 }
9679
9680 // T* -> int
9681 if (LHSType->isIntegerType()) {
9682 Kind = CK_PointerToIntegral;
9683 return PointerToInt;
9684 }
9685
9686 return Incompatible;
9687 }
9688
9689 // struct A -> struct B
9690 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9691 if (Context.typesAreCompatible(LHSType, RHSType)) {
9692 Kind = CK_NoOp;
9693 return Compatible;
9694 }
9695 }
9696
9697 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9698 Kind = CK_IntToOCLSampler;
9699 return Compatible;
9700 }
9701
9702 return Incompatible;
9703}
9704
9705/// Constructs a transparent union from an expression that is
9706/// used to initialize the transparent union.
9707static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9708 ExprResult &EResult, QualType UnionType,
9709 FieldDecl *Field) {
9710 // Build an initializer list that designates the appropriate member
9711 // of the transparent union.
9712 Expr *E = EResult.get();
9713 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9714 E, SourceLocation());
9715 Initializer->setType(UnionType);
9716 Initializer->setInitializedFieldInUnion(Field);
9717
9718 // Build a compound literal constructing a value of the transparent
9719 // union type from this initializer list.
9720 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9721 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9722 VK_PRValue, Initializer, false);
9723}
9724
9725Sema::AssignConvertType
9726Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9727 ExprResult &RHS) {
9728 QualType RHSType = RHS.get()->getType();
9729
9730 // If the ArgType is a Union type, we want to handle a potential
9731 // transparent_union GCC extension.
9732 const RecordType *UT = ArgType->getAsUnionType();
9733 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9734 return Incompatible;
9735
9736 // The field to initialize within the transparent union.
9737 RecordDecl *UD = UT->getDecl();
9738 FieldDecl *InitField = nullptr;
9739 // It's compatible if the expression matches any of the fields.
9740 for (auto *it : UD->fields()) {
9741 if (it->getType()->isPointerType()) {
9742 // If the transparent union contains a pointer type, we allow:
9743 // 1) void pointer
9744 // 2) null pointer constant
9745 if (RHSType->isPointerType())
9746 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9747 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9748 InitField = it;
9749 break;
9750 }
9751
9752 if (RHS.get()->isNullPointerConstant(Context,
9753 Expr::NPC_ValueDependentIsNull)) {
9754 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9755 CK_NullToPointer);
9756 InitField = it;
9757 break;
9758 }
9759 }
9760
9761 CastKind Kind;
9762 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9763 == Compatible) {
9764 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9765 InitField = it;
9766 break;
9767 }
9768 }
9769
9770 if (!InitField)
9771 return Incompatible;
9772
9773 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9774 return Compatible;
9775}
9776
9777Sema::AssignConvertType
9778Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9779 bool Diagnose,
9780 bool DiagnoseCFAudited,
9781 bool ConvertRHS) {
9782 // We need to be able to tell the caller whether we diagnosed a problem, if
9783 // they ask us to issue diagnostics.
9784 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", 9784, __extension__ __PRETTY_FUNCTION__
))
;
9785
9786 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9787 // we can't avoid *all* modifications at the moment, so we need some somewhere
9788 // to put the updated value.
9789 ExprResult LocalRHS = CallerRHS;
9790 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9791
9792 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9793 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9794 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9795 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9796 Diag(RHS.get()->getExprLoc(),
9797 diag::warn_noderef_to_dereferenceable_pointer)
9798 << RHS.get()->getSourceRange();
9799 }
9800 }
9801 }
9802
9803 if (getLangOpts().CPlusPlus) {
9804 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9805 // C++ 5.17p3: If the left operand is not of class type, the
9806 // expression is implicitly converted (C++ 4) to the
9807 // cv-unqualified type of the left operand.
9808 QualType RHSType = RHS.get()->getType();
9809 if (Diagnose) {
9810 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9811 AA_Assigning);
9812 } else {
9813 ImplicitConversionSequence ICS =
9814 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9815 /*SuppressUserConversions=*/false,
9816 AllowedExplicit::None,
9817 /*InOverloadResolution=*/false,
9818 /*CStyle=*/false,
9819 /*AllowObjCWritebackConversion=*/false);
9820 if (ICS.isFailure())
9821 return Incompatible;
9822 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9823 ICS, AA_Assigning);
9824 }
9825 if (RHS.isInvalid())
9826 return Incompatible;
9827 Sema::AssignConvertType result = Compatible;
9828 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9829 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9830 result = IncompatibleObjCWeakRef;
9831 return result;
9832 }
9833
9834 // FIXME: Currently, we fall through and treat C++ classes like C
9835 // structures.
9836 // FIXME: We also fall through for atomics; not sure what should
9837 // happen there, though.
9838 } else if (RHS.get()->getType() == Context.OverloadTy) {
9839 // As a set of extensions to C, we support overloading on functions. These
9840 // functions need to be resolved here.
9841 DeclAccessPair DAP;
9842 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9843 RHS.get(), LHSType, /*Complain=*/false, DAP))
9844 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9845 else
9846 return Incompatible;
9847 }
9848
9849 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9850 // a null pointer constant.
9851 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9852 LHSType->isBlockPointerType()) &&
9853 RHS.get()->isNullPointerConstant(Context,
9854 Expr::NPC_ValueDependentIsNull)) {
9855 if (Diagnose || ConvertRHS) {
9856 CastKind Kind;
9857 CXXCastPath Path;
9858 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9859 /*IgnoreBaseAccess=*/false, Diagnose);
9860 if (ConvertRHS)
9861 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9862 }
9863 return Compatible;
9864 }
9865
9866 // OpenCL queue_t type assignment.
9867 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9868 Context, Expr::NPC_ValueDependentIsNull)) {
9869 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9870 return Compatible;
9871 }
9872
9873 // This check seems unnatural, however it is necessary to ensure the proper
9874 // conversion of functions/arrays. If the conversion were done for all
9875 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9876 // expressions that suppress this implicit conversion (&, sizeof).
9877 //
9878 // Suppress this for references: C++ 8.5.3p5.
9879 if (!LHSType->isReferenceType()) {
9880 // FIXME: We potentially allocate here even if ConvertRHS is false.
9881 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9882 if (RHS.isInvalid())
9883 return Incompatible;
9884 }
9885 CastKind Kind;
9886 Sema::AssignConvertType result =
9887 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9888
9889 // C99 6.5.16.1p2: The value of the right operand is converted to the
9890 // type of the assignment expression.
9891 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9892 // so that we can use references in built-in functions even in C.
9893 // The getNonReferenceType() call makes sure that the resulting expression
9894 // does not have reference type.
9895 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9896 QualType Ty = LHSType.getNonLValueExprType(Context);
9897 Expr *E = RHS.get();
9898
9899 // Check for various Objective-C errors. If we are not reporting
9900 // diagnostics and just checking for errors, e.g., during overload
9901 // resolution, return Incompatible to indicate the failure.
9902 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9903 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9904 Diagnose, DiagnoseCFAudited) != ACR_okay) {
9905 if (!Diagnose)
9906 return Incompatible;
9907 }
9908 if (getLangOpts().ObjC &&
9909 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9910 E->getType(), E, Diagnose) ||
9911 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9912 if (!Diagnose)
9913 return Incompatible;
9914 // Replace the expression with a corrected version and continue so we
9915 // can find further errors.
9916 RHS = E;
9917 return Compatible;
9918 }
9919
9920 if (ConvertRHS)
9921 RHS = ImpCastExprToType(E, Ty, Kind);
9922 }
9923
9924 return result;
9925}
9926
9927namespace {
9928/// The original operand to an operator, prior to the application of the usual
9929/// arithmetic conversions and converting the arguments of a builtin operator
9930/// candidate.
9931struct OriginalOperand {
9932 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9933 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9934 Op = MTE->getSubExpr();
9935 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9936 Op = BTE->getSubExpr();
9937 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9938 Orig = ICE->getSubExprAsWritten();
9939 Conversion = ICE->getConversionFunction();
9940 }
9941 }
9942
9943 QualType getType() const { return Orig->getType(); }
9944
9945 Expr *Orig;
9946 NamedDecl *Conversion;
9947};
9948}
9949
9950QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9951 ExprResult &RHS) {
9952 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9953
9954 Diag(Loc, diag::err_typecheck_invalid_operands)
9955 << OrigLHS.getType() << OrigRHS.getType()
9956 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9957
9958 // If a user-defined conversion was applied to either of the operands prior
9959 // to applying the built-in operator rules, tell the user about it.
9960 if (OrigLHS.Conversion) {
9961 Diag(OrigLHS.Conversion->getLocation(),
9962 diag::note_typecheck_invalid_operands_converted)
9963 << 0 << LHS.get()->getType();
9964 }
9965 if (OrigRHS.Conversion) {
9966 Diag(OrigRHS.Conversion->getLocation(),
9967 diag::note_typecheck_invalid_operands_converted)
9968 << 1 << RHS.get()->getType();
9969 }
9970
9971 return QualType();
9972}
9973
9974// Diagnose cases where a scalar was implicitly converted to a vector and
9975// diagnose the underlying types. Otherwise, diagnose the error
9976// as invalid vector logical operands for non-C++ cases.
9977QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9978 ExprResult &RHS) {
9979 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9980 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9981
9982 bool LHSNatVec = LHSType->isVectorType();
9983 bool RHSNatVec = RHSType->isVectorType();
9984
9985 if (!(LHSNatVec && RHSNatVec)) {
9986 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9987 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9988 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9989 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9990 << Vector->getSourceRange();
9991 return QualType();
9992 }
9993
9994 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9995 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9996 << RHS.get()->getSourceRange();
9997
9998 return QualType();
9999}
10000
10001/// Try to convert a value of non-vector type to a vector type by converting
10002/// the type to the element type of the vector and then performing a splat.
10003/// If the language is OpenCL, we only use conversions that promote scalar
10004/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10005/// for float->int.
10006///
10007/// OpenCL V2.0 6.2.6.p2:
10008/// An error shall occur if any scalar operand type has greater rank
10009/// than the type of the vector element.
10010///
10011/// \param scalar - if non-null, actually perform the conversions
10012/// \return true if the operation fails (but without diagnosing the failure)
10013static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10014 QualType scalarTy,
10015 QualType vectorEltTy,
10016 QualType vectorTy,
10017 unsigned &DiagID) {
10018 // The conversion to apply to the scalar before splatting it,
10019 // if necessary.
10020 CastKind scalarCast = CK_NoOp;
10021
10022 if (vectorEltTy->isIntegralType(S.Context)) {
10023 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10024 (scalarTy->isIntegerType() &&
10025 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10026 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10027 return true;
10028 }
10029 if (!scalarTy->isIntegralType(S.Context))
10030 return true;
10031 scalarCast = CK_IntegralCast;
10032 } else if (vectorEltTy->isRealFloatingType()) {
10033 if (scalarTy->isRealFloatingType()) {
10034 if (S.getLangOpts().OpenCL &&
10035 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10036 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10037 return true;
10038 }
10039 scalarCast = CK_FloatingCast;
10040 }
10041 else if (scalarTy->isIntegralType(S.Context))
10042 scalarCast = CK_IntegralToFloating;
10043 else
10044 return true;
10045 } else {
10046 return true;
10047 }
10048
10049 // Adjust scalar if desired.
10050 if (scalar) {
10051 if (scalarCast != CK_NoOp)
10052 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10053 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10054 }
10055 return false;
10056}
10057
10058/// Convert vector E to a vector with the same number of elements but different
10059/// element type.
10060static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10061 const auto *VecTy = E->getType()->getAs<VectorType>();
10062 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", 10062, __extension__ __PRETTY_FUNCTION__
))
;
10063 QualType NewVecTy = S.Context.getVectorType(ElementType,
10064 VecTy->getNumElements(),
10065 VecTy->getVectorKind());
10066
10067 // Look through the implicit cast. Return the subexpression if its type is
10068 // NewVecTy.
10069 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10070 if (ICE->getSubExpr()->getType() == NewVecTy)
10071 return ICE->getSubExpr();
10072
10073 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10074 return S.ImpCastExprToType(E, NewVecTy, Cast);
10075}
10076
10077/// Test if a (constant) integer Int can be casted to another integer type
10078/// IntTy without losing precision.
10079static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10080 QualType OtherIntTy) {
10081 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10082
10083 // Reject cases where the value of the Int is unknown as that would
10084 // possibly cause truncation, but accept cases where the scalar can be
10085 // demoted without loss of precision.
10086 Expr::EvalResult EVResult;
10087 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10088 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10089 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10090 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10091
10092 if (CstInt) {
10093 // If the scalar is constant and is of a higher order and has more active
10094 // bits that the vector element type, reject it.
10095 llvm::APSInt Result = EVResult.Val.getInt();
10096 unsigned NumBits = IntSigned
10097 ? (Result.isNegative() ? Result.getMinSignedBits()
10098 : Result.getActiveBits())
10099 : Result.getActiveBits();
10100 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10101 return true;
10102
10103 // If the signedness of the scalar type and the vector element type
10104 // differs and the number of bits is greater than that of the vector
10105 // element reject it.
10106 return (IntSigned != OtherIntSigned &&
10107 NumBits > S.Context.getIntWidth(OtherIntTy));
10108 }
10109
10110 // Reject cases where the value of the scalar is not constant and it's
10111 // order is greater than that of the vector element type.
10112 return (Order < 0);
10113}
10114
10115/// Test if a (constant) integer Int can be casted to floating point type
10116/// FloatTy without losing precision.
10117static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10118 QualType FloatTy) {
10119 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10120
10121 // Determine if the integer constant can be expressed as a floating point
10122 // number of the appropriate type.
10123 Expr::EvalResult EVResult;
10124 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10125
10126 uint64_t Bits = 0;
10127 if (CstInt) {
10128 // Reject constants that would be truncated if they were converted to
10129 // the floating point type. Test by simple to/from conversion.
10130 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10131 // could be avoided if there was a convertFromAPInt method
10132 // which could signal back if implicit truncation occurred.
10133 llvm::APSInt Result = EVResult.Val.getInt();
10134 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10135 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10136 llvm::APFloat::rmTowardZero);
10137 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10138 !IntTy->hasSignedIntegerRepresentation());
10139 bool Ignored = false;
10140 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10141 &Ignored);
10142 if (Result != ConvertBack)
10143 return true;
10144 } else {
10145 // Reject types that cannot be fully encoded into the mantissa of
10146 // the float.
10147 Bits = S.Context.getTypeSize(IntTy);
10148 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10149 S.Context.getFloatTypeSemantics(FloatTy));
10150 if (Bits > FloatPrec)
10151 return true;
10152 }
10153
10154 return false;
10155}
10156
10157/// Attempt to convert and splat Scalar into a vector whose types matches
10158/// Vector following GCC conversion rules. The rule is that implicit
10159/// conversion can occur when Scalar can be casted to match Vector's element
10160/// type without causing truncation of Scalar.
10161static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10162 ExprResult *Vector) {
10163 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10164 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10165 const auto *VT = VectorTy->castAs<VectorType>();
10166
10167 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", 10168, __extension__ __PRETTY_FUNCTION__
))
10168 "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", 10168, __extension__ __PRETTY_FUNCTION__
))
;
10169
10170 QualType VectorEltTy = VT->getElementType();
10171
10172 // Reject cases where the vector element type or the scalar element type are
10173 // not integral or floating point types.
10174 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10175 return true;
10176
10177 // The conversion to apply to the scalar before splatting it,
10178 // if necessary.
10179 CastKind ScalarCast = CK_NoOp;
10180
10181 // Accept cases where the vector elements are integers and the scalar is
10182 // an integer.
10183 // FIXME: Notionally if the scalar was a floating point value with a precise
10184 // integral representation, we could cast it to an appropriate integer
10185 // type and then perform the rest of the checks here. GCC will perform
10186 // this conversion in some cases as determined by the input language.
10187 // We should accept it on a language independent basis.
10188 if (VectorEltTy->isIntegralType(S.Context) &&
10189 ScalarTy->isIntegralType(S.Context) &&
10190 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10191
10192 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10193 return true;
10194
10195 ScalarCast = CK_IntegralCast;
10196 } else if (VectorEltTy->isIntegralType(S.Context) &&
10197 ScalarTy->isRealFloatingType()) {
10198 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10199 ScalarCast = CK_FloatingToIntegral;
10200 else
10201 return true;
10202 } else if (VectorEltTy->isRealFloatingType()) {
10203 if (ScalarTy->isRealFloatingType()) {
10204
10205 // Reject cases where the scalar type is not a constant and has a higher
10206 // Order than the vector element type.
10207 llvm::APFloat Result(0.0);
10208
10209 // Determine whether this is a constant scalar. In the event that the
10210 // value is dependent (and thus cannot be evaluated by the constant
10211 // evaluator), skip the evaluation. This will then diagnose once the
10212 // expression is instantiated.
10213 bool CstScalar = Scalar->get()->isValueDependent() ||
10214 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10215 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10216 if (!CstScalar && Order < 0)
10217 return true;
10218
10219 // If the scalar cannot be safely casted to the vector element type,
10220 // reject it.
10221 if (CstScalar) {
10222 bool Truncated = false;
10223 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10224 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10225 if (Truncated)
10226 return true;
10227 }
10228
10229 ScalarCast = CK_FloatingCast;
10230 } else if (ScalarTy->isIntegralType(S.Context)) {
10231 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10232 return true;
10233
10234 ScalarCast = CK_IntegralToFloating;
10235 } else
10236 return true;
10237 } else if (ScalarTy->isEnumeralType())
10238 return true;
10239
10240 // Adjust scalar if desired.
10241 if (Scalar) {
10242 if (ScalarCast != CK_NoOp)
10243 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10244 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10245 }
10246 return false;
10247}
10248
10249QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10250 SourceLocation Loc, bool IsCompAssign,
10251 bool AllowBothBool,
10252 bool AllowBoolConversions,
10253 bool AllowBoolOperation,
10254 bool ReportInvalid) {
10255 if (!IsCompAssign) {
10256 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10257 if (LHS.isInvalid())
10258 return QualType();
10259 }
10260 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10261 if (RHS.isInvalid())
10262 return QualType();
10263
10264 // For conversion purposes, we ignore any qualifiers.
10265 // For example, "const float" and "float" are equivalent.
10266 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10267 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10268
10269 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10270 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10271 assert(LHSVecType || RHSVecType)(static_cast <bool> (LHSVecType || RHSVecType) ? void (
0) : __assert_fail ("LHSVecType || RHSVecType", "clang/lib/Sema/SemaExpr.cpp"
, 10271, __extension__ __PRETTY_FUNCTION__))
;
10272
10273 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10274 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10275 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10276
10277 // AltiVec-style "vector bool op vector bool" combinations are allowed
10278 // for some operators but not others.
10279 if (!AllowBothBool &&
10280 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10281 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10282 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10283
10284 // This operation may not be performed on boolean vectors.
10285 if (!AllowBoolOperation &&
10286 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10287 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10288
10289 // If the vector types are identical, return.
10290 if (Context.hasSameType(LHSType, RHSType))
10291 return LHSType;
10292
10293 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10294 if (LHSVecType && RHSVecType &&
10295 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10296 if (isa<ExtVectorType>(LHSVecType)) {
10297 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10298 return LHSType;
10299 }
10300
10301 if (!IsCompAssign)
10302 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10303 return RHSType;
10304 }
10305
10306 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10307 // can be mixed, with the result being the non-bool type. The non-bool
10308 // operand must have integer element type.
10309 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10310 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10311 (Context.getTypeSize(LHSVecType->getElementType()) ==
10312 Context.getTypeSize(RHSVecType->getElementType()))) {
10313 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10314 LHSVecType->getElementType()->isIntegerType() &&
10315 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10316 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10317 return LHSType;
10318 }
10319 if (!IsCompAssign &&
10320 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10321 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10322 RHSVecType->getElementType()->isIntegerType()) {
10323 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10324 return RHSType;
10325 }
10326 }
10327
10328 // Expressions containing fixed-length and sizeless SVE vectors are invalid
10329 // since the ambiguity can affect the ABI.
10330 auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10331 const VectorType *VecType = SecondType->getAs<VectorType>();
10332 return FirstType->isSizelessBuiltinType() && VecType &&
10333 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10334 VecType->getVectorKind() ==
10335 VectorType::SveFixedLengthPredicateVector);
10336 };
10337
10338 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10339 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10340 return QualType();
10341 }
10342
10343 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10344 // since the ambiguity can affect the ABI.
10345 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10346 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10347 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10348
10349 if (FirstVecType && SecondVecType)
10350 return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10351 (SecondVecType->getVectorKind() ==
10352 VectorType::SveFixedLengthDataVector ||
10353 SecondVecType->getVectorKind() ==
10354 VectorType::SveFixedLengthPredicateVector);
10355
10356 return FirstType->isSizelessBuiltinType() && SecondVecType &&
10357 SecondVecType->getVectorKind() == VectorType::GenericVector;
10358 };
10359
10360 if (IsSveGnuConversion(LHSType, RHSType) ||
10361 IsSveGnuConversion(RHSType, LHSType)) {
10362 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10363 return QualType();
10364 }
10365
10366 // If there's a vector type and a scalar, try to convert the scalar to
10367 // the vector element type and splat.
10368 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10369 if (!RHSVecType) {
10370 if (isa<ExtVectorType>(LHSVecType)) {
10371 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10372 LHSVecType->getElementType(), LHSType,
10373 DiagID))
10374 return LHSType;
10375 } else {
10376 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10377 return LHSType;
10378 }
10379 }
10380 if (!LHSVecType) {
10381 if (isa<ExtVectorType>(RHSVecType)) {
10382 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10383 LHSType, RHSVecType->getElementType(),
10384 RHSType, DiagID))
10385 return RHSType;
10386 } else {
10387 if (LHS.get()->isLValue() ||
10388 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10389 return RHSType;
10390 }
10391 }
10392
10393 // FIXME: The code below also handles conversion between vectors and
10394 // non-scalars, we should break this down into fine grained specific checks
10395 // and emit proper diagnostics.
10396 QualType VecType = LHSVecType ? LHSType : RHSType;
10397 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10398 QualType OtherType = LHSVecType ? RHSType : LHSType;
10399 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10400 if (isLaxVectorConversion(OtherType, VecType)) {
10401 // If we're allowing lax vector conversions, only the total (data) size
10402 // needs to be the same. For non compound assignment, if one of the types is
10403 // scalar, the result is always the vector type.
10404 if (!IsCompAssign) {
10405 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10406 return VecType;
10407 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10408 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10409 // type. Note that this is already done by non-compound assignments in
10410 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10411 // <1 x T> -> T. The result is also a vector type.
10412 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10413 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10414 ExprResult *RHSExpr = &RHS;
10415 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10416 return VecType;
10417 }
10418 }
10419
10420 // Okay, the expression is invalid.
10421
10422 // If there's a non-vector, non-real operand, diagnose that.
10423 if ((!RHSVecType && !RHSType->isRealType()) ||
10424 (!LHSVecType && !LHSType->isRealType())) {
10425 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10426 << LHSType << RHSType
10427 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10428 return QualType();
10429 }
10430
10431 // OpenCL V1.1 6.2.6.p1:
10432 // If the operands are of more than one vector type, then an error shall
10433 // occur. Implicit conversions between vector types are not permitted, per
10434 // section 6.2.1.
10435 if (getLangOpts().OpenCL &&
10436 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10437 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10438 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10439 << RHSType;
10440 return QualType();
10441 }
10442
10443
10444 // If there is a vector type that is not a ExtVector and a scalar, we reach
10445 // this point if scalar could not be converted to the vector's element type
10446 // without truncation.
10447 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10448 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10449 QualType Scalar = LHSVecType ? RHSType : LHSType;
10450 QualType Vector = LHSVecType ? LHSType : RHSType;
10451 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10452 Diag(Loc,
10453 diag::err_typecheck_vector_not_convertable_implict_truncation)
10454 << ScalarOrVector << Scalar << Vector;
10455
10456 return QualType();
10457 }
10458
10459 // Otherwise, use the generic diagnostic.
10460 Diag(Loc, DiagID)
10461 << LHSType << RHSType
10462 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10463 return QualType();
10464}
10465
10466QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10467 SourceLocation Loc,
10468 ArithConvKind OperationKind) {
10469 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10470 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10471
10472 const BuiltinType *LHSVecType = LHSType->getAs<BuiltinType>();
10473 const BuiltinType *RHSVecType = RHSType->getAs<BuiltinType>();
10474
10475 unsigned DiagID = diag::err_typecheck_invalid_operands;
10476 if ((OperationKind == ACK_Arithmetic) &&
10477 (LHSVecType->isSVEBool() || RHSVecType->isSVEBool())) {
10478 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10479 << RHS.get()->getSourceRange();
10480 return QualType();
10481 }
10482
10483 if (Context.hasSameType(LHSType, RHSType))
10484 return LHSType;
10485
10486 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10487 << RHS.get()->getSourceRange();
10488 return QualType();
10489}
10490
10491// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10492// expression. These are mainly cases where the null pointer is used as an
10493// integer instead of a pointer.
10494static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10495 SourceLocation Loc, bool IsCompare) {
10496 // The canonical way to check for a GNU null is with isNullPointerConstant,
10497 // but we use a bit of a hack here for speed; this is a relatively
10498 // hot path, and isNullPointerConstant is slow.
10499 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10500 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10501
10502 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10503
10504 // Avoid analyzing cases where the result will either be invalid (and
10505 // diagnosed as such) or entirely valid and not something to warn about.
10506 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10507 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10508 return;
10509
10510 // Comparison operations would not make sense with a null pointer no matter
10511 // what the other expression is.
10512 if (!IsCompare) {
10513 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10514 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10515 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10516 return;
10517 }
10518
10519 // The rest of the operations only make sense with a null pointer
10520 // if the other expression is a pointer.
10521 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10522 NonNullType->canDecayToPointerType())
10523 return;
10524
10525 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10526 << LHSNull /* LHS is NULL */ << NonNullType
10527 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10528}
10529
10530static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10531 SourceLocation Loc) {
10532 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10533 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10534 if (!LUE || !RUE)
10535 return;
10536 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10537 RUE->getKind() != UETT_SizeOf)
10538 return;
10539
10540 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10541 QualType LHSTy = LHSArg->getType();
10542 QualType RHSTy;
10543
10544 if (RUE->isArgumentType())
10545 RHSTy = RUE->getArgumentType().getNonReferenceType();
10546 else
10547 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10548
10549 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10550 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10551 return;
10552
10553 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10554 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10555 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10556 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10557 << LHSArgDecl;
10558 }
10559 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10560 QualType ArrayElemTy = ArrayTy->getElementType();
10561 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10562 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10563 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10564 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10565 return;
10566 S.Diag(Loc, diag::warn_division_sizeof_array)
10567 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10568 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10569 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10570 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10571 << LHSArgDecl;
10572 }
10573
10574 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10575 }
10576}
10577
10578static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10579 ExprResult &RHS,
10580 SourceLocation Loc, bool IsDiv) {
10581 // Check for division/remainder by zero.
10582 Expr::EvalResult RHSValue;
10583 if (!RHS.get()->isValueDependent() &&
10584 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10585 RHSValue.Val.getInt() == 0)
10586 S.DiagRuntimeBehavior(Loc, RHS.get(),
10587 S.PDiag(diag::warn_remainder_division_by_zero)
10588 << IsDiv << RHS.get()->getSourceRange());
10589}
10590
10591QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10592 SourceLocation Loc,
10593 bool IsCompAssign, bool IsDiv) {
10594 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10595
10596 QualType LHSTy = LHS.get()->getType();
10597 QualType RHSTy = RHS.get()->getType();
10598 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10599 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10600 /*AllowBothBool*/ getLangOpts().AltiVec,
10601 /*AllowBoolConversions*/ false,
10602 /*AllowBooleanOperation*/ false,
10603 /*ReportInvalid*/ true);
10604 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
10605 return CheckSizelessVectorOperands(LHS, RHS, Loc, ACK_Arithmetic);
10606 if (!IsDiv &&
10607 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10608 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10609 // For division, only matrix-by-scalar is supported. Other combinations with
10610 // matrix types are invalid.
10611 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10612 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10613
10614 QualType compType = UsualArithmeticConversions(
10615 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10616 if (LHS.isInvalid() || RHS.isInvalid())
10617 return QualType();
10618
10619
10620 if (compType.isNull() || !compType->isArithmeticType())
10621 return InvalidOperands(Loc, LHS, RHS);
10622 if (IsDiv) {
10623 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10624 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10625 }
10626 return compType;
10627}
10628
10629QualType Sema::CheckRemainderOperands(
10630 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10631 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10632
10633 if (LHS.get()->getType()->isVectorType() ||
10634 RHS.get()->getType()->isVectorType()) {
10635 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10636 RHS.get()->getType()->hasIntegerRepresentation())
10637 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10638 /*AllowBothBool*/ getLangOpts().AltiVec,
10639 /*AllowBoolConversions*/ false,
10640 /*AllowBooleanOperation*/ false,
10641 /*ReportInvalid*/ true);
10642 return InvalidOperands(Loc, LHS, RHS);
10643 }
10644
10645 if (LHS.get()->getType()->isVLSTBuiltinType() &&
10646 RHS.get()->getType()->isVLSTBuiltinType()) {
10647 if (LHS.get()
10648 ->getType()
10649 ->getSveEltType(Context)
10650 ->hasIntegerRepresentation() &&
10651 RHS.get()
10652 ->getType()
10653 ->getSveEltType(Context)
10654 ->hasIntegerRepresentation())
10655 return CheckSizelessVectorOperands(LHS, RHS, Loc, ACK_Arithmetic);
10656
10657 return InvalidOperands(Loc, LHS, RHS);
10658 }
10659
10660 QualType compType = UsualArithmeticConversions(
10661 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10662 if (LHS.isInvalid() || RHS.isInvalid())
10663 return QualType();
10664
10665 if (compType.isNull() || !compType->isIntegerType())
10666 return InvalidOperands(Loc, LHS, RHS);
10667 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10668 return compType;
10669}
10670
10671/// Diagnose invalid arithmetic on two void pointers.
10672static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10673 Expr *LHSExpr, Expr *RHSExpr) {
10674 S.Diag(Loc, S.getLangOpts().CPlusPlus
10675 ? diag::err_typecheck_pointer_arith_void_type
10676 : diag::ext_gnu_void_ptr)
10677 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10678 << RHSExpr->getSourceRange();
10679}
10680
10681/// Diagnose invalid arithmetic on a void pointer.
10682static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10683 Expr *Pointer) {
10684 S.Diag(Loc, S.getLangOpts().CPlusPlus
10685 ? diag::err_typecheck_pointer_arith_void_type
10686 : diag::ext_gnu_void_ptr)
10687 << 0 /* one pointer */ << Pointer->getSourceRange();
10688}
10689
10690/// Diagnose invalid arithmetic on a null pointer.
10691///
10692/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10693/// idiom, which we recognize as a GNU extension.
10694///
10695static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10696 Expr *Pointer, bool IsGNUIdiom) {
10697 if (IsGNUIdiom)
10698 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10699 << Pointer->getSourceRange();
10700 else
10701 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10702 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10703}
10704
10705/// Diagnose invalid subraction on a null pointer.
10706///
10707static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10708 Expr *Pointer, bool BothNull) {
10709 // Null - null is valid in C++ [expr.add]p7
10710 if (BothNull && S.getLangOpts().CPlusPlus)
10711 return;
10712
10713 // Is this s a macro from a system header?
10714 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10715 return;
10716
10717 S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10718 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10719}
10720
10721/// Diagnose invalid arithmetic on two function pointers.
10722static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10723 Expr *LHS, Expr *RHS) {
10724 assert(LHS->getType()->isAnyPointerType())(static_cast <bool> (LHS->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("LHS->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 10724, __extension__ __PRETTY_FUNCTION__
))
;
10725 assert(RHS->getType()->isAnyPointerType())(static_cast <bool> (RHS->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("RHS->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 10725, __extension__ __PRETTY_FUNCTION__
))
;
10726 S.Diag(Loc, S.getLangOpts().CPlusPlus
10727 ? diag::err_typecheck_pointer_arith_function_type
10728 : diag::ext_gnu_ptr_func_arith)
10729 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10730 // We only show the second type if it differs from the first.
10731 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10732 RHS->getType())
10733 << RHS->getType()->getPointeeType()
10734 << LHS->getSourceRange() << RHS->getSourceRange();
10735}
10736
10737/// Diagnose invalid arithmetic on a function pointer.
10738static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10739 Expr *Pointer) {
10740 assert(Pointer->getType()->isAnyPointerType())(static_cast <bool> (Pointer->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 10740, __extension__ __PRETTY_FUNCTION__
))
;
10741 S.Diag(Loc, S.getLangOpts().CPlusPlus
10742 ? diag::err_typecheck_pointer_arith_function_type
10743 : diag::ext_gnu_ptr_func_arith)
10744 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10745 << 0 /* one pointer, so only one type */
10746 << Pointer->getSourceRange();
10747}
10748
10749/// Emit error if Operand is incomplete pointer type
10750///
10751/// \returns True if pointer has incomplete type
10752static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10753 Expr *Operand) {
10754 QualType ResType = Operand->getType();
10755 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10756 ResType = ResAtomicType->getValueType();
10757
10758 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", 10758, __extension__ __PRETTY_FUNCTION__
))
;
10759 QualType PointeeTy = ResType->getPointeeType();
10760 return S.RequireCompleteSizedType(
10761 Loc, PointeeTy,
10762 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10763 Operand->getSourceRange());
10764}
10765
10766/// Check the validity of an arithmetic pointer operand.
10767///
10768/// If the operand has pointer type, this code will check for pointer types
10769/// which are invalid in arithmetic operations. These will be diagnosed
10770/// appropriately, including whether or not the use is supported as an
10771/// extension.
10772///
10773/// \returns True when the operand is valid to use (even if as an extension).
10774static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10775 Expr *Operand) {
10776 QualType ResType = Operand->getType();
10777 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10778 ResType = ResAtomicType->getValueType();
10779
10780 if (!ResType->isAnyPointerType()) return true;
10781
10782 QualType PointeeTy = ResType->getPointeeType();
10783 if (PointeeTy->isVoidType()) {
10784 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10785 return !S.getLangOpts().CPlusPlus;
10786 }
10787 if (PointeeTy->isFunctionType()) {
10788 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10789 return !S.getLangOpts().CPlusPlus;
10790 }
10791
10792 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10793
10794 return true;
10795}
10796
10797/// Check the validity of a binary arithmetic operation w.r.t. pointer
10798/// operands.
10799///
10800/// This routine will diagnose any invalid arithmetic on pointer operands much
10801/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10802/// for emitting a single diagnostic even for operations where both LHS and RHS
10803/// are (potentially problematic) pointers.
10804///
10805/// \returns True when the operand is valid to use (even if as an extension).
10806static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10807 Expr *LHSExpr, Expr *RHSExpr) {
10808 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10809 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10810 if (!isLHSPointer && !isRHSPointer) return true;
10811
10812 QualType LHSPointeeTy, RHSPointeeTy;
10813 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10814 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10815
10816 // if both are pointers check if operation is valid wrt address spaces
10817 if (isLHSPointer && isRHSPointer) {
10818 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10819 S.Diag(Loc,
10820 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10821 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10822 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10823 return false;
10824 }
10825 }
10826
10827 // Check for arithmetic on pointers to incomplete types.
10828 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10829 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10830 if (isLHSVoidPtr || isRHSVoidPtr) {
10831 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10832 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10833 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10834
10835 return !S.getLangOpts().CPlusPlus;
10836 }
10837
10838 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10839 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10840 if (isLHSFuncPtr || isRHSFuncPtr) {
10841 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10842 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10843 RHSExpr);
10844 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10845
10846 return !S.getLangOpts().CPlusPlus;
10847 }
10848
10849 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10850 return false;
10851 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10852 return false;
10853
10854 return true;
10855}
10856
10857/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10858/// literal.
10859static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10860 Expr *LHSExpr, Expr *RHSExpr) {
10861 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10862 Expr* IndexExpr = RHSExpr;
10863 if (!StrExpr) {
10864 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10865 IndexExpr = LHSExpr;
10866 }
10867
10868 bool IsStringPlusInt = StrExpr &&
10869 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10870 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10871 return;
10872
10873 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10874 Self.Diag(OpLoc, diag::warn_string_plus_int)
10875 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10876
10877 // Only print a fixit for "str" + int, not for int + "str".
10878 if (IndexExpr == RHSExpr) {
10879 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10880 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10881 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10882 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10883 << FixItHint::CreateInsertion(EndLoc, "]");
10884 } else
10885 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10886}
10887
10888/// Emit a warning when adding a char literal to a string.
10889static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10890 Expr *LHSExpr, Expr *RHSExpr) {
10891 const Expr *StringRefExpr = LHSExpr;
10892 const CharacterLiteral *CharExpr =
10893 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10894
10895 if (!CharExpr) {
10896 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10897 StringRefExpr = RHSExpr;
10898 }
10899
10900 if (!CharExpr || !StringRefExpr)
10901 return;
10902
10903 const QualType StringType = StringRefExpr->getType();
10904
10905 // Return if not a PointerType.
10906 if (!StringType->isAnyPointerType())
10907 return;
10908
10909 // Return if not a CharacterType.
10910 if (!StringType->getPointeeType()->isAnyCharacterType())
10911 return;
10912
10913 ASTContext &Ctx = Self.getASTContext();
10914 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10915
10916 const QualType CharType = CharExpr->getType();
10917 if (!CharType->isAnyCharacterType() &&
10918 CharType->isIntegerType() &&
10919 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10920 Self.Diag(OpLoc, diag::warn_string_plus_char)
10921 << DiagRange << Ctx.CharTy;
10922 } else {
10923 Self.Diag(OpLoc, diag::warn_string_plus_char)
10924 << DiagRange << CharExpr->getType();
10925 }
10926
10927 // Only print a fixit for str + char, not for char + str.
10928 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10929 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10930 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10931 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10932 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10933 << FixItHint::CreateInsertion(EndLoc, "]");
10934 } else {
10935 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10936 }
10937}
10938
10939/// Emit error when two pointers are incompatible.
10940static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10941 Expr *LHSExpr, Expr *RHSExpr) {
10942 assert(LHSExpr->getType()->isAnyPointerType())(static_cast <bool> (LHSExpr->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 10942, __extension__ __PRETTY_FUNCTION__
))
;
10943 assert(RHSExpr->getType()->isAnyPointerType())(static_cast <bool> (RHSExpr->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 10943, __extension__ __PRETTY_FUNCTION__
))
;
10944 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10945 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10946 << RHSExpr->getSourceRange();
10947}
10948
10949// C99 6.5.6
10950QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10951 SourceLocation Loc, BinaryOperatorKind Opc,
10952 QualType* CompLHSTy) {
10953 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10954
10955 if (LHS.get()->getType()->isVectorType() ||
10956 RHS.get()->getType()->isVectorType()) {
10957 QualType compType =
10958 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
10959 /*AllowBothBool*/ getLangOpts().AltiVec,
10960 /*AllowBoolConversions*/ getLangOpts().ZVector,
10961 /*AllowBooleanOperation*/ false,
10962 /*ReportInvalid*/ true);
10963 if (CompLHSTy) *CompLHSTy = compType;
10964 return compType;
10965 }
10966
10967 if (LHS.get()->getType()->isVLSTBuiltinType() ||
10968 RHS.get()->getType()->isVLSTBuiltinType()) {
10969 QualType compType =
10970 CheckSizelessVectorOperands(LHS, RHS, Loc, ACK_Arithmetic);
10971 if (CompLHSTy)
10972 *CompLHSTy = compType;
10973 return compType;
10974 }
10975
10976 if (LHS.get()->getType()->isConstantMatrixType() ||
10977 RHS.get()->getType()->isConstantMatrixType()) {
10978 QualType compType =
10979 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10980 if (CompLHSTy)
10981 *CompLHSTy = compType;
10982 return compType;
10983 }
10984
10985 QualType compType = UsualArithmeticConversions(
10986 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10987 if (LHS.isInvalid() || RHS.isInvalid())
10988 return QualType();
10989
10990 // Diagnose "string literal" '+' int and string '+' "char literal".
10991 if (Opc == BO_Add) {
10992 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10993 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10994 }
10995
10996 // handle the common case first (both operands are arithmetic).
10997 if (!compType.isNull() && compType->isArithmeticType()) {
10998 if (CompLHSTy) *CompLHSTy = compType;
10999 return compType;
11000 }
11001
11002 // Type-checking. Ultimately the pointer's going to be in PExp;
11003 // note that we bias towards the LHS being the pointer.
11004 Expr *PExp = LHS.get(), *IExp = RHS.get();
11005
11006 bool isObjCPointer;
11007 if (PExp->getType()->isPointerType()) {
11008 isObjCPointer = false;
11009 } else if (PExp->getType()->isObjCObjectPointerType()) {
11010 isObjCPointer = true;
11011 } else {
11012 std::swap(PExp, IExp);
11013 if (PExp->getType()->isPointerType()) {
11014 isObjCPointer = false;
11015 } else if (PExp->getType()->isObjCObjectPointerType()) {
11016 isObjCPointer = true;
11017 } else {
11018 return InvalidOperands(Loc, LHS, RHS);
11019 }
11020 }
11021 assert(PExp->getType()->isAnyPointerType())(static_cast <bool> (PExp->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("PExp->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11021, __extension__ __PRETTY_FUNCTION__
))
;
11022
11023 if (!IExp->getType()->isIntegerType())
11024 return InvalidOperands(Loc, LHS, RHS);
11025
11026 // Adding to a null pointer results in undefined behavior.
11027 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11028 Context, Expr::NPC_ValueDependentIsNotNull)) {
11029 // In C++ adding zero to a null pointer is defined.
11030 Expr::EvalResult KnownVal;
11031 if (!getLangOpts().CPlusPlus ||
11032 (!IExp->isValueDependent() &&
11033 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11034 KnownVal.Val.getInt() != 0))) {
11035 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11036 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11037 Context, BO_Add, PExp, IExp);
11038 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11039 }
11040 }
11041
11042 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11043 return QualType();
11044
11045 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11046 return QualType();
11047
11048 // Check array bounds for pointer arithemtic
11049 CheckArrayAccess(PExp, IExp);
11050
11051 if (CompLHSTy) {
11052 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11053 if (LHSTy.isNull()) {
11054 LHSTy = LHS.get()->getType();
11055 if (LHSTy->isPromotableIntegerType())
11056 LHSTy = Context.getPromotedIntegerType(LHSTy);
11057 }
11058 *CompLHSTy = LHSTy;
11059 }
11060
11061 return PExp->getType();
11062}
11063
11064// C99 6.5.6
11065QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11066 SourceLocation Loc,
11067 QualType* CompLHSTy) {
11068 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11069
11070 if (LHS.get()->getType()->isVectorType() ||
11071 RHS.get()->getType()->isVectorType()) {
11072 QualType compType =
11073 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11074 /*AllowBothBool*/ getLangOpts().AltiVec,
11075 /*AllowBoolConversions*/ getLangOpts().ZVector,
11076 /*AllowBooleanOperation*/ false,
11077 /*ReportInvalid*/ true);
11078 if (CompLHSTy) *CompLHSTy = compType;
11079 return compType;
11080 }
11081
11082 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11083 RHS.get()->getType()->isVLSTBuiltinType()) {
11084 QualType compType =
11085 CheckSizelessVectorOperands(LHS, RHS, Loc, ACK_Arithmetic);
11086 if (CompLHSTy)
11087 *CompLHSTy = compType;
11088 return compType;
11089 }
11090
11091 if (LHS.get()->getType()->isConstantMatrixType() ||
11092 RHS.get()->getType()->isConstantMatrixType()) {
11093 QualType compType =
11094 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11095 if (CompLHSTy)
11096 *CompLHSTy = compType;
11097 return compType;
11098 }
11099
11100 QualType compType = UsualArithmeticConversions(
11101 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11102 if (LHS.isInvalid() || RHS.isInvalid())
11103 return QualType();
11104
11105 // Enforce type constraints: C99 6.5.6p3.
11106
11107 // Handle the common case first (both operands are arithmetic).
11108 if (!compType.isNull() && compType->isArithmeticType()) {
11109 if (CompLHSTy) *CompLHSTy = compType;
11110 return compType;
11111 }
11112
11113 // Either ptr - int or ptr - ptr.
11114 if (LHS.get()->getType()->isAnyPointerType()) {
11115 QualType lpointee = LHS.get()->getType()->getPointeeType();
11116
11117 // Diagnose bad cases where we step over interface counts.
11118 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11119 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11120 return QualType();
11121
11122 // The result type of a pointer-int computation is the pointer type.
11123 if (RHS.get()->getType()->isIntegerType()) {
11124 // Subtracting from a null pointer should produce a warning.
11125 // The last argument to the diagnose call says this doesn't match the
11126 // GNU int-to-pointer idiom.
11127 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11128 Expr::NPC_ValueDependentIsNotNull)) {
11129 // In C++ adding zero to a null pointer is defined.
11130 Expr::EvalResult KnownVal;
11131 if (!getLangOpts().CPlusPlus ||
11132 (!RHS.get()->isValueDependent() &&
11133 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11134 KnownVal.Val.getInt() != 0))) {
11135 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11136 }
11137 }
11138
11139 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11140 return QualType();
11141
11142 // Check array bounds for pointer arithemtic
11143 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11144 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11145
11146 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11147 return LHS.get()->getType();
11148 }
11149
11150 // Handle pointer-pointer subtractions.
11151 if (const PointerType *RHSPTy
11152 = RHS.get()->getType()->getAs<PointerType>()) {
11153 QualType rpointee = RHSPTy->getPointeeType();
11154
11155 if (getLangOpts().CPlusPlus) {
11156 // Pointee types must be the same: C++ [expr.add]
11157 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11158 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11159 }
11160 } else {
11161 // Pointee types must be compatible C99 6.5.6p3
11162 if (!Context.typesAreCompatible(
11163 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11164 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11165 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11166 return QualType();
11167 }
11168 }
11169
11170 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11171 LHS.get(), RHS.get()))
11172 return QualType();
11173
11174 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11175 Context, Expr::NPC_ValueDependentIsNotNull);
11176 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11177 Context, Expr::NPC_ValueDependentIsNotNull);
11178
11179 // Subtracting nullptr or from nullptr is suspect
11180 if (LHSIsNullPtr)
11181 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11182 if (RHSIsNullPtr)
11183 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11184
11185 // The pointee type may have zero size. As an extension, a structure or
11186 // union may have zero size or an array may have zero length. In this
11187 // case subtraction does not make sense.
11188 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11189 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11190 if (ElementSize.isZero()) {
11191 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11192 << rpointee.getUnqualifiedType()
11193 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11194 }
11195 }
11196
11197 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11198 return Context.getPointerDiffType();
11199 }
11200 }
11201
11202 return InvalidOperands(Loc, LHS, RHS);
11203}
11204
11205static bool isScopedEnumerationType(QualType T) {
11206 if (const EnumType *ET = T->getAs<EnumType>())
11207 return ET->getDecl()->isScoped();
11208 return false;
11209}
11210
11211static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11212 SourceLocation Loc, BinaryOperatorKind Opc,
11213 QualType LHSType) {
11214 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11215 // so skip remaining warnings as we don't want to modify values within Sema.
11216 if (S.getLangOpts().OpenCL)
11217 return;
11218
11219 // Check right/shifter operand
11220 Expr::EvalResult RHSResult;
11221 if (RHS.get()->isValueDependent() ||
11222 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11223 return;
11224 llvm::APSInt Right = RHSResult.Val.getInt();
11225
11226 if (Right.isNegative()) {
11227 S.DiagRuntimeBehavior(Loc, RHS.get(),
11228 S.PDiag(diag::warn_shift_negative)
11229 << RHS.get()->getSourceRange());
11230 return;
11231 }
11232
11233 QualType LHSExprType = LHS.get()->getType();
11234 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11235 if (LHSExprType->isBitIntType())
11236 LeftSize = S.Context.getIntWidth(LHSExprType);
11237 else if (LHSExprType->isFixedPointType()) {
11238 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11239 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11240 }
11241 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11242 if (Right.uge(LeftBits)) {
11243 S.DiagRuntimeBehavior(Loc, RHS.get(),
11244 S.PDiag(diag::warn_shift_gt_typewidth)
11245 << RHS.get()->getSourceRange());
11246 return;
11247 }
11248
11249 // FIXME: We probably need to handle fixed point types specially here.
11250 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11251 return;
11252
11253 // When left shifting an ICE which is signed, we can check for overflow which
11254 // according to C++ standards prior to C++2a has undefined behavior
11255 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11256 // more than the maximum value representable in the result type, so never
11257 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11258 // expression is still probably a bug.)
11259 Expr::EvalResult LHSResult;
11260 if (LHS.get()->isValueDependent() ||
11261 LHSType->hasUnsignedIntegerRepresentation() ||
11262 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11263 return;
11264 llvm::APSInt Left = LHSResult.Val.getInt();
11265
11266 // If LHS does not have a signed type and non-negative value
11267 // then, the behavior is undefined before C++2a. Warn about it.
11268 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
11269 !S.getLangOpts().CPlusPlus20) {
11270 S.DiagRuntimeBehavior(Loc, LHS.get(),
11271 S.PDiag(diag::warn_shift_lhs_negative)
11272 << LHS.get()->getSourceRange());
11273 return;
11274 }
11275
11276 llvm::APInt ResultBits =
11277 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11278 if (LeftBits.uge(ResultBits))
11279 return;
11280 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11281 Result = Result.shl(Right);
11282
11283 // Print the bit representation of the signed integer as an unsigned
11284 // hexadecimal number.
11285 SmallString<40> HexResult;
11286 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11287
11288 // If we are only missing a sign bit, this is less likely to result in actual
11289 // bugs -- if the result is cast back to an unsigned type, it will have the
11290 // expected value. Thus we place this behind a different warning that can be
11291 // turned off separately if needed.
11292 if (LeftBits == ResultBits - 1) {
11293 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11294 << HexResult << LHSType
11295 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11296 return;
11297 }
11298
11299 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11300 << HexResult.str() << Result.getMinSignedBits() << LHSType
11301 << Left.getBitWidth() << LHS.get()->getSourceRange()
11302 << RHS.get()->getSourceRange();
11303}
11304
11305/// Return the resulting type when a vector is shifted
11306/// by a scalar or vector shift amount.
11307static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11308 SourceLocation Loc, bool IsCompAssign) {
11309 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11310 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11311 !LHS.get()->getType()->isVectorType()) {
11312 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11313 << RHS.get()->getType() << LHS.get()->getType()
11314 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11315 return QualType();
11316 }
11317
11318 if (!IsCompAssign) {
11319 LHS = S.UsualUnaryConversions(LHS.get());
11320 if (LHS.isInvalid()) return QualType();
11321 }
11322
11323 RHS = S.UsualUnaryConversions(RHS.get());
11324 if (RHS.isInvalid()) return QualType();
11325
11326 QualType LHSType = LHS.get()->getType();
11327 // Note that LHS might be a scalar because the routine calls not only in
11328 // OpenCL case.
11329 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11330 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11331
11332 // Note that RHS might not be a vector.
11333 QualType RHSType = RHS.get()->getType();
11334 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11335 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11336
11337 // Do not allow shifts for boolean vectors.
11338 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11339 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11340 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11341 << LHS.get()->getType() << RHS.get()->getType()
11342 << LHS.get()->getSourceRange();
11343 return QualType();
11344 }
11345
11346 // The operands need to be integers.
11347 if (!LHSEleType->isIntegerType()) {
11348 S.Diag(Loc, diag::err_typecheck_expect_int)
11349 << LHS.get()->getType() << LHS.get()->getSourceRange();
11350 return QualType();
11351 }
11352
11353 if (!RHSEleType->isIntegerType()) {
11354 S.Diag(Loc, diag::err_typecheck_expect_int)
11355 << RHS.get()->getType() << RHS.get()->getSourceRange();
11356 return QualType();
11357 }
11358
11359 if (!LHSVecTy) {
11360 assert(RHSVecTy)(static_cast <bool> (RHSVecTy) ? void (0) : __assert_fail
("RHSVecTy", "clang/lib/Sema/SemaExpr.cpp", 11360, __extension__
__PRETTY_FUNCTION__))
;
11361 if (IsCompAssign)
11362 return RHSType;
11363 if (LHSEleType != RHSEleType) {
11364 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11365 LHSEleType = RHSEleType;
11366 }
11367 QualType VecTy =
11368 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11369 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11370 LHSType = VecTy;
11371 } else if (RHSVecTy) {
11372 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11373 // are applied component-wise. So if RHS is a vector, then ensure
11374 // that the number of elements is the same as LHS...
11375 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11376 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11377 << LHS.get()->getType() << RHS.get()->getType()
11378 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11379 return QualType();
11380 }
11381 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11382 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11383 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11384 if (LHSBT != RHSBT &&
11385 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11386 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11387 << LHS.get()->getType() << RHS.get()->getType()
11388 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11389 }
11390 }
11391 } else {
11392 // ...else expand RHS to match the number of elements in LHS.
11393 QualType VecTy =
11394 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11395 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11396 }
11397
11398 return LHSType;
11399}
11400
11401// C99 6.5.7
11402QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11403 SourceLocation Loc, BinaryOperatorKind Opc,
11404 bool IsCompAssign) {
11405 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11406
11407 // Vector shifts promote their scalar inputs to vector type.
11408 if (LHS.get()->getType()->isVectorType() ||
11409 RHS.get()->getType()->isVectorType()) {
11410 if (LangOpts.ZVector) {
11411 // The shift operators for the z vector extensions work basically
11412 // like general shifts, except that neither the LHS nor the RHS is
11413 // allowed to be a "vector bool".
11414 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11415 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11416 return InvalidOperands(Loc, LHS, RHS);
11417 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11418 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11419 return InvalidOperands(Loc, LHS, RHS);
11420 }
11421 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11422 }
11423
11424 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11425 RHS.get()->getType()->isVLSTBuiltinType())
11426 return InvalidOperands(Loc, LHS, RHS);
11427
11428 // Shifts don't perform usual arithmetic conversions, they just do integer
11429 // promotions on each operand. C99 6.5.7p3
11430
11431 // For the LHS, do usual unary conversions, but then reset them away
11432 // if this is a compound assignment.
11433 ExprResult OldLHS = LHS;
11434 LHS = UsualUnaryConversions(LHS.get());
11435 if (LHS.isInvalid())
11436 return QualType();
11437 QualType LHSType = LHS.get()->getType();
11438 if (IsCompAssign) LHS = OldLHS;
11439
11440 // The RHS is simpler.
11441 RHS = UsualUnaryConversions(RHS.get());
11442 if (RHS.isInvalid())
11443 return QualType();
11444 QualType RHSType = RHS.get()->getType();
11445
11446 // C99 6.5.7p2: Each of the operands shall have integer type.
11447 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11448 if ((!LHSType->isFixedPointOrIntegerType() &&
11449 !LHSType->hasIntegerRepresentation()) ||
11450 !RHSType->hasIntegerRepresentation())
11451 return InvalidOperands(Loc, LHS, RHS);
11452
11453 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11454 // hasIntegerRepresentation() above instead of this.
11455 if (isScopedEnumerationType(LHSType) ||
11456 isScopedEnumerationType(RHSType)) {
11457 return InvalidOperands(Loc, LHS, RHS);
11458 }
11459 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11460
11461 // "The type of the result is that of the promoted left operand."
11462 return LHSType;
11463}
11464
11465/// Diagnose bad pointer comparisons.
11466static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11467 ExprResult &LHS, ExprResult &RHS,
11468 bool IsError) {
11469 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11470 : diag::ext_typecheck_comparison_of_distinct_pointers)
11471 << LHS.get()->getType() << RHS.get()->getType()
11472 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11473}
11474
11475/// Returns false if the pointers are converted to a composite type,
11476/// true otherwise.
11477static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11478 ExprResult &LHS, ExprResult &RHS) {
11479 // C++ [expr.rel]p2:
11480 // [...] Pointer conversions (4.10) and qualification
11481 // conversions (4.4) are performed on pointer operands (or on
11482 // a pointer operand and a null pointer constant) to bring
11483 // them to their composite pointer type. [...]
11484 //
11485 // C++ [expr.eq]p1 uses the same notion for (in)equality
11486 // comparisons of pointers.
11487
11488 QualType LHSType = LHS.get()->getType();
11489 QualType RHSType = RHS.get()->getType();
11490 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", 11491, __extension__ __PRETTY_FUNCTION__
))
11491 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", 11491, __extension__ __PRETTY_FUNCTION__
))
;
11492
11493 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11494 if (T.isNull()) {
11495 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11496 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11497 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11498 else
11499 S.InvalidOperands(Loc, LHS, RHS);
11500 return true;
11501 }
11502
11503 return false;
11504}
11505
11506static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11507 ExprResult &LHS,
11508 ExprResult &RHS,
11509 bool IsError) {
11510 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11511 : diag::ext_typecheck_comparison_of_fptr_to_void)
11512 << LHS.get()->getType() << RHS.get()->getType()
11513 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11514}
11515
11516static bool isObjCObjectLiteral(ExprResult &E) {
11517 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11518 case Stmt::ObjCArrayLiteralClass:
11519 case Stmt::ObjCDictionaryLiteralClass:
11520 case Stmt::ObjCStringLiteralClass:
11521 case Stmt::ObjCBoxedExprClass:
11522 return true;
11523 default:
11524 // Note that ObjCBoolLiteral is NOT an object literal!
11525 return false;
11526 }
11527}
11528
11529static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11530 const ObjCObjectPointerType *Type =
11531 LHS->getType()->getAs<ObjCObjectPointerType>();
11532
11533 // If this is not actually an Objective-C object, bail out.
11534 if (!Type)
11535 return false;
11536
11537 // Get the LHS object's interface type.
11538 QualType InterfaceType = Type->getPointeeType();
11539
11540 // If the RHS isn't an Objective-C object, bail out.
11541 if (!RHS->getType()->isObjCObjectPointerType())
11542 return false;
11543
11544 // Try to find the -isEqual: method.
11545 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11546 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11547 InterfaceType,
11548 /*IsInstance=*/true);
11549 if (!Method) {
11550 if (Type->isObjCIdType()) {
11551 // For 'id', just check the global pool.
11552 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11553 /*receiverId=*/true);
11554 } else {
11555 // Check protocols.
11556 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11557 /*IsInstance=*/true);
11558 }
11559 }
11560
11561 if (!Method)
11562 return false;
11563
11564 QualType T = Method->parameters()[0]->getType();
11565 if (!T->isObjCObjectPointerType())
11566 return false;
11567
11568 QualType R = Method->getReturnType();
11569 if (!R->isScalarType())
11570 return false;
11571
11572 return true;
11573}
11574
11575Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11576 FromE = FromE->IgnoreParenImpCasts();
11577 switch (FromE->getStmtClass()) {
11578 default:
11579 break;
11580 case Stmt::ObjCStringLiteralClass:
11581 // "string literal"
11582 return LK_String;
11583 case Stmt::ObjCArrayLiteralClass:
11584 // "array literal"
11585 return LK_Array;
11586 case Stmt::ObjCDictionaryLiteralClass:
11587 // "dictionary literal"
11588 return LK_Dictionary;
11589 case Stmt::BlockExprClass:
11590 return LK_Block;
11591 case Stmt::ObjCBoxedExprClass: {
11592 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11593 switch (Inner->getStmtClass()) {
11594 case Stmt::IntegerLiteralClass:
11595 case Stmt::FloatingLiteralClass:
11596 case Stmt::CharacterLiteralClass:
11597 case Stmt::ObjCBoolLiteralExprClass:
11598 case Stmt::CXXBoolLiteralExprClass:
11599 // "numeric literal"
11600 return LK_Numeric;
11601 case Stmt::ImplicitCastExprClass: {
11602 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11603 // Boolean literals can be represented by implicit casts.
11604 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11605 return LK_Numeric;
11606 break;
11607 }
11608 default:
11609 break;
11610 }
11611 return LK_Boxed;
11612 }
11613 }
11614 return LK_None;
11615}
11616
11617static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11618 ExprResult &LHS, ExprResult &RHS,
11619 BinaryOperator::Opcode Opc){
11620 Expr *Literal;
11621 Expr *Other;
11622 if (isObjCObjectLiteral(LHS)) {
11623 Literal = LHS.get();
11624 Other = RHS.get();
11625 } else {
11626 Literal = RHS.get();
11627 Other = LHS.get();
11628 }
11629
11630 // Don't warn on comparisons against nil.
11631 Other = Other->IgnoreParenCasts();
11632 if (Other->isNullPointerConstant(S.getASTContext(),
11633 Expr::NPC_ValueDependentIsNotNull))
11634 return;
11635
11636 // This should be kept in sync with warn_objc_literal_comparison.
11637 // LK_String should always be after the other literals, since it has its own
11638 // warning flag.
11639 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11640 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"
, 11640, __extension__ __PRETTY_FUNCTION__))
;
11641 if (LiteralKind == Sema::LK_None) {
11642 llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind"
, "clang/lib/Sema/SemaExpr.cpp", 11642)
;
11643 }
11644
11645 if (LiteralKind == Sema::LK_String)
11646 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11647 << Literal->getSourceRange();
11648 else
11649 S.Diag(Loc, diag::warn_objc_literal_comparison)
11650 << LiteralKind << Literal->getSourceRange();
11651
11652 if (BinaryOperator::isEqualityOp(Opc) &&
11653 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11654 SourceLocation Start = LHS.get()->getBeginLoc();
11655 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11656 CharSourceRange OpRange =
11657 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11658
11659 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11660 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11661 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11662 << FixItHint::CreateInsertion(End, "]");
11663 }
11664}
11665
11666/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11667static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11668 ExprResult &RHS, SourceLocation Loc,
11669 BinaryOperatorKind Opc) {
11670 // Check that left hand side is !something.
11671 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11672 if (!UO || UO->getOpcode() != UO_LNot) return;
11673
11674 // Only check if the right hand side is non-bool arithmetic type.
11675 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11676
11677 // Make sure that the something in !something is not bool.
11678 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11679 if (SubExpr->isKnownToHaveBooleanValue()) return;
11680
11681 // Emit warning.
11682 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11683 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11684 << Loc << IsBitwiseOp;
11685
11686 // First note suggest !(x < y)
11687 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11688 SourceLocation FirstClose = RHS.get()->getEndLoc();
11689 FirstClose = S.getLocForEndOfToken(FirstClose);
11690 if (FirstClose.isInvalid())
11691 FirstOpen = SourceLocation();
11692 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11693 << IsBitwiseOp
11694 << FixItHint::CreateInsertion(FirstOpen, "(")
11695 << FixItHint::CreateInsertion(FirstClose, ")");
11696
11697 // Second note suggests (!x) < y
11698 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11699 SourceLocation SecondClose = LHS.get()->getEndLoc();
11700 SecondClose = S.getLocForEndOfToken(SecondClose);
11701 if (SecondClose.isInvalid())
11702 SecondOpen = SourceLocation();
11703 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11704 << FixItHint::CreateInsertion(SecondOpen, "(")
11705 << FixItHint::CreateInsertion(SecondClose, ")");
11706}
11707
11708// Returns true if E refers to a non-weak array.
11709static bool checkForArray(const Expr *E) {
11710 const ValueDecl *D = nullptr;
11711 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11712 D = DR->getDecl();
11713 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11714 if (Mem->isImplicitAccess())
11715 D = Mem->getMemberDecl();
11716 }
11717 if (!D)
11718 return false;
11719 return D->getType()->isArrayType() && !D->isWeak();
11720}
11721
11722/// Diagnose some forms of syntactically-obvious tautological comparison.
11723static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11724 Expr *LHS, Expr *RHS,
11725 BinaryOperatorKind Opc) {
11726 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11727 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11728
11729 QualType LHSType = LHS->getType();
11730 QualType RHSType = RHS->getType();
11731 if (LHSType->hasFloatingRepresentation() ||
11732 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11733 S.inTemplateInstantiation())
11734 return;
11735
11736 // Comparisons between two array types are ill-formed for operator<=>, so
11737 // we shouldn't emit any additional warnings about it.
11738 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11739 return;
11740
11741 // For non-floating point types, check for self-comparisons of the form
11742 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11743 // often indicate logic errors in the program.
11744 //
11745 // NOTE: Don't warn about comparison expressions resulting from macro
11746 // expansion. Also don't warn about comparisons which are only self
11747 // comparisons within a template instantiation. The warnings should catch
11748 // obvious cases in the definition of the template anyways. The idea is to
11749 // warn when the typed comparison operator will always evaluate to the same
11750 // result.
11751
11752 // Used for indexing into %select in warn_comparison_always
11753 enum {
11754 AlwaysConstant,
11755 AlwaysTrue,
11756 AlwaysFalse,
11757 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11758 };
11759
11760 // C++2a [depr.array.comp]:
11761 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11762 // operands of array type are deprecated.
11763 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11764 RHSStripped->getType()->isArrayType()) {
11765 S.Diag(Loc, diag::warn_depr_array_comparison)
11766 << LHS->getSourceRange() << RHS->getSourceRange()
11767 << LHSStripped->getType() << RHSStripped->getType();
11768 // Carry on to produce the tautological comparison warning, if this
11769 // expression is potentially-evaluated, we can resolve the array to a
11770 // non-weak declaration, and so on.
11771 }
11772
11773 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11774 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11775 unsigned Result;
11776 switch (Opc) {
11777 case BO_EQ:
11778 case BO_LE:
11779 case BO_GE:
11780 Result = AlwaysTrue;
11781 break;
11782 case BO_NE:
11783 case BO_LT:
11784 case BO_GT:
11785 Result = AlwaysFalse;
11786 break;
11787 case BO_Cmp:
11788 Result = AlwaysEqual;
11789 break;
11790 default:
11791 Result = AlwaysConstant;
11792 break;
11793 }
11794 S.DiagRuntimeBehavior(Loc, nullptr,
11795 S.PDiag(diag::warn_comparison_always)
11796 << 0 /*self-comparison*/
11797 << Result);
11798 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11799 // What is it always going to evaluate to?
11800 unsigned Result;
11801 switch (Opc) {
11802 case BO_EQ: // e.g. array1 == array2
11803 Result = AlwaysFalse;
11804 break;
11805 case BO_NE: // e.g. array1 != array2
11806 Result = AlwaysTrue;
11807 break;
11808 default: // e.g. array1 <= array2
11809 // The best we can say is 'a constant'
11810 Result = AlwaysConstant;
11811 break;
11812 }
11813 S.DiagRuntimeBehavior(Loc, nullptr,
11814 S.PDiag(diag::warn_comparison_always)
11815 << 1 /*array comparison*/
11816 << Result);
11817 }
11818 }
11819
11820 if (isa<CastExpr>(LHSStripped))
11821 LHSStripped = LHSStripped->IgnoreParenCasts();
11822 if (isa<CastExpr>(RHSStripped))
11823 RHSStripped = RHSStripped->IgnoreParenCasts();
11824
11825 // Warn about comparisons against a string constant (unless the other
11826 // operand is null); the user probably wants string comparison function.
11827 Expr *LiteralString = nullptr;
11828 Expr *LiteralStringStripped = nullptr;
11829 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11830 !RHSStripped->isNullPointerConstant(S.Context,
11831 Expr::NPC_ValueDependentIsNull)) {
11832 LiteralString = LHS;
11833 LiteralStringStripped = LHSStripped;
11834 } else if ((isa<StringLiteral>(RHSStripped) ||
11835 isa<ObjCEncodeExpr>(RHSStripped)) &&
11836 !LHSStripped->isNullPointerConstant(S.Context,
11837 Expr::NPC_ValueDependentIsNull)) {
11838 LiteralString = RHS;
11839 LiteralStringStripped = RHSStripped;
11840 }
11841
11842 if (LiteralString) {
11843 S.DiagRuntimeBehavior(Loc, nullptr,
11844 S.PDiag(diag::warn_stringcompare)
11845 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11846 << LiteralString->getSourceRange());
11847 }
11848}
11849
11850static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11851 switch (CK) {
11852 default: {
11853#ifndef NDEBUG
11854 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11855 << "\n";
11856#endif
11857 llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "clang/lib/Sema/SemaExpr.cpp"
, 11857)
;
11858 }
11859 case CK_UserDefinedConversion:
11860 return ICK_Identity;
11861 case CK_LValueToRValue:
11862 return ICK_Lvalue_To_Rvalue;
11863 case CK_ArrayToPointerDecay:
11864 return ICK_Array_To_Pointer;
11865 case CK_FunctionToPointerDecay:
11866 return ICK_Function_To_Pointer;
11867 case CK_IntegralCast:
11868 return ICK_Integral_Conversion;
11869 case CK_FloatingCast:
11870 return ICK_Floating_Conversion;
11871 case CK_IntegralToFloating:
11872 case CK_FloatingToIntegral:
11873 return ICK_Floating_Integral;
11874 case CK_IntegralComplexCast:
11875 case CK_FloatingComplexCast:
11876 case CK_FloatingComplexToIntegralComplex:
11877 case CK_IntegralComplexToFloatingComplex:
11878 return ICK_Complex_Conversion;
11879 case CK_FloatingComplexToReal:
11880 case CK_FloatingRealToComplex:
11881 case CK_IntegralComplexToReal:
11882 case CK_IntegralRealToComplex:
11883 return ICK_Complex_Real;
11884 }
11885}
11886
11887static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11888 QualType FromType,
11889 SourceLocation Loc) {
11890 // Check for a narrowing implicit conversion.
11891 StandardConversionSequence SCS;
11892 SCS.setAsIdentityConversion();
11893 SCS.setToType(0, FromType);
11894 SCS.setToType(1, ToType);
11895 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11896 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11897
11898 APValue PreNarrowingValue;
11899 QualType PreNarrowingType;
11900 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11901 PreNarrowingType,
11902 /*IgnoreFloatToIntegralConversion*/ true)) {
11903 case NK_Dependent_Narrowing:
11904 // Implicit conversion to a narrower type, but the expression is
11905 // value-dependent so we can't tell whether it's actually narrowing.
11906 case NK_Not_Narrowing:
11907 return false;
11908
11909 case NK_Constant_Narrowing:
11910 // Implicit conversion to a narrower type, and the value is not a constant
11911 // expression.
11912 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11913 << /*Constant*/ 1
11914 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11915 return true;
11916
11917 case NK_Variable_Narrowing:
11918 // Implicit conversion to a narrower type, and the value is not a constant
11919 // expression.
11920 case NK_Type_Narrowing:
11921 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11922 << /*Constant*/ 0 << FromType << ToType;
11923 // TODO: It's not a constant expression, but what if the user intended it
11924 // to be? Can we produce notes to help them figure out why it isn't?
11925 return true;
11926 }
11927 llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch",
"clang/lib/Sema/SemaExpr.cpp", 11927)
;
11928}
11929
11930static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11931 ExprResult &LHS,
11932 ExprResult &RHS,
11933 SourceLocation Loc) {
11934 QualType LHSType = LHS.get()->getType();
11935 QualType RHSType = RHS.get()->getType();
11936 // Dig out the original argument type and expression before implicit casts
11937 // were applied. These are the types/expressions we need to check the
11938 // [expr.spaceship] requirements against.
11939 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11940 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11941 QualType LHSStrippedType = LHSStripped.get()->getType();
11942 QualType RHSStrippedType = RHSStripped.get()->getType();
11943
11944 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11945 // other is not, the program is ill-formed.
11946 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11947 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11948 return QualType();
11949 }
11950
11951 // FIXME: Consider combining this with checkEnumArithmeticConversions.
11952 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11953 RHSStrippedType->isEnumeralType();
11954 if (NumEnumArgs == 1) {
11955 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11956 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11957 if (OtherTy->hasFloatingRepresentation()) {
11958 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11959 return QualType();
11960 }
11961 }
11962 if (NumEnumArgs == 2) {
11963 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11964 // type E, the operator yields the result of converting the operands
11965 // to the underlying type of E and applying <=> to the converted operands.
11966 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11967 S.InvalidOperands(Loc, LHS, RHS);
11968 return QualType();
11969 }
11970 QualType IntType =
11971 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11972 assert(IntType->isArithmeticType())(static_cast <bool> (IntType->isArithmeticType()) ? void
(0) : __assert_fail ("IntType->isArithmeticType()", "clang/lib/Sema/SemaExpr.cpp"
, 11972, __extension__ __PRETTY_FUNCTION__))
;
11973
11974 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11975 // promote the boolean type, and all other promotable integer types, to
11976 // avoid this.
11977 if (IntType->isPromotableIntegerType())
11978 IntType = S.Context.getPromotedIntegerType(IntType);
11979
11980 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11981 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11982 LHSType = RHSType = IntType;
11983 }
11984
11985 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11986 // usual arithmetic conversions are applied to the operands.
11987 QualType Type =
11988 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11989 if (LHS.isInvalid() || RHS.isInvalid())
11990 return QualType();
11991 if (Type.isNull())
11992 return S.InvalidOperands(Loc, LHS, RHS);
11993
11994 Optional<ComparisonCategoryType> CCT =
11995 getComparisonCategoryForBuiltinCmp(Type);
11996 if (!CCT)
11997 return S.InvalidOperands(Loc, LHS, RHS);
11998
11999 bool HasNarrowing = checkThreeWayNarrowingConversion(
12000 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12001 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12002 RHS.get()->getBeginLoc());
12003 if (HasNarrowing)
12004 return QualType();
12005
12006 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", 12006, __extension__ __PRETTY_FUNCTION__
))
;
12007
12008 return S.CheckComparisonCategoryType(
12009 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12010}
12011
12012static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12013 ExprResult &RHS,
12014 SourceLocation Loc,
12015 BinaryOperatorKind Opc) {
12016 if (Opc == BO_Cmp)
12017 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12018
12019 // C99 6.5.8p3 / C99 6.5.9p4
12020 QualType Type =
12021 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12022 if (LHS.isInvalid() || RHS.isInvalid())
12023 return QualType();
12024 if (Type.isNull())
12025 return S.InvalidOperands(Loc, LHS, RHS);
12026 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", 12026, __extension__ __PRETTY_FUNCTION__
))
;
12027
12028 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12029 return S.InvalidOperands(Loc, LHS, RHS);
12030
12031 // Check for comparisons of floating point operands using != and ==.
12032 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
12033 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12034
12035 // The result of comparisons is 'bool' in C++, 'int' in C.
12036 return S.Context.getLogicalOperationType();
12037}
12038
12039void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12040 if (!NullE.get()->getType()->isAnyPointerType())
12041 return;
12042 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12043 if (!E.get()->getType()->isAnyPointerType() &&
12044 E.get()->isNullPointerConstant(Context,
12045 Expr::NPC_ValueDependentIsNotNull) ==
12046 Expr::NPCK_ZeroExpression) {
12047 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12048 if (CL->getValue() == 0)
12049 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12050 << NullValue
12051 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12052 NullValue ? "NULL" : "(void *)0");
12053 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12054 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12055 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12056 if (T == Context.CharTy)
12057 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12058 << NullValue
12059 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12060 NullValue ? "NULL" : "(void *)0");
12061 }
12062 }
12063}
12064
12065// C99 6.5.8, C++ [expr.rel]
12066QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12067 SourceLocation Loc,
12068 BinaryOperatorKind Opc) {
12069 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12070 bool IsThreeWay = Opc == BO_Cmp;
12071 bool IsOrdered = IsRelational || IsThreeWay;
12072 auto IsAnyPointerType = [](ExprResult E) {
12073 QualType Ty = E.get()->getType();
12074 return Ty->isPointerType() || Ty->isMemberPointerType();
12075 };
12076
12077 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12078 // type, array-to-pointer, ..., conversions are performed on both operands to
12079 // bring them to their composite type.
12080 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12081 // any type-related checks.
12082 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12083 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12084 if (LHS.isInvalid())
12085 return QualType();
12086 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12087 if (RHS.isInvalid())
12088 return QualType();
12089 } else {
12090 LHS = DefaultLvalueConversion(LHS.get());
12091 if (LHS.isInvalid())
12092 return QualType();
12093 RHS = DefaultLvalueConversion(RHS.get());
12094 if (RHS.isInvalid())
12095 return QualType();
12096 }
12097
12098 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12099 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12100 CheckPtrComparisonWithNullChar(LHS, RHS);
12101 CheckPtrComparisonWithNullChar(RHS, LHS);
12102 }
12103
12104 // Handle vector comparisons separately.
12105 if (LHS.get()->getType()->isVectorType() ||
12106 RHS.get()->getType()->isVectorType())
12107 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12108
12109 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12110 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12111
12112 QualType LHSType = LHS.get()->getType();
12113 QualType RHSType = RHS.get()->getType();
12114 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12115 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12116 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12117
12118 const Expr::NullPointerConstantKind LHSNullKind =
12119 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12120 const Expr::NullPointerConstantKind RHSNullKind =
12121 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12122 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12123 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12124
12125 auto computeResultTy = [&]() {
12126 if (Opc != BO_Cmp)
12127 return Context.getLogicalOperationType();
12128 assert(getLangOpts().CPlusPlus)(static_cast <bool> (getLangOpts().CPlusPlus) ? void (0
) : __assert_fail ("getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 12128, __extension__ __PRETTY_FUNCTION__))
;
12129 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", 12129, __extension__ __PRETTY_FUNCTION__
))
;
12130
12131 QualType CompositeTy = LHS.get()->getType();
12132 assert(!CompositeTy->isReferenceType())(static_cast <bool> (!CompositeTy->isReferenceType()
) ? void (0) : __assert_fail ("!CompositeTy->isReferenceType()"
, "clang/lib/Sema/SemaExpr.cpp", 12132, __extension__ __PRETTY_FUNCTION__
))
;
12133
12134 Optional<ComparisonCategoryType> CCT =
12135 getComparisonCategoryForBuiltinCmp(CompositeTy);
12136 if (!CCT)
12137 return InvalidOperands(Loc, LHS, RHS);
12138
12139 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12140 // P0946R0: Comparisons between a null pointer constant and an object
12141 // pointer result in std::strong_equality, which is ill-formed under
12142 // P1959R0.
12143 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12144 << (LHSIsNull ? LHS.get()->getSourceRange()
12145 : RHS.get()->getSourceRange());
12146 return QualType();
12147 }
12148
12149 return CheckComparisonCategoryType(
12150 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12151 };
12152
12153 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12154 bool IsEquality = Opc == BO_EQ;
12155 if (RHSIsNull)
12156 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12157 RHS.get()->getSourceRange());
12158 else
12159 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12160 LHS.get()->getSourceRange());
12161 }
12162
12163 if (IsOrdered && LHSType->isFunctionPointerType() &&
12164 RHSType->isFunctionPointerType()) {
12165 // Valid unless a relational comparison of function pointers
12166 bool IsError = Opc == BO_Cmp;
12167 auto DiagID =
12168 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12169 : getLangOpts().CPlusPlus
12170 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12171 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12172 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12173 << RHS.get()->getSourceRange();
12174 if (IsError)
12175 return QualType();
12176 }
12177
12178 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12179 (RHSType->isIntegerType() && !RHSIsNull)) {
12180 // Skip normal pointer conversion checks in this case; we have better
12181 // diagnostics for this below.
12182 } else if (getLangOpts().CPlusPlus) {
12183 // Equality comparison of a function pointer to a void pointer is invalid,
12184 // but we allow it as an extension.
12185 // FIXME: If we really want to allow this, should it be part of composite
12186 // pointer type computation so it works in conditionals too?
12187 if (!IsOrdered &&
12188 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12189 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12190 // This is a gcc extension compatibility comparison.
12191 // In a SFINAE context, we treat this as a hard error to maintain
12192 // conformance with the C++ standard.
12193 diagnoseFunctionPointerToVoidComparison(
12194 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12195
12196 if (isSFINAEContext())
12197 return QualType();
12198
12199 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12200 return computeResultTy();
12201 }
12202
12203 // C++ [expr.eq]p2:
12204 // If at least one operand is a pointer [...] bring them to their
12205 // composite pointer type.
12206 // C++ [expr.spaceship]p6
12207 // If at least one of the operands is of pointer type, [...] bring them
12208 // to their composite pointer type.
12209 // C++ [expr.rel]p2:
12210 // If both operands are pointers, [...] bring them to their composite
12211 // pointer type.
12212 // For <=>, the only valid non-pointer types are arrays and functions, and
12213 // we already decayed those, so this is really the same as the relational
12214 // comparison rule.
12215 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12216 (IsOrdered ? 2 : 1) &&
12217 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12218 RHSType->isObjCObjectPointerType()))) {
12219 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12220 return QualType();
12221 return computeResultTy();
12222 }
12223 } else if (LHSType->isPointerType() &&
12224 RHSType->isPointerType()) { // C99 6.5.8p2
12225 // All of the following pointer-related warnings are GCC extensions, except
12226 // when handling null pointer constants.
12227 QualType LCanPointeeTy =
12228 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12229 QualType RCanPointeeTy =
12230 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12231
12232 // C99 6.5.9p2 and C99 6.5.8p2
12233 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12234 RCanPointeeTy.getUnqualifiedType())) {
12235 if (IsRelational) {
12236 // Pointers both need to point to complete or incomplete types
12237 if ((LCanPointeeTy->isIncompleteType() !=
12238 RCanPointeeTy->isIncompleteType()) &&
12239 !getLangOpts().C11) {
12240 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12241 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12242 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12243 << RCanPointeeTy->isIncompleteType();
12244 }
12245 }
12246 } else if (!IsRelational &&
12247 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12248 // Valid unless comparison between non-null pointer and function pointer
12249 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12250 && !LHSIsNull && !RHSIsNull)
12251 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12252 /*isError*/false);
12253 } else {
12254 // Invalid
12255 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12256 }
12257 if (LCanPointeeTy != RCanPointeeTy) {
12258 // Treat NULL constant as a special case in OpenCL.
12259 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12260 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12261 Diag(Loc,
12262 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12263 << LHSType << RHSType << 0 /* comparison */
12264 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12265 }
12266 }
12267 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12268 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12269 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12270 : CK_BitCast;
12271 if (LHSIsNull && !RHSIsNull)
12272 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12273 else
12274 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12275 }
12276 return computeResultTy();
12277 }
12278
12279 if (getLangOpts().CPlusPlus) {
12280 // C++ [expr.eq]p4:
12281 // Two operands of type std::nullptr_t or one operand of type
12282 // std::nullptr_t and the other a null pointer constant compare equal.
12283 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12284 if (LHSType->isNullPtrType()) {
12285 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12286 return computeResultTy();
12287 }
12288 if (RHSType->isNullPtrType()) {
12289 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12290 return computeResultTy();
12291 }
12292 }
12293
12294 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12295 // These aren't covered by the composite pointer type rules.
12296 if (!IsOrdered && RHSType->isNullPtrType() &&
12297 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12298 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12299 return computeResultTy();
12300 }
12301 if (!IsOrdered && LHSType->isNullPtrType() &&
12302 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12303 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12304 return computeResultTy();
12305 }
12306
12307 if (IsRelational &&
12308 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12309 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12310 // HACK: Relational comparison of nullptr_t against a pointer type is
12311 // invalid per DR583, but we allow it within std::less<> and friends,
12312 // since otherwise common uses of it break.
12313 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12314 // friends to have std::nullptr_t overload candidates.
12315 DeclContext *DC = CurContext;
12316 if (isa<FunctionDecl>(DC))
12317 DC = DC->getParent();
12318 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12319 if (CTSD->isInStdNamespace() &&
12320 llvm::StringSwitch<bool>(CTSD->getName())
12321 .Cases("less", "less_equal", "greater", "greater_equal", true)
12322 .Default(false)) {
12323 if (RHSType->isNullPtrType())
12324 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12325 else
12326 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12327 return computeResultTy();
12328 }
12329 }
12330 }
12331
12332 // C++ [expr.eq]p2:
12333 // If at least one operand is a pointer to member, [...] bring them to
12334 // their composite pointer type.
12335 if (!IsOrdered &&
12336 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12337 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12338 return QualType();
12339 else
12340 return computeResultTy();
12341 }
12342 }
12343
12344 // Handle block pointer types.
12345 if (!IsOrdered && LHSType->isBlockPointerType() &&
12346 RHSType->isBlockPointerType()) {
12347 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12348 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12349
12350 if (!LHSIsNull && !RHSIsNull &&
12351 !Context.typesAreCompatible(lpointee, rpointee)) {
12352 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12353 << LHSType << RHSType << LHS.get()->getSourceRange()
12354 << RHS.get()->getSourceRange();
12355 }
12356 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12357 return computeResultTy();
12358 }
12359
12360 // Allow block pointers to be compared with null pointer constants.
12361 if (!IsOrdered
12362 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12363 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12364 if (!LHSIsNull && !RHSIsNull) {
12365 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12366 ->getPointeeType()->isVoidType())
12367 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12368 ->getPointeeType()->isVoidType())))
12369 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12370 << LHSType << RHSType << LHS.get()->getSourceRange()
12371 << RHS.get()->getSourceRange();
12372 }
12373 if (LHSIsNull && !RHSIsNull)
12374 LHS = ImpCastExprToType(LHS.get(), RHSType,
12375 RHSType->isPointerType() ? CK_BitCast
12376 : CK_AnyPointerToBlockPointerCast);
12377 else
12378 RHS = ImpCastExprToType(RHS.get(), LHSType,
12379 LHSType->isPointerType() ? CK_BitCast
12380 : CK_AnyPointerToBlockPointerCast);
12381 return computeResultTy();
12382 }
12383
12384 if (LHSType->isObjCObjectPointerType() ||
12385 RHSType->isObjCObjectPointerType()) {
12386 const PointerType *LPT = LHSType->getAs<PointerType>();
12387 const PointerType *RPT = RHSType->getAs<PointerType>();
12388 if (LPT || RPT) {
12389 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12390 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12391
12392 if (!LPtrToVoid && !RPtrToVoid &&
12393 !Context.typesAreCompatible(LHSType, RHSType)) {
12394 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12395 /*isError*/false);
12396 }
12397 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12398 // the RHS, but we have test coverage for this behavior.
12399 // FIXME: Consider using convertPointersToCompositeType in C++.
12400 if (LHSIsNull && !RHSIsNull) {
12401 Expr *E = LHS.get();
12402 if (getLangOpts().ObjCAutoRefCount)
12403 CheckObjCConversion(SourceRange(), RHSType, E,
12404 CCK_ImplicitConversion);
12405 LHS = ImpCastExprToType(E, RHSType,
12406 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12407 }
12408 else {
12409 Expr *E = RHS.get();
12410 if (getLangOpts().ObjCAutoRefCount)
12411 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12412 /*Diagnose=*/true,
12413 /*DiagnoseCFAudited=*/false, Opc);
12414 RHS = ImpCastExprToType(E, LHSType,
12415 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12416 }
12417 return computeResultTy();
12418 }
12419 if (LHSType->isObjCObjectPointerType() &&
12420 RHSType->isObjCObjectPointerType()) {
12421 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12422 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12423 /*isError*/false);
12424 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12425 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12426
12427 if (LHSIsNull && !RHSIsNull)
12428 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12429 else
12430 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12431 return computeResultTy();
12432 }
12433
12434 if (!IsOrdered && LHSType->isBlockPointerType() &&
12435 RHSType->isBlockCompatibleObjCPointerType(Context)) {
12436 LHS = ImpCastExprToType(LHS.get(), RHSType,
12437 CK_BlockPointerToObjCPointerCast);
12438 return computeResultTy();
12439 } else if (!IsOrdered &&
12440 LHSType->isBlockCompatibleObjCPointerType(Context) &&
12441 RHSType->isBlockPointerType()) {
12442 RHS = ImpCastExprToType(RHS.get(), LHSType,
12443 CK_BlockPointerToObjCPointerCast);
12444 return computeResultTy();
12445 }
12446 }
12447 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12448 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12449 unsigned DiagID = 0;
12450 bool isError = false;
12451 if (LangOpts.DebuggerSupport) {
12452 // Under a debugger, allow the comparison of pointers to integers,
12453 // since users tend to want to compare addresses.
12454 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12455 (RHSIsNull && RHSType->isIntegerType())) {
12456 if (IsOrdered) {
12457 isError = getLangOpts().CPlusPlus;
12458 DiagID =
12459 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12460 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12461 }
12462 } else if (getLangOpts().CPlusPlus) {
12463 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12464 isError = true;
12465 } else if (IsOrdered)
12466 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12467 else
12468 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12469
12470 if (DiagID) {
12471 Diag(Loc, DiagID)
12472 << LHSType << RHSType << LHS.get()->getSourceRange()
12473 << RHS.get()->getSourceRange();
12474 if (isError)
12475 return QualType();
12476 }
12477
12478 if (LHSType->isIntegerType())
12479 LHS = ImpCastExprToType(LHS.get(), RHSType,
12480 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12481 else
12482 RHS = ImpCastExprToType(RHS.get(), LHSType,
12483 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12484 return computeResultTy();
12485 }
12486
12487 // Handle block pointers.
12488 if (!IsOrdered && RHSIsNull
12489 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12490 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12491 return computeResultTy();
12492 }
12493 if (!IsOrdered && LHSIsNull
12494 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12495 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12496 return computeResultTy();
12497 }
12498
12499 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12500 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12501 return computeResultTy();
12502 }
12503
12504 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12505 return computeResultTy();
12506 }
12507
12508 if (LHSIsNull && RHSType->isQueueT()) {
12509 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12510 return computeResultTy();
12511 }
12512
12513 if (LHSType->isQueueT() && RHSIsNull) {
12514 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12515 return computeResultTy();
12516 }
12517 }
12518
12519 return InvalidOperands(Loc, LHS, RHS);
12520}
12521
12522// Return a signed ext_vector_type that is of identical size and number of
12523// elements. For floating point vectors, return an integer type of identical
12524// size and number of elements. In the non ext_vector_type case, search from
12525// the largest type to the smallest type to avoid cases where long long == long,
12526// where long gets picked over long long.
12527QualType Sema::GetSignedVectorType(QualType V) {
12528 const VectorType *VTy = V->castAs<VectorType>();
12529 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12530
12531 if (isa<ExtVectorType>(VTy)) {
12532 if (VTy->isExtVectorBoolType())
12533 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
12534 if (TypeSize == Context.getTypeSize(Context.CharTy))
12535 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12536 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12537 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12538 if (TypeSize == Context.getTypeSize(Context.IntTy))
12539 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12540 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12541 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12542 if (TypeSize == Context.getTypeSize(Context.LongTy))
12543 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12544 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", 12545, __extension__ __PRETTY_FUNCTION__
))
12545 "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", 12545, __extension__ __PRETTY_FUNCTION__
))
;
12546 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12547 }
12548
12549 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12550 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12551 VectorType::GenericVector);
12552 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12553 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12554 VectorType::GenericVector);
12555 if (TypeSize == Context.getTypeSize(Context.LongTy))
12556 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12557 VectorType::GenericVector);
12558 if (TypeSize == Context.getTypeSize(Context.IntTy))
12559 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12560 VectorType::GenericVector);
12561 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12562 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12563 VectorType::GenericVector);
12564 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", 12565, __extension__ __PRETTY_FUNCTION__
))
12565 "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", 12565, __extension__ __PRETTY_FUNCTION__
))
;
12566 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12567 VectorType::GenericVector);
12568}
12569
12570/// CheckVectorCompareOperands - vector comparisons are a clang extension that
12571/// operates on extended vector types. Instead of producing an IntTy result,
12572/// like a scalar comparison, a vector comparison produces a vector of integer
12573/// types.
12574QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12575 SourceLocation Loc,
12576 BinaryOperatorKind Opc) {
12577 if (Opc == BO_Cmp) {
12578 Diag(Loc, diag::err_three_way_vector_comparison);
12579 return QualType();
12580 }
12581
12582 // Check to make sure we're operating on vectors of the same type and width,
12583 // Allowing one side to be a scalar of element type.
12584 QualType vType =
12585 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12586 /*AllowBothBool*/ true,
12587 /*AllowBoolConversions*/ getLangOpts().ZVector,
12588 /*AllowBooleanOperation*/ true,
12589 /*ReportInvalid*/ true);
12590 if (vType.isNull())
12591 return vType;
12592
12593 QualType LHSType = LHS.get()->getType();
12594
12595 // Determine the return type of a vector compare. By default clang will return
12596 // a scalar for all vector compares except vector bool and vector pixel.
12597 // With the gcc compiler we will always return a vector type and with the xl
12598 // compiler we will always return a scalar type. This switch allows choosing
12599 // which behavior is prefered.
12600 if (getLangOpts().AltiVec) {
12601 switch (getLangOpts().getAltivecSrcCompat()) {
12602 case LangOptions::AltivecSrcCompatKind::Mixed:
12603 // If AltiVec, the comparison results in a numeric type, i.e.
12604 // bool for C++, int for C
12605 if (vType->castAs<VectorType>()->getVectorKind() ==
12606 VectorType::AltiVecVector)
12607 return Context.getLogicalOperationType();
12608 else
12609 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12610 break;
12611 case LangOptions::AltivecSrcCompatKind::GCC:
12612 // For GCC we always return the vector type.
12613 break;
12614 case LangOptions::AltivecSrcCompatKind::XL:
12615 return Context.getLogicalOperationType();
12616 break;
12617 }
12618 }
12619
12620 // For non-floating point types, check for self-comparisons of the form
12621 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12622 // often indicate logic errors in the program.
12623 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12624
12625 // Check for comparisons of floating point operands using != and ==.
12626 if (BinaryOperator::isEqualityOp(Opc) &&
12627 LHSType->hasFloatingRepresentation()) {
12628 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", 12628, __extension__ __PRETTY_FUNCTION__
))
;
12629 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12630 }
12631
12632 // Return a signed type for the vector.
12633 return GetSignedVectorType(vType);
12634}
12635
12636static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12637 const ExprResult &XorRHS,
12638 const SourceLocation Loc) {
12639 // Do not diagnose macros.
12640 if (Loc.isMacroID())
12641 return;
12642
12643 // Do not diagnose if both LHS and RHS are macros.
12644 if (XorLHS.get()->getExprLoc().isMacroID() &&
12645 XorRHS.get()->getExprLoc().isMacroID())
12646 return;
12647
12648 bool Negative = false;
12649 bool ExplicitPlus = false;
12650 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12651 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12652
12653 if (!LHSInt)
12654 return;
12655 if (!RHSInt) {
12656 // Check negative literals.
12657 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12658 UnaryOperatorKind Opc = UO->getOpcode();
12659 if (Opc != UO_Minus && Opc != UO_Plus)
12660 return;
12661 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12662 if (!RHSInt)
12663 return;
12664 Negative = (Opc == UO_Minus);
12665 ExplicitPlus = !Negative;
12666 } else {
12667 return;
12668 }
12669 }
12670
12671 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12672 llvm::APInt RightSideValue = RHSInt->getValue();
12673 if (LeftSideValue != 2 && LeftSideValue != 10)
12674 return;
12675
12676 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12677 return;
12678
12679 CharSourceRange ExprRange = CharSourceRange::getCharRange(
12680 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12681 llvm::StringRef ExprStr =
12682 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12683
12684 CharSourceRange XorRange =
12685 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12686 llvm::StringRef XorStr =
12687 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12688 // Do not diagnose if xor keyword/macro is used.
12689 if (XorStr == "xor")
12690 return;
12691
12692 std::string LHSStr = std::string(Lexer::getSourceText(
12693 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12694 S.getSourceManager(), S.getLangOpts()));
12695 std::string RHSStr = std::string(Lexer::getSourceText(
12696 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12697 S.getSourceManager(), S.getLangOpts()));
12698
12699 if (Negative) {
12700 RightSideValue = -RightSideValue;
12701 RHSStr = "-" + RHSStr;
12702 } else if (ExplicitPlus) {
12703 RHSStr = "+" + RHSStr;
12704 }
12705
12706 StringRef LHSStrRef = LHSStr;
12707 StringRef RHSStrRef = RHSStr;
12708 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12709 // literals.
12710 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12711 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12712 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12713 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12714 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12715 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12716 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12717 return;
12718
12719 bool SuggestXor =
12720 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12721 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12722 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12723 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12724 std::string SuggestedExpr = "1 << " + RHSStr;
12725 bool Overflow = false;
12726 llvm::APInt One = (LeftSideValue - 1);
12727 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12728 if (Overflow) {
12729 if (RightSideIntValue < 64)
12730 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12731 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12732 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12733 else if (RightSideIntValue == 64)
12734 S.Diag(Loc, diag::warn_xor_used_as_pow)
12735 << ExprStr << toString(XorValue, 10, true);
12736 else
12737 return;
12738 } else {
12739 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12740 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12741 << toString(PowValue, 10, true)
12742 << FixItHint::CreateReplacement(
12743 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12744 }
12745
12746 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12747 << ("0x2 ^ " + RHSStr) << SuggestXor;
12748 } else if (LeftSideValue == 10) {
12749 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12750 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12751 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12752 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12753 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12754 << ("0xA ^ " + RHSStr) << SuggestXor;
12755 }
12756}
12757
12758QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12759 SourceLocation Loc) {
12760 // Ensure that either both operands are of the same vector type, or
12761 // one operand is of a vector type and the other is of its element type.
12762 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12763 /*AllowBothBool*/ true,
12764 /*AllowBoolConversions*/ false,
12765 /*AllowBooleanOperation*/ false,
12766 /*ReportInvalid*/ false);
12767 if (vType.isNull())
12768 return InvalidOperands(Loc, LHS, RHS);
12769 if (getLangOpts().OpenCL &&
12770 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12771 vType->hasFloatingRepresentation())
12772 return InvalidOperands(Loc, LHS, RHS);
12773 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12774 // usage of the logical operators && and || with vectors in C. This
12775 // check could be notionally dropped.
12776 if (!getLangOpts().CPlusPlus &&
12777 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12778 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12779
12780 return GetSignedVectorType(LHS.get()->getType());
12781}
12782
12783QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12784 SourceLocation Loc,
12785 bool IsCompAssign) {
12786 if (!IsCompAssign) {
12787 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12788 if (LHS.isInvalid())
12789 return QualType();
12790 }
12791 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12792 if (RHS.isInvalid())
12793 return QualType();
12794
12795 // For conversion purposes, we ignore any qualifiers.
12796 // For example, "const float" and "float" are equivalent.
12797 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12798 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12799
12800 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12801 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12802 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", 12802, __extension__ __PRETTY_FUNCTION__
))
;
12803
12804 if (Context.hasSameType(LHSType, RHSType))
12805 return LHSType;
12806
12807 // Type conversion may change LHS/RHS. Keep copies to the original results, in
12808 // case we have to return InvalidOperands.
12809 ExprResult OriginalLHS = LHS;
12810 ExprResult OriginalRHS = RHS;
12811 if (LHSMatType && !RHSMatType) {
12812 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12813 if (!RHS.isInvalid())
12814 return LHSType;
12815
12816 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12817 }
12818
12819 if (!LHSMatType && RHSMatType) {
12820 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12821 if (!LHS.isInvalid())
12822 return RHSType;
12823 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12824 }
12825
12826 return InvalidOperands(Loc, LHS, RHS);
12827}
12828
12829QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12830 SourceLocation Loc,
12831 bool IsCompAssign) {
12832 if (!IsCompAssign) {
12833 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12834 if (LHS.isInvalid())
12835 return QualType();
12836 }
12837 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12838 if (RHS.isInvalid())
12839 return QualType();
12840
12841 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12842 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12843 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", 12843, __extension__ __PRETTY_FUNCTION__
))
;
12844
12845 if (LHSMatType && RHSMatType) {
12846 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12847 return InvalidOperands(Loc, LHS, RHS);
12848
12849 if (!Context.hasSameType(LHSMatType->getElementType(),
12850 RHSMatType->getElementType()))
12851 return InvalidOperands(Loc, LHS, RHS);
12852
12853 return Context.getConstantMatrixType(LHSMatType->getElementType(),
12854 LHSMatType->getNumRows(),
12855 RHSMatType->getNumColumns());
12856 }
12857 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12858}
12859
12860static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
12861 switch (Opc) {
12862 default:
12863 return false;
12864 case BO_And:
12865 case BO_AndAssign:
12866 case BO_Or:
12867 case BO_OrAssign:
12868 case BO_Xor:
12869 case BO_XorAssign:
12870 return true;
12871 }
12872}
12873
12874inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12875 SourceLocation Loc,
12876 BinaryOperatorKind Opc) {
12877 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12878
12879 bool IsCompAssign =
12880 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12881
12882 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
12883
12884 if (LHS.get()->getType()->isVectorType() ||
12885 RHS.get()->getType()->isVectorType()) {
12886 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12887 RHS.get()->getType()->hasIntegerRepresentation())
12888 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12889 /*AllowBothBool*/ true,
12890 /*AllowBoolConversions*/ getLangOpts().ZVector,
12891 /*AllowBooleanOperation*/ LegalBoolVecOperator,
12892 /*ReportInvalid*/ true);
12893 return InvalidOperands(Loc, LHS, RHS);
12894 }
12895
12896 if (LHS.get()->getType()->isVLSTBuiltinType() ||
12897 RHS.get()->getType()->isVLSTBuiltinType()) {
12898 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12899 RHS.get()->getType()->hasIntegerRepresentation())
12900 return CheckSizelessVectorOperands(LHS, RHS, Loc, ACK_BitwiseOp);
12901 return InvalidOperands(Loc, LHS, RHS);
12902 }
12903
12904 if (Opc == BO_And)
12905 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12906
12907 if (LHS.get()->getType()->hasFloatingRepresentation() ||
12908 RHS.get()->getType()->hasFloatingRepresentation())
12909 return InvalidOperands(Loc, LHS, RHS);
12910
12911 ExprResult LHSResult = LHS, RHSResult = RHS;
12912 QualType compType = UsualArithmeticConversions(
12913 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12914 if (LHSResult.isInvalid() || RHSResult.isInvalid())
12915 return QualType();
12916 LHS = LHSResult.get();
12917 RHS = RHSResult.get();
12918
12919 if (Opc == BO_Xor)
12920 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12921
12922 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12923 return compType;
12924 return InvalidOperands(Loc, LHS, RHS);
12925}
12926
12927// C99 6.5.[13,14]
12928inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12929 SourceLocation Loc,
12930 BinaryOperatorKind Opc) {
12931 // Check vector operands differently.
12932 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12933 return CheckVectorLogicalOperands(LHS, RHS, Loc);
12934
12935 bool EnumConstantInBoolContext = false;
12936 for (const ExprResult &HS : {LHS, RHS}) {
12937 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12938 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12939 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12940 EnumConstantInBoolContext = true;
12941 }
12942 }
12943
12944 if (EnumConstantInBoolContext)
12945 Diag(Loc, diag::warn_enum_constant_in_bool_context);
12946
12947 // Diagnose cases where the user write a logical and/or but probably meant a
12948 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
12949 // is a constant.
12950 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12951 !LHS.get()->getType()->isBooleanType() &&
12952 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12953 // Don't warn in macros or template instantiations.
12954 !Loc.isMacroID() && !inTemplateInstantiation()) {
12955 // If the RHS can be constant folded, and if it constant folds to something
12956 // that isn't 0 or 1 (which indicate a potential logical operation that
12957 // happened to fold to true/false) then warn.
12958 // Parens on the RHS are ignored.
12959 Expr::EvalResult EVResult;
12960 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12961 llvm::APSInt Result = EVResult.Val.getInt();
12962 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12963 !RHS.get()->getExprLoc().isMacroID()) ||
12964 (Result != 0 && Result != 1)) {
12965 Diag(Loc, diag::warn_logical_instead_of_bitwise)
12966 << RHS.get()->getSourceRange()
12967 << (Opc == BO_LAnd ? "&&" : "||");
12968 // Suggest replacing the logical operator with the bitwise version
12969 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12970 << (Opc == BO_LAnd ? "&" : "|")
12971 << FixItHint::CreateReplacement(SourceRange(
12972 Loc, getLocForEndOfToken(Loc)),
12973 Opc == BO_LAnd ? "&" : "|");
12974 if (Opc == BO_LAnd)
12975 // Suggest replacing "Foo() && kNonZero" with "Foo()"
12976 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12977 << FixItHint::CreateRemoval(
12978 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12979 RHS.get()->getEndLoc()));
12980 }
12981 }
12982 }
12983
12984 if (!Context.getLangOpts().CPlusPlus) {
12985 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12986 // not operate on the built-in scalar and vector float types.
12987 if (Context.getLangOpts().OpenCL &&
12988 Context.getLangOpts().OpenCLVersion < 120) {
12989 if (LHS.get()->getType()->isFloatingType() ||
12990 RHS.get()->getType()->isFloatingType())
12991 return InvalidOperands(Loc, LHS, RHS);
12992 }
12993
12994 LHS = UsualUnaryConversions(LHS.get());
12995 if (LHS.isInvalid())
12996 return QualType();
12997
12998 RHS = UsualUnaryConversions(RHS.get());
12999 if (RHS.isInvalid())
13000 return QualType();
13001
13002 if (!LHS.get()->getType()->isScalarType() ||
13003 !RHS.get()->getType()->isScalarType())
13004 return InvalidOperands(Loc, LHS, RHS);
13005
13006 return Context.IntTy;
13007 }
13008
13009 // The following is safe because we only use this method for
13010 // non-overloadable operands.
13011
13012 // C++ [expr.log.and]p1
13013 // C++ [expr.log.or]p1
13014 // The operands are both contextually converted to type bool.
13015 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13016 if (LHSRes.isInvalid())
13017 return InvalidOperands(Loc, LHS, RHS);
13018 LHS = LHSRes;
13019
13020 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13021 if (RHSRes.isInvalid())
13022 return InvalidOperands(Loc, LHS, RHS);
13023 RHS = RHSRes;
13024
13025 // C++ [expr.log.and]p2
13026 // C++ [expr.log.or]p2
13027 // The result is a bool.
13028 return Context.BoolTy;
13029}
13030
13031static bool IsReadonlyMessage(Expr *E, Sema &S) {
13032 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13033 if (!ME) return false;
13034 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13035 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13036 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13037 if (!Base) return false;
13038 return Base->getMethodDecl() != nullptr;
13039}
13040
13041/// Is the given expression (which must be 'const') a reference to a
13042/// variable which was originally non-const, but which has become
13043/// 'const' due to being captured within a block?
13044enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13045static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13046 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", 13046, __extension__ __PRETTY_FUNCTION__
))
;
13047 E = E->IgnoreParens();
13048
13049 // Must be a reference to a declaration from an enclosing scope.
13050 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13051 if (!DRE) return NCCK_None;
13052 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13053
13054 // The declaration must be a variable which is not declared 'const'.
13055 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13056 if (!var) return NCCK_None;
13057 if (var->getType().isConstQualified()) return NCCK_None;
13058 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", 13058, __extension__ __PRETTY_FUNCTION__
))
;
13059
13060 // Decide whether the first capture was for a block or a lambda.
13061 DeclContext *DC = S.CurContext, *Prev = nullptr;
13062 // Decide whether the first capture was for a block or a lambda.
13063 while (DC) {
13064 // For init-capture, it is possible that the variable belongs to the
13065 // template pattern of the current context.
13066 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13067 if (var->isInitCapture() &&
13068 FD->getTemplateInstantiationPattern() == var->getDeclContext())
13069 break;
13070 if (DC == var->getDeclContext())
13071 break;
13072 Prev = DC;
13073 DC = DC->getParent();
13074 }
13075 // Unless we have an init-capture, we've gone one step too far.
13076 if (!var->isInitCapture())
13077 DC = Prev;
13078 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13079}
13080
13081static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13082 Ty = Ty.getNonReferenceType();
13083 if (IsDereference && Ty->isPointerType())
13084 Ty = Ty->getPointeeType();
13085 return !Ty.isConstQualified();
13086}
13087
13088// Update err_typecheck_assign_const and note_typecheck_assign_const
13089// when this enum is changed.
13090enum {
13091 ConstFunction,
13092 ConstVariable,
13093 ConstMember,
13094 ConstMethod,
13095 NestedConstMember,
13096 ConstUnknown, // Keep as last element
13097};
13098
13099/// Emit the "read-only variable not assignable" error and print notes to give
13100/// more information about why the variable is not assignable, such as pointing
13101/// to the declaration of a const variable, showing that a method is const, or
13102/// that the function is returning a const reference.
13103static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13104 SourceLocation Loc) {
13105 SourceRange ExprRange = E->getSourceRange();
13106
13107 // Only emit one error on the first const found. All other consts will emit
13108 // a note to the error.
13109 bool DiagnosticEmitted = false;
13110
13111 // Track if the current expression is the result of a dereference, and if the
13112 // next checked expression is the result of a dereference.
13113 bool IsDereference = false;
13114 bool NextIsDereference = false;
13115
13116 // Loop to process MemberExpr chains.
13117 while (true) {
13118 IsDereference = NextIsDereference;
13119
13120 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13121 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13122 NextIsDereference = ME->isArrow();
13123 const ValueDecl *VD = ME->getMemberDecl();
13124 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13125 // Mutable fields can be modified even if the class is const.
13126 if (Field->isMutable()) {
13127 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", 13127, __extension__ __PRETTY_FUNCTION__
))
;
13128 break;
13129 }
13130
13131 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13132 if (!DiagnosticEmitted) {
13133 S.Diag(Loc, diag::err_typecheck_assign_const)
13134 << ExprRange << ConstMember << false /*static*/ << Field
13135 << Field->getType();
13136 DiagnosticEmitted = true;
13137 }
13138 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13139 << ConstMember << false /*static*/ << Field << Field->getType()
13140 << Field->getSourceRange();
13141 }
13142 E = ME->getBase();
13143 continue;
13144 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13145 if (VDecl->getType().isConstQualified()) {
13146 if (!DiagnosticEmitted) {
13147 S.Diag(Loc, diag::err_typecheck_assign_const)
13148 << ExprRange << ConstMember << true /*static*/ << VDecl
13149 << VDecl->getType();
13150 DiagnosticEmitted = true;
13151 }
13152 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13153 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13154 << VDecl->getSourceRange();
13155 }
13156 // Static fields do not inherit constness from parents.
13157 break;
13158 }
13159 break; // End MemberExpr
13160 } else if (const ArraySubscriptExpr *ASE =
13161 dyn_cast<ArraySubscriptExpr>(E)) {
13162 E = ASE->getBase()->IgnoreParenImpCasts();
13163 continue;
13164 } else if (const ExtVectorElementExpr *EVE =
13165 dyn_cast<ExtVectorElementExpr>(E)) {
13166 E = EVE->getBase()->IgnoreParenImpCasts();
13167 continue;
13168 }
13169 break;
13170 }
13171
13172 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13173 // Function calls
13174 const FunctionDecl *FD = CE->getDirectCallee();
13175 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13176 if (!DiagnosticEmitted) {
13177 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13178 << ConstFunction << FD;
13179 DiagnosticEmitted = true;
13180 }
13181 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13182 diag::note_typecheck_assign_const)
13183 << ConstFunction << FD << FD->getReturnType()
13184 << FD->getReturnTypeSourceRange();
13185 }
13186 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13187 // Point to variable declaration.
13188 if (const ValueDecl *VD = DRE->getDecl()) {
13189 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13190 if (!DiagnosticEmitted) {
13191 S.Diag(Loc, diag::err_typecheck_assign_const)
13192 << ExprRange << ConstVariable << VD << VD->getType();
13193 DiagnosticEmitted = true;
13194 }
13195 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13196 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13197 }
13198 }
13199 } else if (isa<CXXThisExpr>(E)) {
13200 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13201 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13202 if (MD->isConst()) {
13203 if (!DiagnosticEmitted) {
13204 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13205 << ConstMethod << MD;
13206 DiagnosticEmitted = true;
13207 }
13208 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13209 << ConstMethod << MD << MD->getSourceRange();
13210 }
13211 }
13212 }
13213 }
13214
13215 if (DiagnosticEmitted)
13216 return;
13217
13218 // Can't determine a more specific message, so display the generic error.
13219 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13220}
13221
13222enum OriginalExprKind {
13223 OEK_Variable,
13224 OEK_Member,
13225 OEK_LValue
13226};
13227
13228static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13229 const RecordType *Ty,
13230 SourceLocation Loc, SourceRange Range,
13231 OriginalExprKind OEK,
13232 bool &DiagnosticEmitted) {
13233 std::vector<const RecordType *> RecordTypeList;
13234 RecordTypeList.push_back(Ty);
13235 unsigned NextToCheckIndex = 0;
13236 // We walk the record hierarchy breadth-first to ensure that we print
13237 // diagnostics in field nesting order.
13238 while (RecordTypeList.size() > NextToCheckIndex) {
13239 bool IsNested = NextToCheckIndex > 0;
13240 for (const FieldDecl *Field :
13241 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13242 // First, check every field for constness.
13243 QualType FieldTy = Field->getType();
13244 if (FieldTy.isConstQualified()) {
13245 if (!DiagnosticEmitted) {
13246 S.Diag(Loc, diag::err_typecheck_assign_const)
13247 << Range << NestedConstMember << OEK << VD
13248 << IsNested << Field;
13249 DiagnosticEmitted = true;
13250 }
13251 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13252 << NestedConstMember << IsNested << Field
13253 << FieldTy << Field->getSourceRange();
13254 }
13255
13256 // Then we append it to the list to check next in order.
13257 FieldTy = FieldTy.getCanonicalType();
13258 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13259 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13260 RecordTypeList.push_back(FieldRecTy);
13261 }
13262 }
13263 ++NextToCheckIndex;
13264 }
13265}
13266
13267/// Emit an error for the case where a record we are trying to assign to has a
13268/// const-qualified field somewhere in its hierarchy.
13269static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13270 SourceLocation Loc) {
13271 QualType Ty = E->getType();
13272 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", 13272, __extension__ __PRETTY_FUNCTION__
))
;
13273 SourceRange Range = E->getSourceRange();
13274 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13275 bool DiagEmitted = false;
13276
13277 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13278 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13279 Range, OEK_Member, DiagEmitted);
13280 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13281 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13282 Range, OEK_Variable, DiagEmitted);
13283 else
13284 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13285 Range, OEK_LValue, DiagEmitted);
13286 if (!DiagEmitted)
13287 DiagnoseConstAssignment(S, E, Loc);
13288}
13289
13290/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13291/// emit an error and return true. If so, return false.
13292static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13293 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", 13293, __extension__ __PRETTY_FUNCTION__
))
;
13294
13295 S.CheckShadowingDeclModification(E, Loc);
13296
13297 SourceLocation OrigLoc = Loc;
13298 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13299 &Loc);
13300 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13301 IsLV = Expr::MLV_InvalidMessageExpression;
13302 if (IsLV == Expr::MLV_Valid)
13303 return false;
13304
13305 unsigned DiagID = 0;
13306 bool NeedType = false;
13307 switch (IsLV) { // C99 6.5.16p2
13308 case Expr::MLV_ConstQualified:
13309 // Use a specialized diagnostic when we're assigning to an object
13310 // from an enclosing function or block.
13311 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13312 if (NCCK == NCCK_Block)
13313 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13314 else
13315 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13316 break;
13317 }
13318
13319 // In ARC, use some specialized diagnostics for occasions where we
13320 // infer 'const'. These are always pseudo-strong variables.
13321 if (S.getLangOpts().ObjCAutoRefCount) {
13322 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13323 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13324 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13325
13326 // Use the normal diagnostic if it's pseudo-__strong but the
13327 // user actually wrote 'const'.
13328 if (var->isARCPseudoStrong() &&
13329 (!var->getTypeSourceInfo() ||
13330 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13331 // There are three pseudo-strong cases:
13332 // - self
13333 ObjCMethodDecl *method = S.getCurMethodDecl();
13334 if (method && var == method->getSelfDecl()) {
13335 DiagID = method->isClassMethod()
13336 ? diag::err_typecheck_arc_assign_self_class_method
13337 : diag::err_typecheck_arc_assign_self;
13338
13339 // - Objective-C externally_retained attribute.
13340 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13341 isa<ParmVarDecl>(var)) {
13342 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13343
13344 // - fast enumeration variables
13345 } else {
13346 DiagID = diag::err_typecheck_arr_assign_enumeration;
13347 }
13348
13349 SourceRange Assign;
13350 if (Loc != OrigLoc)
13351 Assign = SourceRange(OrigLoc, OrigLoc);
13352 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13353 // We need to preserve the AST regardless, so migration tool
13354 // can do its job.
13355 return false;
13356 }
13357 }
13358 }
13359
13360 // If none of the special cases above are triggered, then this is a
13361 // simple const assignment.
13362 if (DiagID == 0) {
13363 DiagnoseConstAssignment(S, E, Loc);
13364 return true;
13365 }
13366
13367 break;
13368 case Expr::MLV_ConstAddrSpace:
13369 DiagnoseConstAssignment(S, E, Loc);
13370 return true;
13371 case Expr::MLV_ConstQualifiedField:
13372 DiagnoseRecursiveConstFields(S, E, Loc);
13373 return true;
13374 case Expr::MLV_ArrayType:
13375 case Expr::MLV_ArrayTemporary:
13376 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13377 NeedType = true;
13378 break;
13379 case Expr::MLV_NotObjectType:
13380 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13381 NeedType = true;
13382 break;
13383 case Expr::MLV_LValueCast:
13384 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13385 break;
13386 case Expr::MLV_Valid:
13387 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", 13387)
;
13388 case Expr::MLV_InvalidExpression:
13389 case Expr::MLV_MemberFunction:
13390 case Expr::MLV_ClassTemporary:
13391 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13392 break;
13393 case Expr::MLV_IncompleteType:
13394 case Expr::MLV_IncompleteVoidType:
13395 return S.RequireCompleteType(Loc, E->getType(),
13396 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13397 case Expr::MLV_DuplicateVectorComponents:
13398 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13399 break;
13400 case Expr::MLV_NoSetterProperty:
13401 llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently"
, "clang/lib/Sema/SemaExpr.cpp", 13401)
;
13402 case Expr::MLV_InvalidMessageExpression:
13403 DiagID = diag::err_readonly_message_assignment;
13404 break;
13405 case Expr::MLV_SubObjCPropertySetting:
13406 DiagID = diag::err_no_subobject_property_setting;
13407 break;
13408 }
13409
13410 SourceRange Assign;
13411 if (Loc != OrigLoc)
13412 Assign = SourceRange(OrigLoc, OrigLoc);
13413 if (NeedType)
13414 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13415 else
13416 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13417 return true;
13418}
13419
13420static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13421 SourceLocation Loc,
13422 Sema &Sema) {
13423 if (Sema.inTemplateInstantiation())
13424 return;
13425 if (Sema.isUnevaluatedContext())
13426 return;
13427 if (Loc.isInvalid() || Loc.isMacroID())
13428 return;
13429 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13430 return;
13431
13432 // C / C++ fields
13433 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13434 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13435 if (ML && MR) {
13436 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13437 return;
13438 const ValueDecl *LHSDecl =
13439 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13440 const ValueDecl *RHSDecl =
13441 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13442 if (LHSDecl != RHSDecl)
13443 return;
13444 if (LHSDecl->getType().isVolatileQualified())
13445 return;
13446 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13447 if (RefTy->getPointeeType().isVolatileQualified())
13448 return;
13449
13450 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13451 }
13452
13453 // Objective-C instance variables
13454 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13455 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13456 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13457 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13458 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13459 if (RL && RR && RL->getDecl() == RR->getDecl())
13460 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13461 }
13462}
13463
13464// C99 6.5.16.1
13465QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13466 SourceLocation Loc,
13467 QualType CompoundType) {
13468 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", 13468, __extension__ __PRETTY_FUNCTION__
))
;
13469
13470 // Verify that LHS is a modifiable lvalue, and emit error if not.
13471 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13472 return QualType();
13473
13474 QualType LHSType = LHSExpr->getType();
13475 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13476 CompoundType;
13477 // OpenCL v1.2 s6.1.1.1 p2:
13478 // The half data type can only be used to declare a pointer to a buffer that
13479 // contains half values
13480 if (getLangOpts().OpenCL &&
13481 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13482 LHSType->isHalfType()) {
13483 Diag(Loc, diag::err_opencl_half_load_store) << 1
13484 << LHSType.getUnqualifiedType();
13485 return QualType();
13486 }
13487
13488 AssignConvertType ConvTy;
13489 if (CompoundType.isNull()) {
13490 Expr *RHSCheck = RHS.get();
13491
13492 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13493
13494 QualType LHSTy(LHSType);
13495 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13496 if (RHS.isInvalid())
13497 return QualType();
13498 // Special case of NSObject attributes on c-style pointer types.
13499 if (ConvTy == IncompatiblePointer &&
13500 ((Context.isObjCNSObjectType(LHSType) &&
13501 RHSType->isObjCObjectPointerType()) ||
13502 (Context.isObjCNSObjectType(RHSType) &&
13503 LHSType->isObjCObjectPointerType())))
13504 ConvTy = Compatible;
13505
13506 if (ConvTy == Compatible &&
13507 LHSType->isObjCObjectType())
13508 Diag(Loc, diag::err_objc_object_assignment)
13509 << LHSType;
13510
13511 // If the RHS is a unary plus or minus, check to see if they = and + are
13512 // right next to each other. If so, the user may have typo'd "x =+ 4"
13513 // instead of "x += 4".
13514 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13515 RHSCheck = ICE->getSubExpr();
13516 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13517 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13518 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13519 // Only if the two operators are exactly adjacent.
13520 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13521 // And there is a space or other character before the subexpr of the
13522 // unary +/-. We don't want to warn on "x=-1".
13523 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13524 UO->getSubExpr()->getBeginLoc().isFileID()) {
13525 Diag(Loc, diag::warn_not_compound_assign)
13526 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13527 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13528 }
13529 }
13530
13531 if (ConvTy == Compatible) {
13532 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13533 // Warn about retain cycles where a block captures the LHS, but
13534 // not if the LHS is a simple variable into which the block is
13535 // being stored...unless that variable can be captured by reference!
13536 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13537 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13538 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13539 checkRetainCycles(LHSExpr, RHS.get());
13540 }
13541
13542 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13543 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13544 // It is safe to assign a weak reference into a strong variable.
13545 // Although this code can still have problems:
13546 // id x = self.weakProp;
13547 // id y = self.weakProp;
13548 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13549 // paths through the function. This should be revisited if
13550 // -Wrepeated-use-of-weak is made flow-sensitive.
13551 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13552 // variable, which will be valid for the current autorelease scope.
13553 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13554 RHS.get()->getBeginLoc()))
13555 getCurFunction()->markSafeWeakUse(RHS.get());
13556
13557 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13558 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13559 }
13560 }
13561 } else {
13562 // Compound assignment "x += y"
13563 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13564 }
13565
13566 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13567 RHS.get(), AA_Assigning))
13568 return QualType();
13569
13570 CheckForNullPointerDereference(*this, LHSExpr);
13571
13572 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13573 if (CompoundType.isNull()) {
13574 // C++2a [expr.ass]p5:
13575 // A simple-assignment whose left operand is of a volatile-qualified
13576 // type is deprecated unless the assignment is either a discarded-value
13577 // expression or an unevaluated operand
13578 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13579 } else {
13580 // C++2a [expr.ass]p6:
13581 // [Compound-assignment] expressions are deprecated if E1 has
13582 // volatile-qualified type
13583 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13584 }
13585 }
13586
13587 // C99 6.5.16p3: The type of an assignment expression is the type of the
13588 // left operand unless the left operand has qualified type, in which case
13589 // it is the unqualified version of the type of the left operand.
13590 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13591 // is converted to the type of the assignment expression (above).
13592 // C++ 5.17p1: the type of the assignment expression is that of its left
13593 // operand.
13594 return (getLangOpts().CPlusPlus
13595 ? LHSType : LHSType.getUnqualifiedType());
13596}
13597
13598// Only ignore explicit casts to void.
13599static bool IgnoreCommaOperand(const Expr *E) {
13600 E = E->IgnoreParens();
13601
13602 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13603 if (CE->getCastKind() == CK_ToVoid) {
13604 return true;
13605 }
13606
13607 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13608 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13609 CE->getSubExpr()->getType()->isDependentType()) {
13610 return true;
13611 }
13612 }
13613
13614 return false;
13615}
13616
13617// Look for instances where it is likely the comma operator is confused with
13618// another operator. There is an explicit list of acceptable expressions for
13619// the left hand side of the comma operator, otherwise emit a warning.
13620void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13621 // No warnings in macros
13622 if (Loc.isMacroID())
13623 return;
13624
13625 // Don't warn in template instantiations.
13626 if (inTemplateInstantiation())
13627 return;
13628
13629 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13630 // instead, skip more than needed, then call back into here with the
13631 // CommaVisitor in SemaStmt.cpp.
13632 // The listed locations are the initialization and increment portions
13633 // of a for loop. The additional checks are on the condition of
13634 // if statements, do/while loops, and for loops.
13635 // Differences in scope flags for C89 mode requires the extra logic.
13636 const unsigned ForIncrementFlags =
13637 getLangOpts().C99 || getLangOpts().CPlusPlus
13638 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13639 : Scope::ContinueScope | Scope::BreakScope;
13640 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13641 const unsigned ScopeFlags = getCurScope()->getFlags();
13642 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13643 (ScopeFlags & ForInitFlags) == ForInitFlags)
13644 return;
13645
13646 // If there are multiple comma operators used together, get the RHS of the
13647 // of the comma operator as the LHS.
13648 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13649 if (BO->getOpcode() != BO_Comma)
13650 break;
13651 LHS = BO->getRHS();
13652 }
13653
13654 // Only allow some expressions on LHS to not warn.
13655 if (IgnoreCommaOperand(LHS))
13656 return;
13657
13658 Diag(Loc, diag::warn_comma_operator);
13659 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13660 << LHS->getSourceRange()
13661 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13662 LangOpts.CPlusPlus ? "static_cast<void>("
13663 : "(void)(")
13664 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13665 ")");
13666}
13667
13668// C99 6.5.17
13669static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13670 SourceLocation Loc) {
13671 LHS = S.CheckPlaceholderExpr(LHS.get());
13672 RHS = S.CheckPlaceholderExpr(RHS.get());
13673 if (LHS.isInvalid() || RHS.isInvalid())
13674 return QualType();
13675
13676 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13677 // operands, but not unary promotions.
13678 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13679
13680 // So we treat the LHS as a ignored value, and in C++ we allow the
13681 // containing site to determine what should be done with the RHS.
13682 LHS = S.IgnoredValueConversions(LHS.get());
13683 if (LHS.isInvalid())
13684 return QualType();
13685
13686 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13687
13688 if (!S.getLangOpts().CPlusPlus) {
13689 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13690 if (RHS.isInvalid())
13691 return QualType();
13692 if (!RHS.get()->getType()->isVoidType())
13693 S.RequireCompleteType(Loc, RHS.get()->getType(),
13694 diag::err_incomplete_type);
13695 }
13696
13697 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13698 S.DiagnoseCommaOperator(LHS.get(), Loc);
13699
13700 return RHS.get()->getType();
13701}
13702
13703/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13704/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13705static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13706 ExprValueKind &VK,
13707 ExprObjectKind &OK,
13708 SourceLocation OpLoc,
13709 bool IsInc, bool IsPrefix) {
13710 if (Op->isTypeDependent())
13711 return S.Context.DependentTy;
13712
13713 QualType ResType = Op->getType();
13714 // Atomic types can be used for increment / decrement where the non-atomic
13715 // versions can, so ignore the _Atomic() specifier for the purpose of
13716 // checking.
13717 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13718 ResType = ResAtomicType->getValueType();
13719
13720 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", 13720, __extension__ __PRETTY_FUNCTION__
))
;
13721
13722 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13723 // Decrement of bool is not allowed.
13724 if (!IsInc) {
13725 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13726 return QualType();
13727 }
13728 // Increment of bool sets it to true, but is deprecated.
13729 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13730 : diag::warn_increment_bool)
13731 << Op->getSourceRange();
13732 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13733 // Error on enum increments and decrements in C++ mode
13734 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13735 return QualType();
13736 } else if (ResType->isRealType()) {
13737 // OK!
13738 } else if (ResType->isPointerType()) {
13739 // C99 6.5.2.4p2, 6.5.6p2
13740 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13741 return QualType();
13742 } else if (ResType->isObjCObjectPointerType()) {
13743 // On modern runtimes, ObjC pointer arithmetic is forbidden.
13744 // Otherwise, we just need a complete type.
13745 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13746 checkArithmeticOnObjCPointer(S, OpLoc, Op))
13747 return QualType();
13748 } else if (ResType->isAnyComplexType()) {
13749 // C99 does not support ++/-- on complex types, we allow as an extension.
13750 S.Diag(OpLoc, diag::ext_integer_increment_complex)
13751 << ResType << Op->getSourceRange();
13752 } else if (ResType->isPlaceholderType()) {
13753 ExprResult PR = S.CheckPlaceholderExpr(Op);
13754 if (PR.isInvalid()) return QualType();
13755 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13756 IsInc, IsPrefix);
13757 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13758 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13759 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13760 (ResType->castAs<VectorType>()->getVectorKind() !=
13761 VectorType::AltiVecBool)) {
13762 // The z vector extensions allow ++ and -- for non-bool vectors.
13763 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13764 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13765 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13766 } else {
13767 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13768 << ResType << int(IsInc) << Op->getSourceRange();
13769 return QualType();
13770 }
13771 // At this point, we know we have a real, complex or pointer type.
13772 // Now make sure the operand is a modifiable lvalue.
13773 if (CheckForModifiableLvalue(Op, OpLoc, S))
13774 return QualType();
13775 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13776 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13777 // An operand with volatile-qualified type is deprecated
13778 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13779 << IsInc << ResType;
13780 }
13781 // In C++, a prefix increment is the same type as the operand. Otherwise
13782 // (in C or with postfix), the increment is the unqualified type of the
13783 // operand.
13784 if (IsPrefix && S.getLangOpts().CPlusPlus) {
13785 VK = VK_LValue;
13786 OK = Op->getObjectKind();
13787 return ResType;
13788 } else {
13789 VK = VK_PRValue;
13790 return ResType.getUnqualifiedType();
13791 }
13792}
13793
13794
13795/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13796/// This routine allows us to typecheck complex/recursive expressions
13797/// where the declaration is needed for type checking. We only need to
13798/// handle cases when the expression references a function designator
13799/// or is an lvalue. Here are some examples:
13800/// - &(x) => x
13801/// - &*****f => f for f a function designator.
13802/// - &s.xx => s
13803/// - &s.zz[1].yy -> s, if zz is an array
13804/// - *(x + 1) -> x, if x is an array
13805/// - &"123"[2] -> 0
13806/// - & __real__ x -> x
13807///
13808/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13809/// members.
13810static ValueDecl *getPrimaryDecl(Expr *E) {
13811 switch (E->getStmtClass()) {
13812 case Stmt::DeclRefExprClass:
13813 return cast<DeclRefExpr>(E)->getDecl();
13814 case Stmt::MemberExprClass:
13815 // If this is an arrow operator, the address is an offset from
13816 // the base's value, so the object the base refers to is
13817 // irrelevant.
13818 if (cast<MemberExpr>(E)->isArrow())
13819 return nullptr;
13820 // Otherwise, the expression refers to a part of the base
13821 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13822 case Stmt::ArraySubscriptExprClass: {
13823 // FIXME: This code shouldn't be necessary! We should catch the implicit
13824 // promotion of register arrays earlier.
13825 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13826 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13827 if (ICE->getSubExpr()->getType()->isArrayType())
13828 return getPrimaryDecl(ICE->getSubExpr());
13829 }
13830 return nullptr;
13831 }
13832 case Stmt::UnaryOperatorClass: {
13833 UnaryOperator *UO = cast<UnaryOperator>(E);
13834
13835 switch(UO->getOpcode()) {
13836 case UO_Real:
13837 case UO_Imag:
13838 case UO_Extension:
13839 return getPrimaryDecl(UO->getSubExpr());
13840 default:
13841 return nullptr;
13842 }
13843 }
13844 case Stmt::ParenExprClass:
13845 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13846 case Stmt::ImplicitCastExprClass:
13847 // If the result of an implicit cast is an l-value, we care about
13848 // the sub-expression; otherwise, the result here doesn't matter.
13849 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13850 case Stmt::CXXUuidofExprClass:
13851 return cast<CXXUuidofExpr>(E)->getGuidDecl();
13852 default:
13853 return nullptr;
13854 }
13855}
13856
13857namespace {
13858enum {
13859 AO_Bit_Field = 0,
13860 AO_Vector_Element = 1,
13861 AO_Property_Expansion = 2,
13862 AO_Register_Variable = 3,
13863 AO_Matrix_Element = 4,
13864 AO_No_Error = 5
13865};
13866}
13867/// Diagnose invalid operand for address of operations.
13868///
13869/// \param Type The type of operand which cannot have its address taken.
13870static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13871 Expr *E, unsigned Type) {
13872 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13873}
13874
13875/// CheckAddressOfOperand - The operand of & must be either a function
13876/// designator or an lvalue designating an object. If it is an lvalue, the
13877/// object cannot be declared with storage class register or be a bit field.
13878/// Note: The usual conversions are *not* applied to the operand of the &
13879/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13880/// In C++, the operand might be an overloaded function name, in which case
13881/// we allow the '&' but retain the overloaded-function type.
13882QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13883 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13884 if (PTy->getKind() == BuiltinType::Overload) {
13885 Expr *E = OrigOp.get()->IgnoreParens();
13886 if (!isa<OverloadExpr>(E)) {
13887 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", 13887, __extension__ __PRETTY_FUNCTION__
))
;
13888 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13889 << OrigOp.get()->getSourceRange();
13890 return QualType();
13891 }
13892
13893 OverloadExpr *Ovl = cast<OverloadExpr>(E);
13894 if (isa<UnresolvedMemberExpr>(Ovl))
13895 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13896 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13897 << OrigOp.get()->getSourceRange();
13898 return QualType();
13899 }
13900
13901 return Context.OverloadTy;
13902 }
13903
13904 if (PTy->getKind() == BuiltinType::UnknownAny)
13905 return Context.UnknownAnyTy;
13906
13907 if (PTy->getKind() == BuiltinType::BoundMember) {
13908 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13909 << OrigOp.get()->getSourceRange();
13910 return QualType();
13911 }
13912
13913 OrigOp = CheckPlaceholderExpr(OrigOp.get());
13914 if (OrigOp.isInvalid()) return QualType();
13915 }
13916
13917 if (OrigOp.get()->isTypeDependent())
13918 return Context.DependentTy;
13919
13920 assert(!OrigOp.get()->hasPlaceholderType())(static_cast <bool> (!OrigOp.get()->hasPlaceholderType
()) ? void (0) : __assert_fail ("!OrigOp.get()->hasPlaceholderType()"
, "clang/lib/Sema/SemaExpr.cpp", 13920, __extension__ __PRETTY_FUNCTION__
))
;
13921
13922 // Make sure to ignore parentheses in subsequent checks
13923 Expr *op = OrigOp.get()->IgnoreParens();
13924
13925 // In OpenCL captures for blocks called as lambda functions
13926 // are located in the private address space. Blocks used in
13927 // enqueue_kernel can be located in a different address space
13928 // depending on a vendor implementation. Thus preventing
13929 // taking an address of the capture to avoid invalid AS casts.
13930 if (LangOpts.OpenCL) {
13931 auto* VarRef = dyn_cast<DeclRefExpr>(op);
13932 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13933 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13934 return QualType();
13935 }
13936 }
13937
13938 if (getLangOpts().C99) {
13939 // Implement C99-only parts of addressof rules.
13940 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13941 if (uOp->getOpcode() == UO_Deref)
13942 // Per C99 6.5.3.2, the address of a deref always returns a valid result
13943 // (assuming the deref expression is valid).
13944 return uOp->getSubExpr()->getType();
13945 }
13946 // Technically, there should be a check for array subscript
13947 // expressions here, but the result of one is always an lvalue anyway.
13948 }
13949 ValueDecl *dcl = getPrimaryDecl(op);
13950
13951 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13952 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13953 op->getBeginLoc()))
13954 return QualType();
13955
13956 Expr::LValueClassification lval = op->ClassifyLValue(Context);
13957 unsigned AddressOfError = AO_No_Error;
13958
13959 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13960 bool sfinae = (bool)isSFINAEContext();
13961 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13962 : diag::ext_typecheck_addrof_temporary)
13963 << op->getType() << op->getSourceRange();
13964 if (sfinae)
13965 return QualType();
13966 // Materialize the temporary as an lvalue so that we can take its address.
13967 OrigOp = op =
13968 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13969 } else if (isa<ObjCSelectorExpr>(op)) {
13970 return Context.getPointerType(op->getType());
13971 } else if (lval == Expr::LV_MemberFunction) {
13972 // If it's an instance method, make a member pointer.
13973 // The expression must have exactly the form &A::foo.
13974
13975 // If the underlying expression isn't a decl ref, give up.
13976 if (!isa<DeclRefExpr>(op)) {
13977 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13978 << OrigOp.get()->getSourceRange();
13979 return QualType();
13980 }
13981 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13982 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13983
13984 // The id-expression was parenthesized.
13985 if (OrigOp.get() != DRE) {
13986 Diag(OpLoc, diag::err_parens_pointer_member_function)
13987 << OrigOp.get()->getSourceRange();
13988
13989 // The method was named without a qualifier.
13990 } else if (!DRE->getQualifier()) {
13991 if (MD->getParent()->getName().empty())
13992 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13993 << op->getSourceRange();
13994 else {
13995 SmallString<32> Str;
13996 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13997 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13998 << op->getSourceRange()
13999 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14000 }
14001 }
14002
14003 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14004 if (isa<CXXDestructorDecl>(MD))
14005 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14006
14007 QualType MPTy = Context.getMemberPointerType(
14008 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14009 // Under the MS ABI, lock down the inheritance model now.
14010 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14011 (void)isCompleteType(OpLoc, MPTy);
14012 return MPTy;
14013 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14014 // C99 6.5.3.2p1
14015 // The operand must be either an l-value or a function designator
14016 if (!op->getType()->isFunctionType()) {
14017 // Use a special diagnostic for loads from property references.
14018 if (isa<PseudoObjectExpr>(op)) {
14019 AddressOfError = AO_Property_Expansion;
14020 } else {
14021 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14022 << op->getType() << op->getSourceRange();
14023 return QualType();
14024 }
14025 }
14026 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14027 // The operand cannot be a bit-field
14028 AddressOfError = AO_Bit_Field;
14029 } else if (op->getObjectKind() == OK_VectorComponent) {
14030 // The operand cannot be an element of a vector
14031 AddressOfError = AO_Vector_Element;
14032 } else if (op->getObjectKind() == OK_MatrixComponent) {
14033 // The operand cannot be an element of a matrix.
14034 AddressOfError = AO_Matrix_Element;
14035 } else if (dcl) { // C99 6.5.3.2p1
14036 // We have an lvalue with a decl. Make sure the decl is not declared
14037 // with the register storage-class specifier.
14038 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14039 // in C++ it is not error to take address of a register
14040 // variable (c++03 7.1.1P3)
14041 if (vd->getStorageClass() == SC_Register &&
14042 !getLangOpts().CPlusPlus) {
14043 AddressOfError = AO_Register_Variable;
14044 }
14045 } else if (isa<MSPropertyDecl>(dcl)) {
14046 AddressOfError = AO_Property_Expansion;
14047 } else if (isa<FunctionTemplateDecl>(dcl)) {
14048 return Context.OverloadTy;
14049 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14050 // Okay: we can take the address of a field.
14051 // Could be a pointer to member, though, if there is an explicit
14052 // scope qualifier for the class.
14053 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14054 DeclContext *Ctx = dcl->getDeclContext();
14055 if (Ctx && Ctx->isRecord()) {
14056 if (dcl->getType()->isReferenceType()) {
14057 Diag(OpLoc,
14058 diag::err_cannot_form_pointer_to_member_of_reference_type)
14059 << dcl->getDeclName() << dcl->getType();
14060 return QualType();
14061 }
14062
14063 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14064 Ctx = Ctx->getParent();
14065
14066 QualType MPTy = Context.getMemberPointerType(
14067 op->getType(),
14068 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14069 // Under the MS ABI, lock down the inheritance model now.
14070 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14071 (void)isCompleteType(OpLoc, MPTy);
14072 return MPTy;
14073 }
14074 }
14075 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
14076 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
14077 llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type"
, "clang/lib/Sema/SemaExpr.cpp", 14077)
;
14078 }
14079
14080 if (AddressOfError != AO_No_Error) {
14081 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14082 return QualType();
14083 }
14084
14085 if (lval == Expr::LV_IncompleteVoidType) {
14086 // Taking the address of a void variable is technically illegal, but we
14087 // allow it in cases which are otherwise valid.
14088 // Example: "extern void x; void* y = &x;".
14089 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14090 }
14091
14092 // If the operand has type "type", the result has type "pointer to type".
14093 if (op->getType()->isObjCObjectType())
14094 return Context.getObjCObjectPointerType(op->getType());
14095
14096 CheckAddressOfPackedMember(op);
14097
14098 return Context.getPointerType(op->getType());
14099}
14100
14101static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14102 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14103 if (!DRE)
14104 return;
14105 const Decl *D = DRE->getDecl();
14106 if (!D)
14107 return;
14108 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14109 if (!Param)
14110 return;
14111 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14112 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14113 return;
14114 if (FunctionScopeInfo *FD = S.getCurFunction())
14115 if (!FD->ModifiedNonNullParams.count(Param))
14116 FD->ModifiedNonNullParams.insert(Param);
14117}
14118
14119/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14120static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14121 SourceLocation OpLoc) {
14122 if (Op->isTypeDependent())
14123 return S.Context.DependentTy;
14124
14125 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14126 if (ConvResult.isInvalid())
14127 return QualType();
14128 Op = ConvResult.get();
14129 QualType OpTy = Op->getType();
14130 QualType Result;
14131
14132 if (isa<CXXReinterpretCastExpr>(Op)) {
14133 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14134 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14135 Op->getSourceRange());
14136 }
14137
14138 if (const PointerType *PT = OpTy->getAs<PointerType>())
14139 {
14140 Result = PT->getPointeeType();
14141 }
14142 else if (const ObjCObjectPointerType *OPT =
14143 OpTy->getAs<ObjCObjectPointerType>())
14144 Result = OPT->getPointeeType();
14145 else {
14146 ExprResult PR = S.CheckPlaceholderExpr(Op);
14147 if (PR.isInvalid()) return QualType();
14148 if (PR.get() != Op)
14149 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14150 }
14151
14152 if (Result.isNull()) {
14153 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14154 << OpTy << Op->getSourceRange();
14155 return QualType();
14156 }
14157
14158 // Note that per both C89 and C99, indirection is always legal, even if Result
14159 // is an incomplete type or void. It would be possible to warn about
14160 // dereferencing a void pointer, but it's completely well-defined, and such a
14161 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
14162 // for pointers to 'void' but is fine for any other pointer type:
14163 //
14164 // C++ [expr.unary.op]p1:
14165 // [...] the expression to which [the unary * operator] is applied shall
14166 // be a pointer to an object type, or a pointer to a function type
14167 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
14168 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14169 << OpTy << Op->getSourceRange();
14170
14171 // Dereferences are usually l-values...
14172 VK = VK_LValue;
14173
14174 // ...except that certain expressions are never l-values in C.
14175 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14176 VK = VK_PRValue;
14177
14178 return Result;
14179}
14180
14181BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14182 BinaryOperatorKind Opc;
14183 switch (Kind) {
14184 default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "clang/lib/Sema/SemaExpr.cpp"
, 14184)
;
14185 case tok::periodstar: Opc = BO_PtrMemD; break;
14186 case tok::arrowstar: Opc = BO_PtrMemI; break;
14187 case tok::star: Opc = BO_Mul; break;
14188 case tok::slash: Opc = BO_Div; break;
14189 case tok::percent: Opc = BO_Rem; break;
14190 case tok::plus: Opc = BO_Add; break;
14191 case tok::minus: Opc = BO_Sub; break;
14192 case tok::lessless: Opc = BO_Shl; break;
14193 case tok::greatergreater: Opc = BO_Shr; break;
14194 case tok::lessequal: Opc = BO_LE; break;
14195 case tok::less: Opc = BO_LT; break;
14196 case tok::greaterequal: Opc = BO_GE; break;
14197 case tok::greater: Opc = BO_GT; break;
14198 case tok::exclaimequal: Opc = BO_NE; break;
14199 case tok::equalequal: Opc = BO_EQ; break;
14200 case tok::spaceship: Opc = BO_Cmp; break;
14201 case tok::amp: Opc = BO_And; break;
14202 case tok::caret: Opc = BO_Xor; break;
14203 case tok::pipe: Opc = BO_Or; break;
14204 case tok::ampamp: Opc = BO_LAnd; break;
14205 case tok::pipepipe: Opc = BO_LOr; break;
14206 case tok::equal: Opc = BO_Assign; break;
14207 case tok::starequal: Opc = BO_MulAssign; break;
14208 case tok::slashequal: Opc = BO_DivAssign; break;
14209 case tok::percentequal: Opc = BO_RemAssign; break;
14210 case tok::plusequal: Opc = BO_AddAssign; break;
14211 case tok::minusequal: Opc = BO_SubAssign; break;
14212 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14213 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14214 case tok::ampequal: Opc = BO_AndAssign; break;
14215 case tok::caretequal: Opc = BO_XorAssign; break;
14216 case tok::pipeequal: Opc = BO_OrAssign; break;
14217 case tok::comma: Opc = BO_Comma; break;
14218 }
14219 return Opc;
14220}
14221
14222static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14223 tok::TokenKind Kind) {
14224 UnaryOperatorKind Opc;
14225 switch (Kind) {
14226 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp"
, 14226)
;
14227 case tok::plusplus: Opc = UO_PreInc; break;
14228 case tok::minusminus: Opc = UO_PreDec; break;
14229 case tok::amp: Opc = UO_AddrOf; break;
14230 case tok::star: Opc = UO_Deref; break;
14231 case tok::plus: Opc = UO_Plus; break;
14232 case tok::minus: Opc = UO_Minus; break;
14233 case tok::tilde: Opc = UO_Not; break;
14234 case tok::exclaim: Opc = UO_LNot; break;
14235 case tok::kw___real: Opc = UO_Real; break;
14236 case tok::kw___imag: Opc = UO_Imag; break;
14237 case tok::kw___extension__: Opc = UO_Extension; break;
14238 }
14239 return Opc;
14240}
14241
14242/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14243/// This warning suppressed in the event of macro expansions.
14244static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14245 SourceLocation OpLoc, bool IsBuiltin) {
14246 if (S.inTemplateInstantiation())
14247 return;
14248 if (S.isUnevaluatedContext())
14249 return;
14250 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14251 return;
14252 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14253 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14254 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14255 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14256 if (!LHSDeclRef || !RHSDeclRef ||
14257 LHSDeclRef->getLocation().isMacroID() ||
14258 RHSDeclRef->getLocation().isMacroID())
14259 return;
14260 const ValueDecl *LHSDecl =
14261 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14262 const ValueDecl *RHSDecl =
14263 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14264 if (LHSDecl != RHSDecl)
14265 return;
14266 if (LHSDecl->getType().isVolatileQualified())
14267 return;
14268 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14269 if (RefTy->getPointeeType().isVolatileQualified())
14270 return;
14271
14272 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14273 : diag::warn_self_assignment_overloaded)
14274 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14275 << RHSExpr->getSourceRange();
14276}
14277
14278/// Check if a bitwise-& is performed on an Objective-C pointer. This
14279/// is usually indicative of introspection within the Objective-C pointer.
14280static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14281 SourceLocation OpLoc) {
14282 if (!S.getLangOpts().ObjC)
14283 return;
14284
14285 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14286 const Expr *LHS = L.get();
14287 const Expr *RHS = R.get();
14288
14289 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14290 ObjCPointerExpr = LHS;
14291 OtherExpr = RHS;
14292 }
14293 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14294 ObjCPointerExpr = RHS;
14295 OtherExpr = LHS;
14296 }
14297
14298 // This warning is deliberately made very specific to reduce false
14299 // positives with logic that uses '&' for hashing. This logic mainly
14300 // looks for code trying to introspect into tagged pointers, which
14301 // code should generally never do.
14302 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14303 unsigned Diag = diag::warn_objc_pointer_masking;
14304 // Determine if we are introspecting the result of performSelectorXXX.
14305 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14306 // Special case messages to -performSelector and friends, which
14307 // can return non-pointer values boxed in a pointer value.
14308 // Some clients may wish to silence warnings in this subcase.
14309 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14310 Selector S = ME->getSelector();
14311 StringRef SelArg0 = S.getNameForSlot(0);
14312 if (SelArg0.startswith("performSelector"))
14313 Diag = diag::warn_objc_pointer_masking_performSelector;
14314 }
14315
14316 S.Diag(OpLoc, Diag)
14317 << ObjCPointerExpr->getSourceRange();
14318 }
14319}
14320
14321static NamedDecl *getDeclFromExpr(Expr *E) {
14322 if (!E)
14323 return nullptr;
14324 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14325 return DRE->getDecl();
14326 if (auto *ME = dyn_cast<MemberExpr>(E))
14327 return ME->getMemberDecl();
14328 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14329 return IRE->getDecl();
14330 return nullptr;
14331}
14332
14333// This helper function promotes a binary operator's operands (which are of a
14334// half vector type) to a vector of floats and then truncates the result to
14335// a vector of either half or short.
14336static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14337 BinaryOperatorKind Opc, QualType ResultTy,
14338 ExprValueKind VK, ExprObjectKind OK,
14339 bool IsCompAssign, SourceLocation OpLoc,
14340 FPOptionsOverride FPFeatures) {
14341 auto &Context = S.getASTContext();
14342 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", 14344, __extension__ __PRETTY_FUNCTION__
))
14343 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", 14344, __extension__ __PRETTY_FUNCTION__
))
14344 "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", 14344, __extension__ __PRETTY_FUNCTION__
))
;
14345 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", 14347, __extension__ __PRETTY_FUNCTION__
))
14346 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", 14347, __extension__ __PRETTY_FUNCTION__
))
14347 "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", 14347, __extension__ __PRETTY_FUNCTION__
))
;
14348
14349 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14350 QualType BinOpResTy = RHS.get()->getType();
14351
14352 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14353 // change BinOpResTy to a vector of ints.
14354 if (isVector(ResultTy, Context.ShortTy))
14355 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14356
14357 if (IsCompAssign)
14358 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14359 ResultTy, VK, OK, OpLoc, FPFeatures,
14360 BinOpResTy, BinOpResTy);
14361
14362 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14363 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14364 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14365 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14366}
14367
14368static std::pair<ExprResult, ExprResult>
14369CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14370 Expr *RHSExpr) {
14371 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14372 if (!S.Context.isDependenceAllowed()) {
14373 // C cannot handle TypoExpr nodes on either side of a binop because it
14374 // doesn't handle dependent types properly, so make sure any TypoExprs have
14375 // been dealt with before checking the operands.
14376 LHS = S.CorrectDelayedTyposInExpr(LHS);
14377 RHS = S.CorrectDelayedTyposInExpr(
14378 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14379 [Opc, LHS](Expr *E) {
14380 if (Opc != BO_Assign)
14381 return ExprResult(E);
14382 // Avoid correcting the RHS to the same Expr as the LHS.
14383 Decl *D = getDeclFromExpr(E);
14384 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14385 });
14386 }
14387 return std::make_pair(LHS, RHS);
14388}
14389
14390/// Returns true if conversion between vectors of halfs and vectors of floats
14391/// is needed.
14392static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14393 Expr *E0, Expr *E1 = nullptr) {
14394 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14395 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14396 return false;
14397
14398 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14399 QualType Ty = E->IgnoreImplicit()->getType();
14400
14401 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14402 // to vectors of floats. Although the element type of the vectors is __fp16,
14403 // the vectors shouldn't be treated as storage-only types. See the
14404 // discussion here: https://reviews.llvm.org/rG825235c140e7
14405 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14406 if (VT->getVectorKind() == VectorType::NeonVector)
14407 return false;
14408 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14409 }
14410 return false;
14411 };
14412
14413 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14414}
14415
14416/// CreateBuiltinBinOp - Creates a new built-in binary operation with
14417/// operator @p Opc at location @c TokLoc. This routine only supports
14418/// built-in operations; ActOnBinOp handles overloaded operators.
14419ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14420 BinaryOperatorKind Opc,
14421 Expr *LHSExpr, Expr *RHSExpr) {
14422 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14423 // The syntax only allows initializer lists on the RHS of assignment,
14424 // so we don't need to worry about accepting invalid code for
14425 // non-assignment operators.
14426 // C++11 5.17p9:
14427 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14428 // of x = {} is x = T().
14429 InitializationKind Kind = InitializationKind::CreateDirectList(
14430 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14431 InitializedEntity Entity =
14432 InitializedEntity::InitializeTemporary(LHSExpr->getType());
14433 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14434 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14435 if (Init.isInvalid())
14436 return Init;
14437 RHSExpr = Init.get();
14438 }
14439
14440 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14441 QualType ResultTy; // Result type of the binary operator.
14442 // The following two variables are used for compound assignment operators
14443 QualType CompLHSTy; // Type of LHS after promotions for computation
14444 QualType CompResultTy; // Type of computation result
14445 ExprValueKind VK = VK_PRValue;
14446 ExprObjectKind OK = OK_Ordinary;
14447 bool ConvertHalfVec = false;
14448
14449 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14450 if (!LHS.isUsable() || !RHS.isUsable())
14451 return ExprError();
14452
14453 if (getLangOpts().OpenCL) {
14454 QualType LHSTy = LHSExpr->getType();
14455 QualType RHSTy = RHSExpr->getType();
14456 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14457 // the ATOMIC_VAR_INIT macro.
14458 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14459 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14460 if (BO_Assign == Opc)
14461 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14462 else
14463 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14464 return ExprError();
14465 }
14466
14467 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14468 // only with a builtin functions and therefore should be disallowed here.
14469 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14470 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14471 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14472 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14473 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14474 return ExprError();
14475 }
14476 }
14477
14478 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14479 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14480
14481 switch (Opc) {
14482 case BO_Assign:
14483 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14484 if (getLangOpts().CPlusPlus &&
14485 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14486 VK = LHS.get()->getValueKind();
14487 OK = LHS.get()->getObjectKind();
14488 }
14489 if (!ResultTy.isNull()) {
14490 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14491 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14492
14493 // Avoid copying a block to the heap if the block is assigned to a local
14494 // auto variable that is declared in the same scope as the block. This
14495 // optimization is unsafe if the local variable is declared in an outer
14496 // scope. For example:
14497 //
14498 // BlockTy b;
14499 // {
14500 // b = ^{...};
14501 // }
14502 // // It is unsafe to invoke the block here if it wasn't copied to the
14503 // // heap.
14504 // b();
14505
14506 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14507 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14508 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14509 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14510 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14511
14512 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14513 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14514 NTCUC_Assignment, NTCUK_Copy);
14515 }
14516 RecordModifiableNonNullParam(*this, LHS.get());
14517 break;
14518 case BO_PtrMemD:
14519 case BO_PtrMemI:
14520 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14521 Opc == BO_PtrMemI);
14522 break;
14523 case BO_Mul:
14524 case BO_Div:
14525 ConvertHalfVec = true;
14526 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14527 Opc == BO_Div);
14528 break;
14529 case BO_Rem:
14530 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14531 break;
14532 case BO_Add:
14533 ConvertHalfVec = true;
14534 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14535 break;
14536 case BO_Sub:
14537 ConvertHalfVec = true;
14538 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14539 break;
14540 case BO_Shl:
14541 case BO_Shr:
14542 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14543 break;
14544 case BO_LE:
14545 case BO_LT:
14546 case BO_GE:
14547 case BO_GT:
14548 ConvertHalfVec = true;
14549 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14550 break;
14551 case BO_EQ:
14552 case BO_NE:
14553 ConvertHalfVec = true;
14554 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14555 break;
14556 case BO_Cmp:
14557 ConvertHalfVec = true;
14558 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14559 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", 14559, __extension__ __PRETTY_FUNCTION__
))
;
14560 break;
14561 case BO_And:
14562 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14563 LLVM_FALLTHROUGH[[gnu::fallthrough]];
14564 case BO_Xor:
14565 case BO_Or:
14566 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14567 break;
14568 case BO_LAnd:
14569 case BO_LOr:
14570 ConvertHalfVec = true;
14571 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14572 break;
14573 case BO_MulAssign:
14574 case BO_DivAssign:
14575 ConvertHalfVec = true;
14576 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14577 Opc == BO_DivAssign);
14578 CompLHSTy = CompResultTy;
14579 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14580 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14581 break;
14582 case BO_RemAssign:
14583 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14584 CompLHSTy = CompResultTy;
14585 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14586 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14587 break;
14588 case BO_AddAssign:
14589 ConvertHalfVec = true;
14590 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14591 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14592 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14593 break;
14594 case BO_SubAssign:
14595 ConvertHalfVec = true;
14596 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14597 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14598 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14599 break;
14600 case BO_ShlAssign:
14601 case BO_ShrAssign:
14602 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14603 CompLHSTy = CompResultTy;
14604 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14605 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14606 break;
14607 case BO_AndAssign:
14608 case BO_OrAssign: // fallthrough
14609 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14610 LLVM_FALLTHROUGH[[gnu::fallthrough]];
14611 case BO_XorAssign:
14612 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14613 CompLHSTy = CompResultTy;
14614 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14615 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14616 break;
14617 case BO_Comma:
14618 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14619 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14620 VK = RHS.get()->getValueKind();
14621 OK = RHS.get()->getObjectKind();
14622 }
14623 break;
14624 }
14625 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14626 return ExprError();
14627
14628 // Some of the binary operations require promoting operands of half vector to
14629 // float vectors and truncating the result back to half vector. For now, we do
14630 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14631 // arm64).
14632 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", 14635, __extension__ __PRETTY_FUNCTION__
))
14633 (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", 14635, __extension__ __PRETTY_FUNCTION__
))
14634 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", 14635, __extension__ __PRETTY_FUNCTION__
))
14635 "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", 14635, __extension__ __PRETTY_FUNCTION__
))
;
14636 ConvertHalfVec =
14637 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14638
14639 // Check for array bounds violations for both sides of the BinaryOperator
14640 CheckArrayAccess(LHS.get());
14641 CheckArrayAccess(RHS.get());
14642
14643 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14644 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14645 &Context.Idents.get("object_setClass"),
14646 SourceLocation(), LookupOrdinaryName);
14647 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14648 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14649 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14650 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14651 "object_setClass(")
14652 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14653 ",")
14654 << FixItHint::CreateInsertion(RHSLocEnd, ")");
14655 }
14656 else
14657 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14658 }
14659 else if (const ObjCIvarRefExpr *OIRE =
14660 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14661 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14662
14663 // Opc is not a compound assignment if CompResultTy is null.
14664 if (CompResultTy.isNull()) {
14665 if (ConvertHalfVec)
14666 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14667 OpLoc, CurFPFeatureOverrides());
14668 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14669 VK, OK, OpLoc, CurFPFeatureOverrides());
14670 }
14671
14672 // Handle compound assignments.
14673 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14674 OK_ObjCProperty) {
14675 VK = VK_LValue;
14676 OK = LHS.get()->getObjectKind();
14677 }
14678
14679 // The LHS is not converted to the result type for fixed-point compound
14680 // assignment as the common type is computed on demand. Reset the CompLHSTy
14681 // to the LHS type we would have gotten after unary conversions.
14682 if (CompResultTy->isFixedPointType())
14683 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14684
14685 if (ConvertHalfVec)
14686 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14687 OpLoc, CurFPFeatureOverrides());
14688
14689 return CompoundAssignOperator::Create(
14690 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14691 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14692}
14693
14694/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14695/// operators are mixed in a way that suggests that the programmer forgot that
14696/// comparison operators have higher precedence. The most typical example of
14697/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14698static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14699 SourceLocation OpLoc, Expr *LHSExpr,
14700 Expr *RHSExpr) {
14701 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14702 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14703
14704 // Check that one of the sides is a comparison operator and the other isn't.
14705 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14706 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14707 if (isLeftComp == isRightComp)
14708 return;
14709
14710 // Bitwise operations are sometimes used as eager logical ops.
14711 // Don't diagnose this.
14712 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14713 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14714 if (isLeftBitwise || isRightBitwise)
14715 return;
14716
14717 SourceRange DiagRange = isLeftComp
14718 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14719 : SourceRange(OpLoc, RHSExpr->getEndLoc());
14720 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14721 SourceRange ParensRange =
14722 isLeftComp
14723 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14724 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14725
14726 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14727 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14728 SuggestParentheses(Self, OpLoc,
14729 Self.PDiag(diag::note_precedence_silence) << OpStr,
14730 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14731 SuggestParentheses(Self, OpLoc,
14732 Self.PDiag(diag::note_precedence_bitwise_first)
14733 << BinaryOperator::getOpcodeStr(Opc),
14734 ParensRange);
14735}
14736
14737/// It accepts a '&&' expr that is inside a '||' one.
14738/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14739/// in parentheses.
14740static void
14741EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14742 BinaryOperator *Bop) {
14743 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"
, 14743, __extension__ __PRETTY_FUNCTION__))
;
14744 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14745 << Bop->getSourceRange() << OpLoc;
14746 SuggestParentheses(Self, Bop->getOperatorLoc(),
14747 Self.PDiag(diag::note_precedence_silence)
14748 << Bop->getOpcodeStr(),
14749 Bop->getSourceRange());
14750}
14751
14752/// Returns true if the given expression can be evaluated as a constant
14753/// 'true'.
14754static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14755 bool Res;
14756 return !E->isValueDependent() &&
14757 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14758}
14759
14760/// Returns true if the given expression can be evaluated as a constant
14761/// 'false'.
14762static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14763 bool Res;
14764 return !E->isValueDependent() &&
14765 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14766}
14767
14768/// Look for '&&' in the left hand of a '||' expr.
14769static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14770 Expr *LHSExpr, Expr *RHSExpr) {
14771 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14772 if (Bop->getOpcode() == BO_LAnd) {
14773 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14774 if (EvaluatesAsFalse(S, RHSExpr))
14775 return;
14776 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14777 if (!EvaluatesAsTrue(S, Bop->getLHS()))
14778 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14779 } else if (Bop->getOpcode() == BO_LOr) {
14780 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14781 // If it's "a || b && 1 || c" we didn't warn earlier for
14782 // "a || b && 1", but warn now.
14783 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14784 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14785 }
14786 }
14787 }
14788}
14789
14790/// Look for '&&' in the right hand of a '||' expr.
14791static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14792 Expr *LHSExpr, Expr *RHSExpr) {
14793 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14794 if (Bop->getOpcode() == BO_LAnd) {
14795 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14796 if (EvaluatesAsFalse(S, LHSExpr))
14797 return;
14798 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14799 if (!EvaluatesAsTrue(S, Bop->getRHS()))
14800 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14801 }
14802 }
14803}
14804
14805/// Look for bitwise op in the left or right hand of a bitwise op with
14806/// lower precedence and emit a diagnostic together with a fixit hint that wraps
14807/// the '&' expression in parentheses.
14808static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14809 SourceLocation OpLoc, Expr *SubExpr) {
14810 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14811 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14812 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14813 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14814 << Bop->getSourceRange() << OpLoc;
14815 SuggestParentheses(S, Bop->getOperatorLoc(),
14816 S.PDiag(diag::note_precedence_silence)
14817 << Bop->getOpcodeStr(),
14818 Bop->getSourceRange());
14819 }
14820 }
14821}
14822
14823static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14824 Expr *SubExpr, StringRef Shift) {
14825 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14826 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14827 StringRef Op = Bop->getOpcodeStr();
14828 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14829 << Bop->getSourceRange() << OpLoc << Shift << Op;
14830 SuggestParentheses(S, Bop->getOperatorLoc(),
14831 S.PDiag(diag::note_precedence_silence) << Op,
14832 Bop->getSourceRange());
14833 }
14834 }
14835}
14836
14837static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14838 Expr *LHSExpr, Expr *RHSExpr) {
14839 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14840 if (!OCE)
14841 return;
14842
14843 FunctionDecl *FD = OCE->getDirectCallee();
14844 if (!FD || !FD->isOverloadedOperator())
14845 return;
14846
14847 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14848 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14849 return;
14850
14851 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14852 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14853 << (Kind == OO_LessLess);
14854 SuggestParentheses(S, OCE->getOperatorLoc(),
14855 S.PDiag(diag::note_precedence_silence)
14856 << (Kind == OO_LessLess ? "<<" : ">>"),
14857 OCE->getSourceRange());
14858 SuggestParentheses(
14859 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14860 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14861}
14862
14863/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14864/// precedence.
14865static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14866 SourceLocation OpLoc, Expr *LHSExpr,
14867 Expr *RHSExpr){
14868 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14869 if (BinaryOperator::isBitwiseOp(Opc))
14870 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14871
14872 // Diagnose "arg1 & arg2 | arg3"
14873 if ((Opc == BO_Or || Opc == BO_Xor) &&
14874 !OpLoc.isMacroID()/* Don't warn in macros. */) {
14875 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14876 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14877 }
14878
14879 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14880 // We don't warn for 'assert(a || b && "bad")' since this is safe.
14881 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14882 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14883 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14884 }
14885
14886 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14887 || Opc == BO_Shr) {
14888 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14889 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14890 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14891 }
14892
14893 // Warn on overloaded shift operators and comparisons, such as:
14894 // cout << 5 == 4;
14895 if (BinaryOperator::isComparisonOp(Opc))
14896 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14897}
14898
14899// Binary Operators. 'Tok' is the token for the operator.
14900ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14901 tok::TokenKind Kind,
14902 Expr *LHSExpr, Expr *RHSExpr) {
14903 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14904 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", 14904, __extension__ __PRETTY_FUNCTION__
))
;
14905 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", 14905, __extension__ __PRETTY_FUNCTION__
))
;
14906
14907 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14908 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14909
14910 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14911}
14912
14913void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14914 UnresolvedSetImpl &Functions) {
14915 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14916 if (OverOp != OO_None && OverOp != OO_Equal)
14917 LookupOverloadedOperatorName(OverOp, S, Functions);
14918
14919 // In C++20 onwards, we may have a second operator to look up.
14920 if (getLangOpts().CPlusPlus20) {
14921 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14922 LookupOverloadedOperatorName(ExtraOp, S, Functions);
14923 }
14924}
14925
14926/// Build an overloaded binary operator expression in the given scope.
14927static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14928 BinaryOperatorKind Opc,
14929 Expr *LHS, Expr *RHS) {
14930 switch (Opc) {
14931 case BO_Assign:
14932 case BO_DivAssign:
14933 case BO_RemAssign:
14934 case BO_SubAssign:
14935 case BO_AndAssign:
14936 case BO_OrAssign:
14937 case BO_XorAssign:
14938 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14939 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14940 break;
14941 default:
14942 break;
14943 }
14944
14945 // Find all of the overloaded operators visible from this point.
14946 UnresolvedSet<16> Functions;
14947 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14948
14949 // Build the (potentially-overloaded, potentially-dependent)
14950 // binary operation.
14951 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14952}
14953
14954ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14955 BinaryOperatorKind Opc,
14956 Expr *LHSExpr, Expr *RHSExpr) {
14957 ExprResult LHS, RHS;
14958 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14959 if (!LHS.isUsable() || !RHS.isUsable())
14960 return ExprError();
14961 LHSExpr = LHS.get();
14962 RHSExpr = RHS.get();
14963
14964 // We want to end up calling one of checkPseudoObjectAssignment
14965 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14966 // both expressions are overloadable or either is type-dependent),
14967 // or CreateBuiltinBinOp (in any other case). We also want to get
14968 // any placeholder types out of the way.
14969
14970 // Handle pseudo-objects in the LHS.
14971 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14972 // Assignments with a pseudo-object l-value need special analysis.
14973 if (pty->getKind() == BuiltinType::PseudoObject &&
14974 BinaryOperator::isAssignmentOp(Opc))
14975 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14976
14977 // Don't resolve overloads if the other type is overloadable.
14978 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14979 // We can't actually test that if we still have a placeholder,
14980 // though. Fortunately, none of the exceptions we see in that
14981 // code below are valid when the LHS is an overload set. Note
14982 // that an overload set can be dependently-typed, but it never
14983 // instantiates to having an overloadable type.
14984 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14985 if (resolvedRHS.isInvalid()) return ExprError();
14986 RHSExpr = resolvedRHS.get();
14987
14988 if (RHSExpr->isTypeDependent() ||
14989 RHSExpr->getType()->isOverloadableType())
14990 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14991 }
14992
14993 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14994 // template, diagnose the missing 'template' keyword instead of diagnosing
14995 // an invalid use of a bound member function.
14996 //
14997 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14998 // to C++1z [over.over]/1.4, but we already checked for that case above.
14999 if (Opc == BO_LT && inTemplateInstantiation() &&
15000 (pty->getKind() == BuiltinType::BoundMember ||
15001 pty->getKind() == BuiltinType::Overload)) {
15002 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15003 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15004 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
15005 return isa<FunctionTemplateDecl>(ND);
15006 })) {
15007 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15008 : OE->getNameLoc(),
15009 diag::err_template_kw_missing)
15010 << OE->getName().getAsString() << "";
15011 return ExprError();
15012 }
15013 }
15014
15015 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15016 if (LHS.isInvalid()) return ExprError();
15017 LHSExpr = LHS.get();
15018 }
15019
15020 // Handle pseudo-objects in the RHS.
15021 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15022 // An overload in the RHS can potentially be resolved by the type
15023 // being assigned to.
15024 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15025 if (getLangOpts().CPlusPlus &&
15026 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15027 LHSExpr->getType()->isOverloadableType()))
15028 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15029
15030 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15031 }
15032
15033 // Don't resolve overloads if the other type is overloadable.
15034 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15035 LHSExpr->getType()->isOverloadableType())
15036 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15037
15038 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15039 if (!resolvedRHS.isUsable()) return ExprError();
15040 RHSExpr = resolvedRHS.get();
15041 }
15042
15043 if (getLangOpts().CPlusPlus) {
15044 // If either expression is type-dependent, always build an
15045 // overloaded op.
15046 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15047 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15048
15049 // Otherwise, build an overloaded op if either expression has an
15050 // overloadable type.
15051 if (LHSExpr->getType()->isOverloadableType() ||
15052 RHSExpr->getType()->isOverloadableType())
15053 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15054 }
15055
15056 if (getLangOpts().RecoveryAST &&
15057 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15058 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 15058, __extension__ __PRETTY_FUNCTION__))
;
15059 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", 15060, __extension__ __PRETTY_FUNCTION__
))
15060 "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", 15060, __extension__ __PRETTY_FUNCTION__
))
;
15061 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15062 // C [6.15.16] p3:
15063 // An assignment expression has the value of the left operand after the
15064 // assignment, but is not an lvalue.
15065 return CompoundAssignOperator::Create(
15066 Context, LHSExpr, RHSExpr, Opc,
15067 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15068 OpLoc, CurFPFeatureOverrides());
15069 QualType ResultType;
15070 switch (Opc) {
15071 case BO_Assign:
15072 ResultType = LHSExpr->getType().getUnqualifiedType();
15073 break;
15074 case BO_LT:
15075 case BO_GT:
15076 case BO_LE:
15077 case BO_GE:
15078 case BO_EQ:
15079 case BO_NE:
15080 case BO_LAnd:
15081 case BO_LOr:
15082 // These operators have a fixed result type regardless of operands.
15083 ResultType = Context.IntTy;
15084 break;
15085 case BO_Comma:
15086 ResultType = RHSExpr->getType();
15087 break;
15088 default:
15089 ResultType = Context.DependentTy;
15090 break;
15091 }
15092 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15093 VK_PRValue, OK_Ordinary, OpLoc,
15094 CurFPFeatureOverrides());
15095 }
15096
15097 // Build a built-in binary operation.
15098 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15099}
15100
15101static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15102 if (T.isNull() || T->isDependentType())
15103 return false;
15104
15105 if (!T->isPromotableIntegerType())
15106 return true;
15107
15108 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15109}
15110
15111ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15112 UnaryOperatorKind Opc,
15113 Expr *InputExpr) {
15114 ExprResult Input = InputExpr;
15115 ExprValueKind VK = VK_PRValue;
15116 ExprObjectKind OK = OK_Ordinary;
15117 QualType resultType;
15118 bool CanOverflow = false;
15119
15120 bool ConvertHalfVec = false;
15121 if (getLangOpts().OpenCL) {
15122 QualType Ty = InputExpr->getType();
15123 // The only legal unary operation for atomics is '&'.
15124 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15125 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15126 // only with a builtin functions and therefore should be disallowed here.
15127 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15128 || Ty->isBlockPointerType())) {
15129 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15130 << InputExpr->getType()
15131 << Input.get()->getSourceRange());
15132 }
15133 }
15134
15135 switch (Opc) {
15136 case UO_PreInc:
15137 case UO_PreDec:
15138 case UO_PostInc:
15139 case UO_PostDec:
15140 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15141 OpLoc,
15142 Opc == UO_PreInc ||
15143 Opc == UO_PostInc,
15144 Opc == UO_PreInc ||
15145 Opc == UO_PreDec);
15146 CanOverflow = isOverflowingIntegerType(Context, resultType);
15147 break;
15148 case UO_AddrOf:
15149 resultType = CheckAddressOfOperand(Input, OpLoc);
15150 CheckAddressOfNoDeref(InputExpr);
15151 RecordModifiableNonNullParam(*this, InputExpr);
15152 break;
15153 case UO_Deref: {
15154 Input = DefaultFunctionArrayLvalueConversion(Input.get());
15155 if (Input.isInvalid()) return ExprError();
15156 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
15157 break;
15158 }
15159 case UO_Plus:
15160 case UO_Minus:
15161 CanOverflow = Opc == UO_Minus &&
15162 isOverflowingIntegerType(Context, Input.get()->getType());
15163 Input = UsualUnaryConversions(Input.get());
15164 if (Input.isInvalid()) return ExprError();
15165 // Unary plus and minus require promoting an operand of half vector to a
15166 // float vector and truncating the result back to a half vector. For now, we
15167 // do this only when HalfArgsAndReturns is set (that is, when the target is
15168 // arm or arm64).
15169 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15170
15171 // If the operand is a half vector, promote it to a float vector.
15172 if (ConvertHalfVec)
15173 Input = convertVector(Input.get(), Context.FloatTy, *this);
15174 resultType = Input.get()->getType();
15175 if (resultType->isDependentType())
15176 break;
15177 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15178 break;
15179 else if (resultType->isVectorType() &&
15180 // The z vector extensions don't allow + or - with bool vectors.
15181 (!Context.getLangOpts().ZVector ||
15182 resultType->castAs<VectorType>()->getVectorKind() !=
15183 VectorType::AltiVecBool))
15184 break;
15185 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15186 Opc == UO_Plus &&
15187 resultType->isPointerType())
15188 break;
15189
15190 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15191 << resultType << Input.get()->getSourceRange());
15192
15193 case UO_Not: // bitwise complement
15194 Input = UsualUnaryConversions(Input.get());
15195 if (Input.isInvalid())
15196 return ExprError();
15197 resultType = Input.get()->getType();
15198 if (resultType->isDependentType())
15199 break;
15200 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15201 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15202 // C99 does not support '~' for complex conjugation.
15203 Diag(OpLoc, diag::ext_integer_complement_complex)
15204 << resultType << Input.get()->getSourceRange();
15205 else if (resultType->hasIntegerRepresentation())
15206 break;
15207 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15208 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15209 // on vector float types.
15210 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15211 if (!T->isIntegerType())
15212 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15213 << resultType << Input.get()->getSourceRange());
15214 } else {
15215 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15216 << resultType << Input.get()->getSourceRange());
15217 }
15218 break;
15219
15220 case UO_LNot: // logical negation
15221 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15222 Input = DefaultFunctionArrayLvalueConversion(Input.get());
15223 if (Input.isInvalid()) return ExprError();
15224 resultType = Input.get()->getType();
15225
15226 // Though we still have to promote half FP to float...
15227 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15228 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15229 resultType = Context.FloatTy;
15230 }
15231
15232 if (resultType->isDependentType())
15233 break;
15234 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15235 // C99 6.5.3.3p1: ok, fallthrough;
15236 if (Context.getLangOpts().CPlusPlus) {
15237 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15238 // operand contextually converted to bool.
15239 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15240 ScalarTypeToBooleanCastKind(resultType));
15241 } else if (Context.getLangOpts().OpenCL &&
15242 Context.getLangOpts().OpenCLVersion < 120) {
15243 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15244 // operate on scalar float types.
15245 if (!resultType->isIntegerType() && !resultType->isPointerType())
15246 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15247 << resultType << Input.get()->getSourceRange());
15248 }
15249 } else if (resultType->isExtVectorType()) {
15250 if (Context.getLangOpts().OpenCL &&
15251 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15252 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15253 // operate on vector float types.
15254 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15255 if (!T->isIntegerType())
15256 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15257 << resultType << Input.get()->getSourceRange());
15258 }
15259 // Vector logical not returns the signed variant of the operand type.
15260 resultType = GetSignedVectorType(resultType);
15261 break;
15262 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15263 const VectorType *VTy = resultType->castAs<VectorType>();
15264 if (VTy->getVectorKind() != VectorType::GenericVector)
15265 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15266 << resultType << Input.get()->getSourceRange());
15267
15268 // Vector logical not returns the signed variant of the operand type.
15269 resultType = GetSignedVectorType(resultType);
15270 break;
15271 } else {
15272 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15273 << resultType << Input.get()->getSourceRange());
15274 }
15275
15276 // LNot always has type int. C99 6.5.3.3p5.
15277 // In C++, it's bool. C++ 5.3.1p8
15278 resultType = Context.getLogicalOperationType();
15279 break;
15280 case UO_Real:
15281 case UO_Imag:
15282 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15283 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15284 // complex l-values to ordinary l-values and all other values to r-values.
15285 if (Input.isInvalid()) return ExprError();
15286 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15287 if (Input.get()->isGLValue() &&
15288 Input.get()->getObjectKind() == OK_Ordinary)
15289 VK = Input.get()->getValueKind();
15290 } else if (!getLangOpts().CPlusPlus) {
15291 // In C, a volatile scalar is read by __imag. In C++, it is not.
15292 Input = DefaultLvalueConversion(Input.get());
15293 }
15294 break;
15295 case UO_Extension:
15296 resultType = Input.get()->getType();
15297 VK = Input.get()->getValueKind();
15298 OK = Input.get()->getObjectKind();
15299 break;
15300 case UO_Coawait:
15301 // It's unnecessary to represent the pass-through operator co_await in the
15302 // AST; just return the input expression instead.
15303 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", 15305, __extension__ __PRETTY_FUNCTION__
))
15304 "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", 15305, __extension__ __PRETTY_FUNCTION__
))
15305 "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", 15305, __extension__ __PRETTY_FUNCTION__
))
;
15306 return Input;
15307 }
15308 if (resultType.isNull() || Input.isInvalid())
15309 return ExprError();
15310
15311 // Check for array bounds violations in the operand of the UnaryOperator,
15312 // except for the '*' and '&' operators that have to be handled specially
15313 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15314 // that are explicitly defined as valid by the standard).
15315 if (Opc != UO_AddrOf && Opc != UO_Deref)
15316 CheckArrayAccess(Input.get());
15317
15318 auto *UO =
15319 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15320 OpLoc, CanOverflow, CurFPFeatureOverrides());
15321
15322 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15323 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15324 !isUnevaluatedContext())
15325 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15326
15327 // Convert the result back to a half vector.
15328 if (ConvertHalfVec)
15329 return convertVector(UO, Context.HalfTy, *this);
15330 return UO;
15331}
15332
15333/// Determine whether the given expression is a qualified member
15334/// access expression, of a form that could be turned into a pointer to member
15335/// with the address-of operator.
15336bool Sema::isQualifiedMemberAccess(Expr *E) {
15337 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15338 if (!DRE->getQualifier())
15339 return false;
15340
15341 ValueDecl *VD = DRE->getDecl();
15342 if (!VD->isCXXClassMember())
15343 return false;
15344
15345 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15346 return true;
15347 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15348 return Method->isInstance();
15349
15350 return false;
15351 }
15352
15353 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15354 if (!ULE->getQualifier())
15355 return false;
15356
15357 for (NamedDecl *D : ULE->decls()) {
15358 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15359 if (Method->isInstance())
15360 return true;
15361 } else {
15362 // Overload set does not contain methods.
15363 break;
15364 }
15365 }
15366
15367 return false;
15368 }
15369
15370 return false;
15371}
15372
15373ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15374 UnaryOperatorKind Opc, Expr *Input) {
15375 // First things first: handle placeholders so that the
15376 // overloaded-operator check considers the right type.
15377 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15378 // Increment and decrement of pseudo-object references.
15379 if (pty->getKind() == BuiltinType::PseudoObject &&
15380 UnaryOperator::isIncrementDecrementOp(Opc))
15381 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15382
15383 // extension is always a builtin operator.
15384 if (Opc == UO_Extension)
15385 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15386
15387 // & gets special logic for several kinds of placeholder.
15388 // The builtin code knows what to do.
15389 if (Opc == UO_AddrOf &&
15390 (pty->getKind() == BuiltinType::Overload ||
15391 pty->getKind() == BuiltinType::UnknownAny ||
15392 pty->getKind() == BuiltinType::BoundMember))
15393 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15394
15395 // Anything else needs to be handled now.
15396 ExprResult Result = CheckPlaceholderExpr(Input);
15397 if (Result.isInvalid()) return ExprError();
15398 Input = Result.get();
15399 }
15400
15401 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15402 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15403 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15404 // Find all of the overloaded operators visible from this point.
15405 UnresolvedSet<16> Functions;
15406 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15407 if (S && OverOp != OO_None)
15408 LookupOverloadedOperatorName(OverOp, S, Functions);
15409
15410 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15411 }
15412
15413 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15414}
15415
15416// Unary Operators. 'Tok' is the token for the operator.
15417ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15418 tok::TokenKind Op, Expr *Input) {
15419 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15420}
15421
15422/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15423ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15424 LabelDecl *TheDecl) {
15425 TheDecl->markUsed(Context);
15426 // Create the AST node. The address of a label always has type 'void*'.
15427 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15428 Context.getPointerType(Context.VoidTy));
15429}
15430
15431void Sema::ActOnStartStmtExpr() {
15432 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15433}
15434
15435void Sema::ActOnStmtExprError() {
15436 // Note that function is also called by TreeTransform when leaving a
15437 // StmtExpr scope without rebuilding anything.
15438
15439 DiscardCleanupsInEvaluationContext();
15440 PopExpressionEvaluationContext();
15441}
15442
15443ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15444 SourceLocation RPLoc) {
15445 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15446}
15447
15448ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15449 SourceLocation RPLoc, unsigned TemplateDepth) {
15450 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", 15450, __extension__ __PRETTY_FUNCTION__
))
;
15451 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15452
15453 if (hasAnyUnrecoverableErrorsInThisFunction())
15454 DiscardCleanupsInEvaluationContext();
15455 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", 15456, __extension__ __PRETTY_FUNCTION__
))
15456 "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", 15456, __extension__ __PRETTY_FUNCTION__
))
;
15457 PopExpressionEvaluationContext();
15458
15459 // FIXME: there are a variety of strange constraints to enforce here, for
15460 // example, it is not possible to goto into a stmt expression apparently.
15461 // More semantic analysis is needed.
15462
15463 // If there are sub-stmts in the compound stmt, take the type of the last one
15464 // as the type of the stmtexpr.
15465 QualType Ty = Context.VoidTy;
15466 bool StmtExprMayBindToTemp = false;
15467 if (!Compound->body_empty()) {
15468 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15469 if (const auto *LastStmt =
15470 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15471 if (const Expr *Value = LastStmt->getExprStmt()) {
15472 StmtExprMayBindToTemp = true;
15473 Ty = Value->getType();
15474 }
15475 }
15476 }
15477
15478 // FIXME: Check that expression type is complete/non-abstract; statement
15479 // expressions are not lvalues.
15480 Expr *ResStmtExpr =
15481 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15482 if (StmtExprMayBindToTemp)
15483 return MaybeBindToTemporary(ResStmtExpr);
15484 return ResStmtExpr;
15485}
15486
15487ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15488 if (ER.isInvalid())
15489 return ExprError();
15490
15491 // Do function/array conversion on the last expression, but not
15492 // lvalue-to-rvalue. However, initialize an unqualified type.
15493 ER = DefaultFunctionArrayConversion(ER.get());
15494 if (ER.isInvalid())
15495 return ExprError();
15496 Expr *E = ER.get();
15497
15498 if (E->isTypeDependent())
15499 return E;
15500
15501 // In ARC, if the final expression ends in a consume, splice
15502 // the consume out and bind it later. In the alternate case
15503 // (when dealing with a retainable type), the result
15504 // initialization will create a produce. In both cases the
15505 // result will be +1, and we'll need to balance that out with
15506 // a bind.
15507 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15508 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15509 return Cast->getSubExpr();
15510
15511 // FIXME: Provide a better location for the initialization.
15512 return PerformCopyInitialization(
15513 InitializedEntity::InitializeStmtExprResult(
15514 E->getBeginLoc(), E->getType().getUnqualifiedType()),
15515 SourceLocation(), E);
15516}
15517
15518ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15519 TypeSourceInfo *TInfo,
15520 ArrayRef<OffsetOfComponent> Components,
15521 SourceLocation RParenLoc) {
15522 QualType ArgTy = TInfo->getType();
15523 bool Dependent = ArgTy->isDependentType();
15524 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15525
15526 // We must have at least one component that refers to the type, and the first
15527 // one is known to be a field designator. Verify that the ArgTy represents
15528 // a struct/union/class.
15529 if (!Dependent && !ArgTy->isRecordType())
15530 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15531 << ArgTy << TypeRange);
15532
15533 // Type must be complete per C99 7.17p3 because a declaring a variable
15534 // with an incomplete type would be ill-formed.
15535 if (!Dependent
15536 && RequireCompleteType(BuiltinLoc, ArgTy,
15537 diag::err_offsetof_incomplete_type, TypeRange))
15538 return ExprError();
15539
15540 bool DidWarnAboutNonPOD = false;
15541 QualType CurrentType = ArgTy;
15542 SmallVector<OffsetOfNode, 4> Comps;
15543 SmallVector<Expr*, 4> Exprs;
15544 for (const OffsetOfComponent &OC : Components) {
15545 if (OC.isBrackets) {
15546 // Offset of an array sub-field. TODO: Should we allow vector elements?
15547 if (!CurrentType->isDependentType()) {
15548 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15549 if(!AT)
15550 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15551 << CurrentType);
15552 CurrentType = AT->getElementType();
15553 } else
15554 CurrentType = Context.DependentTy;
15555
15556 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15557 if (IdxRval.isInvalid())
15558 return ExprError();
15559 Expr *Idx = IdxRval.get();
15560
15561 // The expression must be an integral expression.
15562 // FIXME: An integral constant expression?
15563 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15564 !Idx->getType()->isIntegerType())
15565 return ExprError(
15566 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15567 << Idx->getSourceRange());
15568
15569 // Record this array index.
15570 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15571 Exprs.push_back(Idx);
15572 continue;
15573 }
15574
15575 // Offset of a field.
15576 if (CurrentType->isDependentType()) {
15577 // We have the offset of a field, but we can't look into the dependent
15578 // type. Just record the identifier of the field.
15579 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15580 CurrentType = Context.DependentTy;
15581 continue;
15582 }
15583
15584 // We need to have a complete type to look into.
15585 if (RequireCompleteType(OC.LocStart, CurrentType,
15586 diag::err_offsetof_incomplete_type))
15587 return ExprError();
15588
15589 // Look for the designated field.
15590 const RecordType *RC = CurrentType->getAs<RecordType>();
15591 if (!RC)
15592 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15593 << CurrentType);
15594 RecordDecl *RD = RC->getDecl();
15595
15596 // C++ [lib.support.types]p5:
15597 // The macro offsetof accepts a restricted set of type arguments in this
15598 // International Standard. type shall be a POD structure or a POD union
15599 // (clause 9).
15600 // C++11 [support.types]p4:
15601 // If type is not a standard-layout class (Clause 9), the results are
15602 // undefined.
15603 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15604 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15605 unsigned DiagID =
15606 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15607 : diag::ext_offsetof_non_pod_type;
15608
15609 if (!IsSafe && !DidWarnAboutNonPOD &&
15610 DiagRuntimeBehavior(BuiltinLoc, nullptr,
15611 PDiag(DiagID)
15612 << SourceRange(Components[0].LocStart, OC.LocEnd)
15613 << CurrentType))
15614 DidWarnAboutNonPOD = true;
15615 }
15616
15617 // Look for the field.
15618 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15619 LookupQualifiedName(R, RD);
15620 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15621 IndirectFieldDecl *IndirectMemberDecl = nullptr;
15622 if (!MemberDecl) {
15623 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15624 MemberDecl = IndirectMemberDecl->getAnonField();
15625 }
15626
15627 if (!MemberDecl)
15628 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15629 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15630 OC.LocEnd));
15631
15632 // C99 7.17p3:
15633 // (If the specified member is a bit-field, the behavior is undefined.)
15634 //
15635 // We diagnose this as an error.
15636 if (MemberDecl->isBitField()) {
15637 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15638 << MemberDecl->getDeclName()
15639 << SourceRange(BuiltinLoc, RParenLoc);
15640 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15641 return ExprError();
15642 }
15643
15644 RecordDecl *Parent = MemberDecl->getParent();
15645 if (IndirectMemberDecl)
15646 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15647
15648 // If the member was found in a base class, introduce OffsetOfNodes for
15649 // the base class indirections.
15650 CXXBasePaths Paths;
15651 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15652 Paths)) {
15653 if (Paths.getDetectedVirtual()) {
15654 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15655 << MemberDecl->getDeclName()
15656 << SourceRange(BuiltinLoc, RParenLoc);
15657 return ExprError();
15658 }
15659
15660 CXXBasePath &Path = Paths.front();
15661 for (const CXXBasePathElement &B : Path)
15662 Comps.push_back(OffsetOfNode(B.Base));
15663 }
15664
15665 if (IndirectMemberDecl) {
15666 for (auto *FI : IndirectMemberDecl->chain()) {
15667 assert(isa<FieldDecl>(FI))(static_cast <bool> (isa<FieldDecl>(FI)) ? void (
0) : __assert_fail ("isa<FieldDecl>(FI)", "clang/lib/Sema/SemaExpr.cpp"
, 15667, __extension__ __PRETTY_FUNCTION__))
;
15668 Comps.push_back(OffsetOfNode(OC.LocStart,
15669 cast<FieldDecl>(FI), OC.LocEnd));
15670 }
15671 } else
15672 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15673
15674 CurrentType = MemberDecl->getType().getNonReferenceType();
15675 }
15676
15677 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15678 Comps, Exprs, RParenLoc);
15679}
15680
15681ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15682 SourceLocation BuiltinLoc,
15683 SourceLocation TypeLoc,
15684 ParsedType ParsedArgTy,
15685 ArrayRef<OffsetOfComponent> Components,
15686 SourceLocation RParenLoc) {
15687
15688 TypeSourceInfo *ArgTInfo;
15689 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15690 if (ArgTy.isNull())
15691 return ExprError();
15692
15693 if (!ArgTInfo)
15694 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15695
15696 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15697}
15698
15699
15700ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15701 Expr *CondExpr,
15702 Expr *LHSExpr, Expr *RHSExpr,
15703 SourceLocation RPLoc) {
15704 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", 15704, __extension__ __PRETTY_FUNCTION__
))
;
15705
15706 ExprValueKind VK = VK_PRValue;
15707 ExprObjectKind OK = OK_Ordinary;
15708 QualType resType;
15709 bool CondIsTrue = false;
15710 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15711 resType = Context.DependentTy;
15712 } else {
15713 // The conditional expression is required to be a constant expression.
15714 llvm::APSInt condEval(32);
15715 ExprResult CondICE = VerifyIntegerConstantExpression(
15716 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15717 if (CondICE.isInvalid())
15718 return ExprError();
15719 CondExpr = CondICE.get();
15720 CondIsTrue = condEval.getZExtValue();
15721
15722 // If the condition is > zero, then the AST type is the same as the LHSExpr.
15723 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15724
15725 resType = ActiveExpr->getType();
15726 VK = ActiveExpr->getValueKind();
15727 OK = ActiveExpr->getObjectKind();
15728 }
15729
15730 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15731 resType, VK, OK, RPLoc, CondIsTrue);
15732}
15733
15734//===----------------------------------------------------------------------===//
15735// Clang Extensions.
15736//===----------------------------------------------------------------------===//
15737
15738/// ActOnBlockStart - This callback is invoked when a block literal is started.
15739void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15740 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15741
15742 if (LangOpts.CPlusPlus) {
15743 MangleNumberingContext *MCtx;
15744 Decl *ManglingContextDecl;
15745 std::tie(MCtx, ManglingContextDecl) =
15746 getCurrentMangleNumberContext(Block->getDeclContext());
15747 if (MCtx) {
15748 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15749 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15750 }
15751 }
15752
15753 PushBlockScope(CurScope, Block);
15754 CurContext->addDecl(Block);
15755 if (CurScope)
15756 PushDeclContext(CurScope, Block);
15757 else
15758 CurContext = Block;
15759
15760 getCurBlock()->HasImplicitReturnType = true;
15761
15762 // Enter a new evaluation context to insulate the block from any
15763 // cleanups from the enclosing full-expression.
15764 PushExpressionEvaluationContext(
15765 ExpressionEvaluationContext::PotentiallyEvaluated);
15766}
15767
15768void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15769 Scope *CurScope) {
15770 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", 15771, __extension__ __PRETTY_FUNCTION__
))
15771 "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", 15771, __extension__ __PRETTY_FUNCTION__
))
;
15772 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", 15772, __extension__ __PRETTY_FUNCTION__
))
;
15773 BlockScopeInfo *CurBlock = getCurBlock();
15774
15775 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15776 QualType T = Sig->getType();
15777
15778 // FIXME: We should allow unexpanded parameter packs here, but that would,
15779 // in turn, make the block expression contain unexpanded parameter packs.
15780 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15781 // Drop the parameters.
15782 FunctionProtoType::ExtProtoInfo EPI;
15783 EPI.HasTrailingReturn = false;
15784 EPI.TypeQuals.addConst();
15785 T = Context.getFunctionType(Context.DependentTy, None, EPI);
15786 Sig = Context.getTrivialTypeSourceInfo(T);
15787 }
15788
15789 // GetTypeForDeclarator always produces a function type for a block
15790 // literal signature. Furthermore, it is always a FunctionProtoType
15791 // unless the function was written with a typedef.
15792 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", 15793, __extension__ __PRETTY_FUNCTION__
))
15793 "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", 15793, __extension__ __PRETTY_FUNCTION__
))
;
15794
15795 // Look for an explicit signature in that function type.
15796 FunctionProtoTypeLoc ExplicitSignature;
15797
15798 if ((ExplicitSignature = Sig->getTypeLoc()
15799 .getAsAdjusted<FunctionProtoTypeLoc>())) {
15800
15801 // Check whether that explicit signature was synthesized by
15802 // GetTypeForDeclarator. If so, don't save that as part of the
15803 // written signature.
15804 if (ExplicitSignature.getLocalRangeBegin() ==
15805 ExplicitSignature.getLocalRangeEnd()) {
15806 // This would be much cheaper if we stored TypeLocs instead of
15807 // TypeSourceInfos.
15808 TypeLoc Result = ExplicitSignature.getReturnLoc();
15809 unsigned Size = Result.getFullDataSize();
15810 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15811 Sig->getTypeLoc().initializeFullCopy(Result, Size);
15812
15813 ExplicitSignature = FunctionProtoTypeLoc();
15814 }
15815 }
15816
15817 CurBlock->TheDecl->setSignatureAsWritten(Sig);
15818 CurBlock->FunctionType = T;
15819
15820 const auto *Fn = T->castAs<FunctionType>();
15821 QualType RetTy = Fn->getReturnType();
15822 bool isVariadic =
15823 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15824
15825 CurBlock->TheDecl->setIsVariadic(isVariadic);
15826
15827 // Context.DependentTy is used as a placeholder for a missing block
15828 // return type. TODO: what should we do with declarators like:
15829 // ^ * { ... }
15830 // If the answer is "apply template argument deduction"....
15831 if (RetTy != Context.DependentTy) {
15832 CurBlock->ReturnType = RetTy;
15833 CurBlock->TheDecl->setBlockMissingReturnType(false);
15834 CurBlock->HasImplicitReturnType = false;
15835 }
15836
15837 // Push block parameters from the declarator if we had them.
15838 SmallVector<ParmVarDecl*, 8> Params;
15839 if (ExplicitSignature) {
15840 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15841 ParmVarDecl *Param = ExplicitSignature.getParam(I);
15842 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15843 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15844 // Diagnose this as an extension in C17 and earlier.
15845 if (!getLangOpts().C2x)
15846 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15847 }
15848 Params.push_back(Param);
15849 }
15850
15851 // Fake up parameter variables if we have a typedef, like
15852 // ^ fntype { ... }
15853 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15854 for (const auto &I : Fn->param_types()) {
15855 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15856 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15857 Params.push_back(Param);
15858 }
15859 }
15860
15861 // Set the parameters on the block decl.
15862 if (!Params.empty()) {
15863 CurBlock->TheDecl->setParams(Params);
15864 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15865 /*CheckParameterNames=*/false);
15866 }
15867
15868 // Finally we can process decl attributes.
15869 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15870
15871 // Put the parameter variables in scope.
15872 for (auto AI : CurBlock->TheDecl->parameters()) {
15873 AI->setOwningFunction(CurBlock->TheDecl);
15874
15875 // If this has an identifier, add it to the scope stack.
15876 if (AI->getIdentifier()) {
15877 CheckShadow(CurBlock->TheScope, AI);
15878
15879 PushOnScopeChains(AI, CurBlock->TheScope);
15880 }
15881 }
15882}
15883
15884/// ActOnBlockError - If there is an error parsing a block, this callback
15885/// is invoked to pop the information about the block from the action impl.
15886void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15887 // Leave the expression-evaluation context.
15888 DiscardCleanupsInEvaluationContext();
15889 PopExpressionEvaluationContext();
15890
15891 // Pop off CurBlock, handle nested blocks.
15892 PopDeclContext();
15893 PopFunctionScopeInfo();
15894}
15895
15896/// ActOnBlockStmtExpr - This is called when the body of a block statement
15897/// literal was successfully completed. ^(int x){...}
15898ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15899 Stmt *Body, Scope *CurScope) {
15900 // If blocks are disabled, emit an error.
15901 if (!LangOpts.Blocks)
15902 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15903
15904 // Leave the expression-evaluation context.
15905 if (hasAnyUnrecoverableErrorsInThisFunction())
15906 DiscardCleanupsInEvaluationContext();
15907 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", 15908, __extension__ __PRETTY_FUNCTION__
))
15908 "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", 15908, __extension__ __PRETTY_FUNCTION__
))
;
15909 PopExpressionEvaluationContext();
15910
15911 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15912 BlockDecl *BD = BSI->TheDecl;
15913
15914 if (BSI->HasImplicitReturnType)
15915 deduceClosureReturnType(*BSI);
15916
15917 QualType RetTy = Context.VoidTy;
15918 if (!BSI->ReturnType.isNull())
15919 RetTy = BSI->ReturnType;
15920
15921 bool NoReturn = BD->hasAttr<NoReturnAttr>();
15922 QualType BlockTy;
15923
15924 // If the user wrote a function type in some form, try to use that.
15925 if (!BSI->FunctionType.isNull()) {
15926 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15927
15928 FunctionType::ExtInfo Ext = FTy->getExtInfo();
15929 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15930
15931 // Turn protoless block types into nullary block types.
15932 if (isa<FunctionNoProtoType>(FTy)) {
15933 FunctionProtoType::ExtProtoInfo EPI;
15934 EPI.ExtInfo = Ext;
15935 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15936
15937 // Otherwise, if we don't need to change anything about the function type,
15938 // preserve its sugar structure.
15939 } else if (FTy->getReturnType() == RetTy &&
15940 (!NoReturn || FTy->getNoReturnAttr())) {
15941 BlockTy = BSI->FunctionType;
15942
15943 // Otherwise, make the minimal modifications to the function type.
15944 } else {
15945 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15946 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15947 EPI.TypeQuals = Qualifiers();
15948 EPI.ExtInfo = Ext;
15949 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15950 }
15951
15952 // If we don't have a function type, just build one from nothing.
15953 } else {
15954 FunctionProtoType::ExtProtoInfo EPI;
15955 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15956 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15957 }
15958
15959 DiagnoseUnusedParameters(BD->parameters());
15960 BlockTy = Context.getBlockPointerType(BlockTy);
15961
15962 // If needed, diagnose invalid gotos and switches in the block.
15963 if (getCurFunction()->NeedsScopeChecking() &&
15964 !PP.isCodeCompletionEnabled())
15965 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15966
15967 BD->setBody(cast<CompoundStmt>(Body));
15968
15969 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15970 DiagnoseUnguardedAvailabilityViolations(BD);
15971
15972 // Try to apply the named return value optimization. We have to check again
15973 // if we can do this, though, because blocks keep return statements around
15974 // to deduce an implicit return type.
15975 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15976 !BD->isDependentContext())
15977 computeNRVO(Body, BSI);
15978
15979 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15980 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15981 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15982 NTCUK_Destruct|NTCUK_Copy);
15983
15984 PopDeclContext();
15985
15986 // Set the captured variables on the block.
15987 SmallVector<BlockDecl::Capture, 4> Captures;
15988 for (Capture &Cap : BSI->Captures) {
15989 if (Cap.isInvalid() || Cap.isThisCapture())
15990 continue;
15991
15992 VarDecl *Var = Cap.getVariable();
15993 Expr *CopyExpr = nullptr;
15994 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15995 if (const RecordType *Record =
15996 Cap.getCaptureType()->getAs<RecordType>()) {
15997 // The capture logic needs the destructor, so make sure we mark it.
15998 // Usually this is unnecessary because most local variables have
15999 // their destructors marked at declaration time, but parameters are
16000 // an exception because it's technically only the call site that
16001 // actually requires the destructor.
16002 if (isa<ParmVarDecl>(Var))
16003 FinalizeVarWithDestructor(Var, Record);
16004
16005 // Enter a separate potentially-evaluated context while building block
16006 // initializers to isolate their cleanups from those of the block
16007 // itself.
16008 // FIXME: Is this appropriate even when the block itself occurs in an
16009 // unevaluated operand?
16010 EnterExpressionEvaluationContext EvalContext(
16011 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16012
16013 SourceLocation Loc = Cap.getLocation();
16014
16015 ExprResult Result = BuildDeclarationNameExpr(
16016 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16017
16018 // According to the blocks spec, the capture of a variable from
16019 // the stack requires a const copy constructor. This is not true
16020 // of the copy/move done to move a __block variable to the heap.
16021 if (!Result.isInvalid() &&
16022 !Result.get()->getType().isConstQualified()) {
16023 Result = ImpCastExprToType(Result.get(),
16024 Result.get()->getType().withConst(),
16025 CK_NoOp, VK_LValue);
16026 }
16027
16028 if (!Result.isInvalid()) {
16029 Result = PerformCopyInitialization(
16030 InitializedEntity::InitializeBlock(Var->getLocation(),
16031 Cap.getCaptureType()),
16032 Loc, Result.get());
16033 }
16034
16035 // Build a full-expression copy expression if initialization
16036 // succeeded and used a non-trivial constructor. Recover from
16037 // errors by pretending that the copy isn't necessary.
16038 if (!Result.isInvalid() &&
16039 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16040 ->isTrivial()) {
16041 Result = MaybeCreateExprWithCleanups(Result);
16042 CopyExpr = Result.get();
16043 }
16044 }
16045 }
16046
16047 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16048 CopyExpr);
16049 Captures.push_back(NewCap);
16050 }
16051 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16052
16053 // Pop the block scope now but keep it alive to the end of this function.
16054 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16055 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16056
16057 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16058
16059 // If the block isn't obviously global, i.e. it captures anything at
16060 // all, then we need to do a few things in the surrounding context:
16061 if (Result->getBlockDecl()->hasCaptures()) {
16062 // First, this expression has a new cleanup object.
16063 ExprCleanupObjects.push_back(Result->getBlockDecl());
16064 Cleanup.setExprNeedsCleanups(true);
16065
16066 // It also gets a branch-protected scope if any of the captured
16067 // variables needs destruction.
16068 for (const auto &CI : Result->getBlockDecl()->captures()) {
16069 const VarDecl *var = CI.getVariable();
16070 if (var->getType().isDestructedType() != QualType::DK_none) {
16071 setFunctionHasBranchProtectedScope();
16072 break;
16073 }
16074 }
16075 }
16076
16077 if (getCurFunction())
16078 getCurFunction()->addBlock(BD);
16079
16080 return Result;
16081}
16082
16083ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16084 SourceLocation RPLoc) {
16085 TypeSourceInfo *TInfo;
16086 GetTypeFromParser(Ty, &TInfo);
16087 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16088}
16089
16090ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16091 Expr *E, TypeSourceInfo *TInfo,
16092 SourceLocation RPLoc) {
16093 Expr *OrigExpr = E;
16094 bool IsMS = false;
16095
16096 // CUDA device code does not support varargs.
16097 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16098 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16099 CUDAFunctionTarget T = IdentifyCUDATarget(F);
16100 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16101 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16102 }
16103 }
16104
16105 // NVPTX does not support va_arg expression.
16106 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16107 Context.getTargetInfo().getTriple().isNVPTX())
16108 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16109
16110 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16111 // as Microsoft ABI on an actual Microsoft platform, where
16112 // __builtin_ms_va_list and __builtin_va_list are the same.)
16113 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16114 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16115 QualType MSVaListType = Context.getBuiltinMSVaListType();
16116 if (Context.hasSameType(MSVaListType, E->getType())) {
16117 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16118 return ExprError();
16119 IsMS = true;
16120 }
16121 }
16122
16123 // Get the va_list type
16124 QualType VaListType = Context.getBuiltinVaListType();
16125 if (!IsMS) {
16126 if (VaListType->isArrayType()) {
16127 // Deal with implicit array decay; for example, on x86-64,
16128 // va_list is an array, but it's supposed to decay to
16129 // a pointer for va_arg.
16130 VaListType = Context.getArrayDecayedType(VaListType);
16131 // Make sure the input expression also decays appropriately.
16132 ExprResult Result = UsualUnaryConversions(E);
16133 if (Result.isInvalid())
16134 return ExprError();
16135 E = Result.get();
16136 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16137 // If va_list is a record type and we are compiling in C++ mode,
16138 // check the argument using reference binding.
16139 InitializedEntity Entity = InitializedEntity::InitializeParameter(
16140 Context, Context.getLValueReferenceType(VaListType), false);
16141 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16142 if (Init.isInvalid())
16143 return ExprError();
16144 E = Init.getAs<Expr>();
16145 } else {
16146 // Otherwise, the va_list argument must be an l-value because
16147 // it is modified by va_arg.
16148 if (!E->isTypeDependent() &&
16149 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16150 return ExprError();
16151 }
16152 }
16153
16154 if (!IsMS && !E->isTypeDependent() &&
16155 !Context.hasSameType(VaListType, E->getType()))
16156 return ExprError(
16157 Diag(E->getBeginLoc(),
16158 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16159 << OrigExpr->getType() << E->getSourceRange());
16160
16161 if (!TInfo->getType()->isDependentType()) {
16162 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16163 diag::err_second_parameter_to_va_arg_incomplete,
16164 TInfo->getTypeLoc()))
16165 return ExprError();
16166
16167 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16168 TInfo->getType(),
16169 diag::err_second_parameter_to_va_arg_abstract,
16170 TInfo->getTypeLoc()))
16171 return ExprError();
16172
16173 if (!TInfo->getType().isPODType(Context)) {
16174 Diag(TInfo->getTypeLoc().getBeginLoc(),
16175 TInfo->getType()->isObjCLifetimeType()
16176 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16177 : diag::warn_second_parameter_to_va_arg_not_pod)
16178 << TInfo->getType()
16179 << TInfo->getTypeLoc().getSourceRange();
16180 }
16181
16182 // Check for va_arg where arguments of the given type will be promoted
16183 // (i.e. this va_arg is guaranteed to have undefined behavior).
16184 QualType PromoteType;
16185 if (TInfo->getType()->isPromotableIntegerType()) {
16186 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16187 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16188 // and C2x 7.16.1.1p2 says, in part:
16189 // If type is not compatible with the type of the actual next argument
16190 // (as promoted according to the default argument promotions), the
16191 // behavior is undefined, except for the following cases:
16192 // - both types are pointers to qualified or unqualified versions of
16193 // compatible types;
16194 // - one type is a signed integer type, the other type is the
16195 // corresponding unsigned integer type, and the value is
16196 // representable in both types;
16197 // - one type is pointer to qualified or unqualified void and the
16198 // other is a pointer to a qualified or unqualified character type.
16199 // Given that type compatibility is the primary requirement (ignoring
16200 // qualifications), you would think we could call typesAreCompatible()
16201 // directly to test this. However, in C++, that checks for *same type*,
16202 // which causes false positives when passing an enumeration type to
16203 // va_arg. Instead, get the underlying type of the enumeration and pass
16204 // that.
16205 QualType UnderlyingType = TInfo->getType();
16206 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16207 UnderlyingType = ET->getDecl()->getIntegerType();
16208 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16209 /*CompareUnqualified*/ true))
16210 PromoteType = QualType();
16211
16212 // If the types are still not compatible, we need to test whether the
16213 // promoted type and the underlying type are the same except for
16214 // signedness. Ask the AST for the correctly corresponding type and see
16215 // if that's compatible.
16216 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16217 PromoteType->isUnsignedIntegerType() !=
16218 UnderlyingType->isUnsignedIntegerType()) {
16219 UnderlyingType =
16220 UnderlyingType->isUnsignedIntegerType()
16221 ? Context.getCorrespondingSignedType(UnderlyingType)
16222 : Context.getCorrespondingUnsignedType(UnderlyingType);
16223 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16224 /*CompareUnqualified*/ true))
16225 PromoteType = QualType();
16226 }
16227 }
16228 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16229 PromoteType = Context.DoubleTy;
16230 if (!PromoteType.isNull())
16231 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16232 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16233 << TInfo->getType()
16234 << PromoteType
16235 << TInfo->getTypeLoc().getSourceRange());
16236 }
16237
16238 QualType T = TInfo->getType().getNonLValueExprType(Context);
16239 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16240}
16241
16242ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16243 // The type of __null will be int or long, depending on the size of
16244 // pointers on the target.
16245 QualType Ty;
16246 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
16247 if (pw == Context.getTargetInfo().getIntWidth())
16248 Ty = Context.IntTy;
16249 else if (pw == Context.getTargetInfo().getLongWidth())
16250 Ty = Context.LongTy;
16251 else if (pw == Context.getTargetInfo().getLongLongWidth())
16252 Ty = Context.LongLongTy;
16253 else {
16254 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", 16254)
;
16255 }
16256
16257 return new (Context) GNUNullExpr(Ty, TokenLoc);
16258}
16259
16260ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
16261 SourceLocation BuiltinLoc,
16262 SourceLocation RPLoc) {
16263 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
16264}
16265
16266ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
16267 SourceLocation BuiltinLoc,
16268 SourceLocation RPLoc,
16269 DeclContext *ParentContext) {
16270 return new (Context)
16271 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
16272}
16273
16274bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
16275 bool Diagnose) {
16276 if (!getLangOpts().ObjC)
16277 return false;
16278
16279 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
16280 if (!PT)
16281 return false;
16282 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
16283
16284 // Ignore any parens, implicit casts (should only be
16285 // array-to-pointer decays), and not-so-opaque values. The last is
16286 // important for making this trigger for property assignments.
16287 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
16288 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
16289 if (OV->getSourceExpr())
16290 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
16291
16292 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
16293 if (!PT->isObjCIdType() &&
16294 !(ID && ID->getIdentifier()->isStr("NSString")))
16295 return false;
16296 if (!SL->isAscii())
16297 return false;
16298
16299 if (Diagnose) {
16300 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
16301 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
16302 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
16303 }
16304 return true;
16305 }
16306
16307 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16308 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16309 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16310 !SrcExpr->isNullPointerConstant(
16311 getASTContext(), Expr::NPC_NeverValueDependent)) {
16312 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16313 return false;
16314 if (Diagnose) {
16315 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16316 << /*number*/1
16317 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16318 Expr *NumLit =
16319 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16320 if (NumLit)
16321 Exp = NumLit;
16322 }
16323 return true;
16324 }
16325
16326 return false;
16327}
16328
16329static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16330 const Expr *SrcExpr) {
16331 if (!DstType->isFunctionPointerType() ||
16332 !SrcExpr->getType()->isFunctionType())
16333 return false;
16334
16335 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16336 if (!DRE)
16337 return false;
16338
16339 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16340 if (!FD)
16341 return false;
16342
16343 return !S.checkAddressOfFunctionIsAvailable(FD,
16344 /*Complain=*/true,
16345 SrcExpr->getBeginLoc());
16346}
16347
16348bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16349 SourceLocation Loc,
16350 QualType DstType, QualType SrcType,
16351 Expr *SrcExpr, AssignmentAction Action,
16352 bool *Complained) {
16353 if (Complained)
16354 *Complained = false;
16355
16356 // Decode the result (notice that AST's are still created for extensions).
16357 bool CheckInferredResultType = false;
16358 bool isInvalid = false;
16359 unsigned DiagKind = 0;
16360 ConversionFixItGenerator ConvHints;
16361 bool MayHaveConvFixit = false;
16362 bool MayHaveFunctionDiff = false;
16363 const ObjCInterfaceDecl *IFace = nullptr;
16364 const ObjCProtocolDecl *PDecl = nullptr;
16365
16366 switch (ConvTy) {
16367 case Compatible:
16368 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16369 return false;
16370
16371 case PointerToInt:
16372 if (getLangOpts().CPlusPlus) {
16373 DiagKind = diag::err_typecheck_convert_pointer_int;
16374 isInvalid = true;
16375 } else {
16376 DiagKind = diag::ext_typecheck_convert_pointer_int;
16377 }
16378 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16379 MayHaveConvFixit = true;
16380 break;
16381 case IntToPointer:
16382 if (getLangOpts().CPlusPlus) {
16383 DiagKind = diag::err_typecheck_convert_int_pointer;
16384 isInvalid = true;
16385 } else {
16386 DiagKind = diag::ext_typecheck_convert_int_pointer;
16387 }
16388 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16389 MayHaveConvFixit = true;
16390 break;
16391 case IncompatibleFunctionPointer:
16392 if (getLangOpts().CPlusPlus) {
16393 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16394 isInvalid = true;
16395 } else {
16396 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16397 }
16398 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16399 MayHaveConvFixit = true;
16400 break;
16401 case IncompatiblePointer:
16402 if (Action == AA_Passing_CFAudited) {
16403 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16404 } else if (getLangOpts().CPlusPlus) {
16405 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16406 isInvalid = true;
16407 } else {
16408 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16409 }
16410 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16411 SrcType->isObjCObjectPointerType();
16412 if (!CheckInferredResultType) {
16413 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16414 } else if (CheckInferredResultType) {
16415 SrcType = SrcType.getUnqualifiedType();
16416 DstType = DstType.getUnqualifiedType();
16417 }
16418 MayHaveConvFixit = true;
16419 break;
16420 case IncompatiblePointerSign:
16421 if (getLangOpts().CPlusPlus) {
16422 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16423 isInvalid = true;
16424 } else {
16425 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16426 }
16427 break;
16428 case FunctionVoidPointer:
16429 if (getLangOpts().CPlusPlus) {
16430 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16431 isInvalid = true;
16432 } else {
16433 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16434 }
16435 break;
16436 case IncompatiblePointerDiscardsQualifiers: {
16437 // Perform array-to-pointer decay if necessary.
16438 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16439
16440 isInvalid = true;
16441
16442 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16443 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16444 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16445 DiagKind = diag::err_typecheck_incompatible_address_space;
16446 break;
16447
16448 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16449 DiagKind = diag::err_typecheck_incompatible_ownership;
16450 break;
16451 }
16452
16453 llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!"
, "clang/lib/Sema/SemaExpr.cpp", 16453)
;
16454 // fallthrough
16455 }
16456 case CompatiblePointerDiscardsQualifiers:
16457 // If the qualifiers lost were because we were applying the
16458 // (deprecated) C++ conversion from a string literal to a char*
16459 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16460 // Ideally, this check would be performed in
16461 // checkPointerTypesForAssignment. However, that would require a
16462 // bit of refactoring (so that the second argument is an
16463 // expression, rather than a type), which should be done as part
16464 // of a larger effort to fix checkPointerTypesForAssignment for
16465 // C++ semantics.
16466 if (getLangOpts().CPlusPlus &&
16467 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16468 return false;
16469 if (getLangOpts().CPlusPlus) {
16470 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16471 isInvalid = true;
16472 } else {
16473 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16474 }
16475
16476 break;
16477 case IncompatibleNestedPointerQualifiers:
16478 if (getLangOpts().CPlusPlus) {
16479 isInvalid = true;
16480 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16481 } else {
16482 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16483 }
16484 break;
16485 case IncompatibleNestedPointerAddressSpaceMismatch:
16486 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16487 isInvalid = true;
16488 break;
16489 case IntToBlockPointer:
16490 DiagKind = diag::err_int_to_block_pointer;
16491 isInvalid = true;
16492 break;
16493 case IncompatibleBlockPointer:
16494 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16495 isInvalid = true;
16496 break;
16497 case IncompatibleObjCQualifiedId: {
16498 if (SrcType->isObjCQualifiedIdType()) {
16499 const ObjCObjectPointerType *srcOPT =
16500 SrcType->castAs<ObjCObjectPointerType>();
16501 for (auto *srcProto : srcOPT->quals()) {
16502 PDecl = srcProto;
16503 break;
16504 }
16505 if (const ObjCInterfaceType *IFaceT =
16506 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16507 IFace = IFaceT->getDecl();
16508 }
16509 else if (DstType->isObjCQualifiedIdType()) {
16510 const ObjCObjectPointerType *dstOPT =
16511 DstType->castAs<ObjCObjectPointerType>();
16512 for (auto *dstProto : dstOPT->quals()) {
16513 PDecl = dstProto;
16514 break;
16515 }
16516 if (const ObjCInterfaceType *IFaceT =
16517 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16518 IFace = IFaceT->getDecl();
16519 }
16520 if (getLangOpts().CPlusPlus) {
16521 DiagKind = diag::err_incompatible_qualified_id;
16522 isInvalid = true;
16523 } else {
16524 DiagKind = diag::warn_incompatible_qualified_id;
16525 }
16526 break;
16527 }
16528 case IncompatibleVectors:
16529 if (getLangOpts().CPlusPlus) {
16530 DiagKind = diag::err_incompatible_vectors;
16531 isInvalid = true;
16532 } else {
16533 DiagKind = diag::warn_incompatible_vectors;
16534 }
16535 break;
16536 case IncompatibleObjCWeakRef:
16537 DiagKind = diag::err_arc_weak_unavailable_assign;
16538 isInvalid = true;
16539 break;
16540 case Incompatible:
16541 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16542 if (Complained)
16543 *Complained = true;
16544 return true;
16545 }
16546
16547 DiagKind = diag::err_typecheck_convert_incompatible;
16548 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16549 MayHaveConvFixit = true;
16550 isInvalid = true;
16551 MayHaveFunctionDiff = true;
16552 break;
16553 }
16554
16555 QualType FirstType, SecondType;
16556 switch (Action) {
16557 case AA_Assigning:
16558 case AA_Initializing:
16559 // The destination type comes first.
16560 FirstType = DstType;
16561 SecondType = SrcType;
16562 break;
16563
16564 case AA_Returning:
16565 case AA_Passing:
16566 case AA_Passing_CFAudited:
16567 case AA_Converting:
16568 case AA_Sending:
16569 case AA_Casting:
16570 // The source type comes first.
16571 FirstType = SrcType;
16572 SecondType = DstType;
16573 break;
16574 }
16575
16576 PartialDiagnostic FDiag = PDiag(DiagKind);
16577 if (Action == AA_Passing_CFAudited)
16578 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16579 else
16580 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16581
16582 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16583 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16584 auto isPlainChar = [](const clang::Type *Type) {
16585 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16586 Type->isSpecificBuiltinType(BuiltinType::Char_U);
16587 };
16588 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16589 isPlainChar(SecondType->getPointeeOrArrayElementType()));
16590 }
16591
16592 // If we can fix the conversion, suggest the FixIts.
16593 if (!ConvHints.isNull()) {
16594 for (FixItHint &H : ConvHints.Hints)
16595 FDiag << H;
16596 }
16597
16598 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16599
16600 if (MayHaveFunctionDiff)
16601 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16602
16603 Diag(Loc, FDiag);
16604 if ((DiagKind == diag::warn_incompatible_qualified_id ||
16605 DiagKind == diag::err_incompatible_qualified_id) &&
16606 PDecl && IFace && !IFace->hasDefinition())
16607 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16608 << IFace << PDecl;
16609
16610 if (SecondType == Context.OverloadTy)
16611 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16612 FirstType, /*TakingAddress=*/true);
16613
16614 if (CheckInferredResultType)
16615 EmitRelatedResultTypeNote(SrcExpr);
16616
16617 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16618 EmitRelatedResultTypeNoteForReturn(DstType);
16619
16620 if (Complained)
16621 *Complained = true;
16622 return isInvalid;
16623}
16624
16625ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16626 llvm::APSInt *Result,
16627 AllowFoldKind CanFold) {
16628 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16629 public:
16630 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16631 QualType T) override {
16632 return S.Diag(Loc, diag::err_ice_not_integral)
16633 << T << S.LangOpts.CPlusPlus;
16634 }
16635 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16636 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16637 }
16638 } Diagnoser;
16639
16640 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16641}
16642
16643ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16644 llvm::APSInt *Result,
16645 unsigned DiagID,
16646 AllowFoldKind CanFold) {
16647 class IDDiagnoser : public VerifyICEDiagnoser {
16648 unsigned DiagID;
16649
16650 public:
16651 IDDiagnoser(unsigned DiagID)
16652 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16653
16654 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16655 return S.Diag(Loc, DiagID);
16656 }
16657 } Diagnoser(DiagID);
16658
16659 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16660}
16661
16662Sema::SemaDiagnosticBuilder
16663Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16664 QualType T) {
16665 return diagnoseNotICE(S, Loc);
16666}
16667
16668Sema::SemaDiagnosticBuilder
16669Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16670 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16671}
16672
16673ExprResult
16674Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16675 VerifyICEDiagnoser &Diagnoser,
16676 AllowFoldKind CanFold) {
16677 SourceLocation DiagLoc = E->getBeginLoc();
16678
16679 if (getLangOpts().CPlusPlus11) {
16680 // C++11 [expr.const]p5:
16681 // If an expression of literal class type is used in a context where an
16682 // integral constant expression is required, then that class type shall
16683 // have a single non-explicit conversion function to an integral or
16684 // unscoped enumeration type
16685 ExprResult Converted;
16686 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16687 VerifyICEDiagnoser &BaseDiagnoser;
16688 public:
16689 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16690 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16691 BaseDiagnoser.Suppress, true),
16692 BaseDiagnoser(BaseDiagnoser) {}
16693
16694 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16695 QualType T) override {
16696 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16697 }
16698
16699 SemaDiagnosticBuilder diagnoseIncomplete(
16700 Sema &S, SourceLocation Loc, QualType T) override {
16701 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16702 }
16703
16704 SemaDiagnosticBuilder diagnoseExplicitConv(
16705 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16706 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16707 }
16708
16709 SemaDiagnosticBuilder noteExplicitConv(
16710 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16711 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16712 << ConvTy->isEnumeralType() << ConvTy;
16713 }
16714
16715 SemaDiagnosticBuilder diagnoseAmbiguous(
16716 Sema &S, SourceLocation Loc, QualType T) override {
16717 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16718 }
16719
16720 SemaDiagnosticBuilder noteAmbiguous(
16721 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16722 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16723 << ConvTy->isEnumeralType() << ConvTy;
16724 }
16725
16726 SemaDiagnosticBuilder diagnoseConversion(
16727 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16728 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "clang/lib/Sema/SemaExpr.cpp", 16728)
;
16729 }
16730 } ConvertDiagnoser(Diagnoser);
16731
16732 Converted = PerformContextualImplicitConversion(DiagLoc, E,
16733 ConvertDiagnoser);
16734 if (Converted.isInvalid())
16735 return Converted;
16736 E = Converted.get();
16737 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16738 return ExprError();
16739 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16740 // An ICE must be of integral or unscoped enumeration type.
16741 if (!Diagnoser.Suppress)
16742 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16743 << E->getSourceRange();
16744 return ExprError();
16745 }
16746
16747 ExprResult RValueExpr = DefaultLvalueConversion(E);
16748 if (RValueExpr.isInvalid())
16749 return ExprError();
16750
16751 E = RValueExpr.get();
16752
16753 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16754 // in the non-ICE case.
16755 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16756 if (Result)
16757 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16758 if (!isa<ConstantExpr>(E))
16759 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
16760 : ConstantExpr::Create(Context, E);
16761 return E;
16762 }
16763
16764 Expr::EvalResult EvalResult;
16765 SmallVector<PartialDiagnosticAt, 8> Notes;
16766 EvalResult.Diag = &Notes;
16767
16768 // Try to evaluate the expression, and produce diagnostics explaining why it's
16769 // not a constant expression as a side-effect.
16770 bool Folded =
16771 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16772 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16773
16774 if (!isa<ConstantExpr>(E))
16775 E = ConstantExpr::Create(Context, E, EvalResult.Val);
16776
16777 // In C++11, we can rely on diagnostics being produced for any expression
16778 // which is not a constant expression. If no diagnostics were produced, then
16779 // this is a constant expression.
16780 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16781 if (Result)
16782 *Result = EvalResult.Val.getInt();
16783 return E;
16784 }
16785
16786 // If our only note is the usual "invalid subexpression" note, just point
16787 // the caret at its location rather than producing an essentially
16788 // redundant note.
16789 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16790 diag::note_invalid_subexpr_in_const_expr) {
16791 DiagLoc = Notes[0].first;
16792 Notes.clear();
16793 }
16794
16795 if (!Folded || !CanFold) {
16796 if (!Diagnoser.Suppress) {
16797 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16798 for (const PartialDiagnosticAt &Note : Notes)
16799 Diag(Note.first, Note.second);
16800 }
16801
16802 return ExprError();
16803 }
16804
16805 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16806 for (const PartialDiagnosticAt &Note : Notes)
16807 Diag(Note.first, Note.second);
16808
16809 if (Result)
16810 *Result = EvalResult.Val.getInt();
16811 return E;
16812}
16813
16814namespace {
16815 // Handle the case where we conclude a expression which we speculatively
16816 // considered to be unevaluated is actually evaluated.
16817 class TransformToPE : public TreeTransform<TransformToPE> {
16818 typedef TreeTransform<TransformToPE> BaseTransform;
16819
16820 public:
16821 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16822
16823 // Make sure we redo semantic analysis
16824 bool AlwaysRebuild() { return true; }
16825 bool ReplacingOriginal() { return true; }
16826
16827 // We need to special-case DeclRefExprs referring to FieldDecls which
16828 // are not part of a member pointer formation; normal TreeTransforming
16829 // doesn't catch this case because of the way we represent them in the AST.
16830 // FIXME: This is a bit ugly; is it really the best way to handle this
16831 // case?
16832 //
16833 // Error on DeclRefExprs referring to FieldDecls.
16834 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16835 if (isa<FieldDecl>(E->getDecl()) &&
16836 !SemaRef.isUnevaluatedContext())
16837 return SemaRef.Diag(E->getLocation(),
16838 diag::err_invalid_non_static_member_use)
16839 << E->getDecl() << E->getSourceRange();
16840
16841 return BaseTransform::TransformDeclRefExpr(E);
16842 }
16843
16844 // Exception: filter out member pointer formation
16845 ExprResult TransformUnaryOperator(UnaryOperator *E) {
16846 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16847 return E;
16848
16849 return BaseTransform::TransformUnaryOperator(E);
16850 }
16851
16852 // The body of a lambda-expression is in a separate expression evaluation
16853 // context so never needs to be transformed.
16854 // FIXME: Ideally we wouldn't transform the closure type either, and would
16855 // just recreate the capture expressions and lambda expression.
16856 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16857 return SkipLambdaBody(E, Body);
16858 }
16859 };
16860}
16861
16862ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16863 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", 16864, __extension__ __PRETTY_FUNCTION__
))
16864 "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", 16864, __extension__ __PRETTY_FUNCTION__
))
;
16865 ExprEvalContexts.back().Context =
16866 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16867 if (isUnevaluatedContext())
16868 return E;
16869 return TransformToPE(*this).TransformExpr(E);
16870}
16871
16872TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
16873 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", 16874, __extension__ __PRETTY_FUNCTION__
))
16874 "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", 16874, __extension__ __PRETTY_FUNCTION__
))
;
16875 ExprEvalContexts.back().Context =
16876 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
16877 if (isUnevaluatedContext())
16878 return TInfo;
16879 return TransformToPE(*this).TransformType(TInfo);
16880}
16881
16882void
16883Sema::PushExpressionEvaluationContext(
16884 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16885 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16886 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16887 LambdaContextDecl, ExprContext);
16888
16889 // Discarded statements and immediate contexts nested in other
16890 // discarded statements or immediate context are themselves
16891 // a discarded statement or an immediate context, respectively.
16892 ExprEvalContexts.back().InDiscardedStatement =
16893 ExprEvalContexts[ExprEvalContexts.size() - 2]
16894 .isDiscardedStatementContext();
16895 ExprEvalContexts.back().InImmediateFunctionContext =
16896 ExprEvalContexts[ExprEvalContexts.size() - 2]
16897 .isImmediateFunctionContext();
16898
16899 Cleanup.reset();
16900 if (!MaybeODRUseExprs.empty())
16901 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16902}
16903
16904void
16905Sema::PushExpressionEvaluationContext(
16906 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16907 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16908 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16909 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16910}
16911
16912namespace {
16913
16914const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16915 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16916 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16917 if (E->getOpcode() == UO_Deref)
16918 return CheckPossibleDeref(S, E->getSubExpr());
16919 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16920 return CheckPossibleDeref(S, E->getBase());
16921 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16922 return CheckPossibleDeref(S, E->getBase());
16923 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16924 QualType Inner;
16925 QualType Ty = E->getType();
16926 if (const auto *Ptr = Ty->getAs<PointerType>())
16927 Inner = Ptr->getPointeeType();
16928 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16929 Inner = Arr->getElementType();
16930 else
16931 return nullptr;
16932
16933 if (Inner->hasAttr(attr::NoDeref))
16934 return E;
16935 }
16936 return nullptr;
16937}
16938
16939} // namespace
16940
16941void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16942 for (const Expr *E : Rec.PossibleDerefs) {
16943 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16944 if (DeclRef) {
16945 const ValueDecl *Decl = DeclRef->getDecl();
16946 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16947 << Decl->getName() << E->getSourceRange();
16948 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16949 } else {
16950 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16951 << E->getSourceRange();
16952 }
16953 }
16954 Rec.PossibleDerefs.clear();
16955}
16956
16957/// Check whether E, which is either a discarded-value expression or an
16958/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16959/// and if so, remove it from the list of volatile-qualified assignments that
16960/// we are going to warn are deprecated.
16961void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16962 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16963 return;
16964
16965 // Note: ignoring parens here is not justified by the standard rules, but
16966 // ignoring parentheses seems like a more reasonable approach, and this only
16967 // drives a deprecation warning so doesn't affect conformance.
16968 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16969 if (BO->getOpcode() == BO_Assign) {
16970 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16971 llvm::erase_value(LHSs, BO->getLHS());
16972 }
16973 }
16974}
16975
16976ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16977 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
16978 !Decl->isConsteval() || isConstantEvaluated() ||
16979 RebuildingImmediateInvocation || isImmediateFunctionContext())
16980 return E;
16981
16982 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16983 /// It's OK if this fails; we'll also remove this in
16984 /// HandleImmediateInvocations, but catching it here allows us to avoid
16985 /// walking the AST looking for it in simple cases.
16986 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16987 if (auto *DeclRef =
16988 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16989 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16990
16991 E = MaybeCreateExprWithCleanups(E);
16992
16993 ConstantExpr *Res = ConstantExpr::Create(
16994 getASTContext(), E.get(),
16995 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16996 getASTContext()),
16997 /*IsImmediateInvocation*/ true);
16998 /// Value-dependent constant expressions should not be immediately
16999 /// evaluated until they are instantiated.
17000 if (!Res->isValueDependent())
17001 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17002 return Res;
17003}
17004
17005static void EvaluateAndDiagnoseImmediateInvocation(
17006 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17007 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17008 Expr::EvalResult Eval;
17009 Eval.Diag = &Notes;
17010 ConstantExpr *CE = Candidate.getPointer();
17011 bool Result = CE->EvaluateAsConstantExpr(
17012 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17013 if (!Result || !Notes.empty()) {
17014 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17015 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17016 InnerExpr = FunctionalCast->getSubExpr();
17017 FunctionDecl *FD = nullptr;
17018 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17019 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17020 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17021 FD = Call->getConstructor();
17022 else
17023 llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "clang/lib/Sema/SemaExpr.cpp"
, 17023)
;
17024 assert(FD->isConsteval())(static_cast <bool> (FD->isConsteval()) ? void (0) :
__assert_fail ("FD->isConsteval()", "clang/lib/Sema/SemaExpr.cpp"
, 17024, __extension__ __PRETTY_FUNCTION__))
;
17025 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17026 for (auto &Note : Notes)
17027 SemaRef.Diag(Note.first, Note.second);
17028 return;
17029 }
17030 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17031}
17032
17033static void RemoveNestedImmediateInvocation(
17034 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17035 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17036 struct ComplexRemove : TreeTransform<ComplexRemove> {
17037 using Base = TreeTransform<ComplexRemove>;
17038 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17039 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17040 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
17041 CurrentII;
17042 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17043 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
17044 SmallVector<Sema::ImmediateInvocationCandidate,
17045 4>::reverse_iterator Current)
17046 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17047 void RemoveImmediateInvocation(ConstantExpr* E) {
17048 auto It = std::find_if(CurrentII, IISet.rend(),
17049 [E](Sema::ImmediateInvocationCandidate Elem) {
17050 return Elem.getPointer() == E;
17051 });
17052 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", 17054, __extension__ __PRETTY_FUNCTION__
))
17053 "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", 17054, __extension__ __PRETTY_FUNCTION__
))
17054 "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", 17054, __extension__ __PRETTY_FUNCTION__
))
;
17055 It->setInt(1); // Mark as deleted
17056 }
17057 ExprResult TransformConstantExpr(ConstantExpr *E) {
17058 if (!E->isImmediateInvocation())
17059 return Base::TransformConstantExpr(E);
17060 RemoveImmediateInvocation(E);
17061 return Base::TransformExpr(E->getSubExpr());
17062 }
17063 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17064 /// we need to remove its DeclRefExpr from the DRSet.
17065 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17066 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17067 return Base::TransformCXXOperatorCallExpr(E);
17068 }
17069 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
17070 /// here.
17071 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17072 if (!Init)
17073 return Init;
17074 /// ConstantExpr are the first layer of implicit node to be removed so if
17075 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17076 if (auto *CE = dyn_cast<ConstantExpr>(Init))
17077 if (CE->isImmediateInvocation())
17078 RemoveImmediateInvocation(CE);
17079 return Base::TransformInitializer(Init, NotCopyInit);
17080 }
17081 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17082 DRSet.erase(E);
17083 return E;
17084 }
17085 bool AlwaysRebuild() { return false; }
17086 bool ReplacingOriginal() { return true; }
17087 bool AllowSkippingCXXConstructExpr() {
17088 bool Res = AllowSkippingFirstCXXConstructExpr;
17089 AllowSkippingFirstCXXConstructExpr = true;
17090 return Res;
17091 }
17092 bool AllowSkippingFirstCXXConstructExpr = true;
17093 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17094 Rec.ImmediateInvocationCandidates, It);
17095
17096 /// CXXConstructExpr with a single argument are getting skipped by
17097 /// TreeTransform in some situtation because they could be implicit. This
17098 /// can only occur for the top-level CXXConstructExpr because it is used
17099 /// nowhere in the expression being transformed therefore will not be rebuilt.
17100 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17101 /// skipping the first CXXConstructExpr.
17102 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17103 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17104
17105 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17106 assert(Res.isUsable())(static_cast <bool> (Res.isUsable()) ? void (0) : __assert_fail
("Res.isUsable()", "clang/lib/Sema/SemaExpr.cpp", 17106, __extension__
__PRETTY_FUNCTION__))
;
17107 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17108 It->getPointer()->setSubExpr(Res.get());
17109}
17110
17111static void
17112HandleImmediateInvocations(Sema &SemaRef,
17113 Sema::ExpressionEvaluationContextRecord &Rec) {
17114 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17115 Rec.ReferenceToConsteval.size() == 0) ||
17116 SemaRef.RebuildingImmediateInvocation)
17117 return;
17118
17119 /// When we have more then 1 ImmediateInvocationCandidates we need to check
17120 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17121 /// need to remove ReferenceToConsteval in the immediate invocation.
17122 if (Rec.ImmediateInvocationCandidates.size() > 1) {
17123
17124 /// Prevent sema calls during the tree transform from adding pointers that
17125 /// are already in the sets.
17126 llvm::SaveAndRestore<bool> DisableIITracking(
17127 SemaRef.RebuildingImmediateInvocation, true);
17128
17129 /// Prevent diagnostic during tree transfrom as they are duplicates
17130 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17131
17132 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17133 It != Rec.ImmediateInvocationCandidates.rend(); It++)
17134 if (!It->getInt())
17135 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17136 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17137 Rec.ReferenceToConsteval.size()) {
17138 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17139 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17140 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17141 bool VisitDeclRefExpr(DeclRefExpr *E) {
17142 DRSet.erase(E);
17143 return DRSet.size();
17144 }
17145 } Visitor(Rec.ReferenceToConsteval);
17146 Visitor.TraverseStmt(
17147 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17148 }
17149 for (auto CE : Rec.ImmediateInvocationCandidates)
17150 if (!CE.getInt())
17151 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
17152 for (auto DR : Rec.ReferenceToConsteval) {
17153 auto *FD = cast<FunctionDecl>(DR->getDecl());
17154 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17155 << FD;
17156 SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
17157 }
17158}
17159
17160void Sema::PopExpressionEvaluationContext() {
17161 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
17162 unsigned NumTypos = Rec.NumTypos;
17163
17164 if (!Rec.Lambdas.empty()) {
17165 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
17166 if (!getLangOpts().CPlusPlus20 &&
17167 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17168 Rec.isUnevaluated() ||
17169 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17170 unsigned D;
17171 if (Rec.isUnevaluated()) {
17172 // C++11 [expr.prim.lambda]p2:
17173 // A lambda-expression shall not appear in an unevaluated operand
17174 // (Clause 5).
17175 D = diag::err_lambda_unevaluated_operand;
17176 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17177 // C++1y [expr.const]p2:
17178 // A conditional-expression e is a core constant expression unless the
17179 // evaluation of e, following the rules of the abstract machine, would
17180 // evaluate [...] a lambda-expression.
17181 D = diag::err_lambda_in_constant_expression;
17182 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17183 // C++17 [expr.prim.lamda]p2:
17184 // A lambda-expression shall not appear [...] in a template-argument.
17185 D = diag::err_lambda_in_invalid_context;
17186 } else
17187 llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message."
, "clang/lib/Sema/SemaExpr.cpp", 17187)
;
17188
17189 for (const auto *L : Rec.Lambdas)
17190 Diag(L->getBeginLoc(), D);
17191 }
17192 }
17193
17194 WarnOnPendingNoDerefs(Rec);
17195 HandleImmediateInvocations(*this, Rec);
17196
17197 // Warn on any volatile-qualified simple-assignments that are not discarded-
17198 // value expressions nor unevaluated operands (those cases get removed from
17199 // this list by CheckUnusedVolatileAssignment).
17200 for (auto *BO : Rec.VolatileAssignmentLHSs)
17201 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17202 << BO->getType();
17203
17204 // When are coming out of an unevaluated context, clear out any
17205 // temporaries that we may have created as part of the evaluation of
17206 // the expression in that context: they aren't relevant because they
17207 // will never be constructed.
17208 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17209 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17210 ExprCleanupObjects.end());
17211 Cleanup = Rec.ParentCleanup;
17212 CleanupVarDeclMarking();
17213 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17214 // Otherwise, merge the contexts together.
17215 } else {
17216 Cleanup.mergeFrom(Rec.ParentCleanup);
17217 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17218 Rec.SavedMaybeODRUseExprs.end());
17219 }
17220
17221 // Pop the current expression evaluation context off the stack.
17222 ExprEvalContexts.pop_back();
17223
17224 // The global expression evaluation context record is never popped.
17225 ExprEvalContexts.back().NumTypos += NumTypos;
17226}
17227
17228void Sema::DiscardCleanupsInEvaluationContext() {
17229 ExprCleanupObjects.erase(
17230 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17231 ExprCleanupObjects.end());
17232 Cleanup.reset();
17233 MaybeODRUseExprs.clear();
17234}
17235
17236ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
17237 ExprResult Result = CheckPlaceholderExpr(E);
17238 if (Result.isInvalid())
17239 return ExprError();
17240 E = Result.get();
17241 if (!E->getType()->isVariablyModifiedType())
17242 return E;
17243 return TransformToPotentiallyEvaluated(E);
17244}
17245
17246/// Are we in a context that is potentially constant evaluated per C++20
17247/// [expr.const]p12?
17248static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
17249 /// C++2a [expr.const]p12:
17250 // An expression or conversion is potentially constant evaluated if it is
17251 switch (SemaRef.ExprEvalContexts.back().Context) {
17252 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17253 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17254
17255 // -- a manifestly constant-evaluated expression,
17256 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17257 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17258 case Sema::ExpressionEvaluationContext::DiscardedStatement:
17259 // -- a potentially-evaluated expression,
17260 case Sema::ExpressionEvaluationContext::UnevaluatedList:
17261 // -- an immediate subexpression of a braced-init-list,
17262
17263 // -- [FIXME] an expression of the form & cast-expression that occurs
17264 // within a templated entity
17265 // -- a subexpression of one of the above that is not a subexpression of
17266 // a nested unevaluated operand.
17267 return true;
17268
17269 case Sema::ExpressionEvaluationContext::Unevaluated:
17270 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17271 // Expressions in this context are never evaluated.
17272 return false;
17273 }
17274 llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "clang/lib/Sema/SemaExpr.cpp"
, 17274)
;
17275}
17276
17277/// Return true if this function has a calling convention that requires mangling
17278/// in the size of the parameter pack.
17279static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17280 // These manglings don't do anything on non-Windows or non-x86 platforms, so
17281 // we don't need parameter type sizes.
17282 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17283 if (!TT.isOSWindows() || !TT.isX86())
17284 return false;
17285
17286 // If this is C++ and this isn't an extern "C" function, parameters do not
17287 // need to be complete. In this case, C++ mangling will apply, which doesn't
17288 // use the size of the parameters.
17289 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17290 return false;
17291
17292 // Stdcall, fastcall, and vectorcall need this special treatment.
17293 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17294 switch (CC) {
17295 case CC_X86StdCall:
17296 case CC_X86FastCall:
17297 case CC_X86VectorCall:
17298 return true;
17299 default:
17300 break;
17301 }
17302 return false;
17303}
17304
17305/// Require that all of the parameter types of function be complete. Normally,
17306/// parameter types are only required to be complete when a function is called
17307/// or defined, but to mangle functions with certain calling conventions, the
17308/// mangler needs to know the size of the parameter list. In this situation,
17309/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17310/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17311/// result in a linker error. Clang doesn't implement this behavior, and instead
17312/// attempts to error at compile time.
17313static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17314 SourceLocation Loc) {
17315 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17316 FunctionDecl *FD;
17317 ParmVarDecl *Param;
17318
17319 public:
17320 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17321 : FD(FD), Param(Param) {}
17322
17323 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17324 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17325 StringRef CCName;
17326 switch (CC) {
17327 case CC_X86StdCall:
17328 CCName = "stdcall";
17329 break;
17330 case CC_X86FastCall:
17331 CCName = "fastcall";
17332 break;
17333 case CC_X86VectorCall:
17334 CCName = "vectorcall";
17335 break;
17336 default:
17337 llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling"
, "clang/lib/Sema/SemaExpr.cpp", 17337)
;
17338 }
17339
17340 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17341 << Param->getDeclName() << FD->getDeclName() << CCName;
17342 }
17343 };
17344
17345 for (ParmVarDecl *Param : FD->parameters()) {
17346 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17347 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17348 }
17349}
17350
17351namespace {
17352enum class OdrUseContext {
17353 /// Declarations in this context are not odr-used.
17354 None,
17355 /// Declarations in this context are formally odr-used, but this is a
17356 /// dependent context.
17357 Dependent,
17358 /// Declarations in this context are odr-used but not actually used (yet).
17359 FormallyOdrUsed,
17360 /// Declarations in this context are used.
17361 Used
17362};
17363}
17364
17365/// Are we within a context in which references to resolved functions or to
17366/// variables result in odr-use?
17367static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17368 OdrUseContext Result;
17369
17370 switch (SemaRef.ExprEvalContexts.back().Context) {
17371 case Sema::ExpressionEvaluationContext::Unevaluated:
17372 case Sema::ExpressionEvaluationContext::UnevaluatedList:
17373 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17374 return OdrUseContext::None;
17375
17376 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17377 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17378 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17379 Result = OdrUseContext::Used;
17380 break;
17381
17382 case Sema::ExpressionEvaluationContext::DiscardedStatement:
17383 Result = OdrUseContext::FormallyOdrUsed;
17384 break;
17385
17386 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17387 // A default argument formally results in odr-use, but doesn't actually
17388 // result in a use in any real sense until it itself is used.
17389 Result = OdrUseContext::FormallyOdrUsed;
17390 break;
17391 }
17392
17393 if (SemaRef.CurContext->isDependentContext())
17394 return OdrUseContext::Dependent;
17395
17396 return Result;
17397}
17398
17399static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17400 if (!Func->isConstexpr())
17401 return false;
17402
17403 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17404 return true;
17405 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17406 return CCD && CCD->getInheritedConstructor();
17407}
17408
17409/// Mark a function referenced, and check whether it is odr-used
17410/// (C++ [basic.def.odr]p2, C99 6.9p3)
17411void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17412 bool MightBeOdrUse) {
17413 assert(Func && "No function?")(static_cast <bool> (Func && "No function?") ? void
(0) : __assert_fail ("Func && \"No function?\"", "clang/lib/Sema/SemaExpr.cpp"
, 17413, __extension__ __PRETTY_FUNCTION__))
;
17414
17415 Func->setReferenced();
17416
17417 // Recursive functions aren't really used until they're used from some other
17418 // context.
17419 bool IsRecursiveCall = CurContext == Func;
17420
17421 // C++11 [basic.def.odr]p3:
17422 // A function whose name appears as a potentially-evaluated expression is
17423 // odr-used if it is the unique lookup result or the selected member of a
17424 // set of overloaded functions [...].
17425 //
17426 // We (incorrectly) mark overload resolution as an unevaluated context, so we
17427 // can just check that here.
17428 OdrUseContext OdrUse =
17429 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17430 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17431 OdrUse = OdrUseContext::FormallyOdrUsed;
17432
17433 // Trivial default constructors and destructors are never actually used.
17434 // FIXME: What about other special members?
17435 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17436 OdrUse == OdrUseContext::Used) {
17437 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17438 if (Constructor->isDefaultConstructor())
17439 OdrUse = OdrUseContext::FormallyOdrUsed;
17440 if (isa<CXXDestructorDecl>(Func))
17441 OdrUse = OdrUseContext::FormallyOdrUsed;
17442 }
17443
17444 // C++20 [expr.const]p12:
17445 // A function [...] is needed for constant evaluation if it is [...] a
17446 // constexpr function that is named by an expression that is potentially
17447 // constant evaluated
17448 bool NeededForConstantEvaluation =
17449 isPotentiallyConstantEvaluatedContext(*this) &&
17450 isImplicitlyDefinableConstexprFunction(Func);
17451
17452 // Determine whether we require a function definition to exist, per
17453 // C++11 [temp.inst]p3:
17454 // Unless a function template specialization has been explicitly
17455 // instantiated or explicitly specialized, the function template
17456 // specialization is implicitly instantiated when the specialization is
17457 // referenced in a context that requires a function definition to exist.
17458 // C++20 [temp.inst]p7:
17459 // The existence of a definition of a [...] function is considered to
17460 // affect the semantics of the program if the [...] function is needed for
17461 // constant evaluation by an expression
17462 // C++20 [basic.def.odr]p10:
17463 // Every program shall contain exactly one definition of every non-inline
17464 // function or variable that is odr-used in that program outside of a
17465 // discarded statement
17466 // C++20 [special]p1:
17467 // The implementation will implicitly define [defaulted special members]
17468 // if they are odr-used or needed for constant evaluation.
17469 //
17470 // Note that we skip the implicit instantiation of templates that are only
17471 // used in unused default arguments or by recursive calls to themselves.
17472 // This is formally non-conforming, but seems reasonable in practice.
17473 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17474 NeededForConstantEvaluation);
17475
17476 // C++14 [temp.expl.spec]p6:
17477 // If a template [...] is explicitly specialized then that specialization
17478 // shall be declared before the first use of that specialization that would
17479 // cause an implicit instantiation to take place, in every translation unit
17480 // in which such a use occurs
17481 if (NeedDefinition &&
17482 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17483 Func->getMemberSpecializationInfo()))
17484 checkSpecializationVisibility(Loc, Func);
17485
17486 if (getLangOpts().CUDA)
17487 CheckCUDACall(Loc, Func);
17488
17489 if (getLangOpts().SYCLIsDevice)
17490 checkSYCLDeviceFunction(Loc, Func);
17491
17492 // If we need a definition, try to create one.
17493 if (NeedDefinition && !Func->getBody()) {
17494 runWithSufficientStackSpace(Loc, [&] {
17495 if (CXXConstructorDecl *Constructor =
17496 dyn_cast<CXXConstructorDecl>(Func)) {
17497 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17498 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17499 if (Constructor->isDefaultConstructor()) {
17500 if (Constructor->isTrivial() &&
17501 !Constructor->hasAttr<DLLExportAttr>())
17502 return;
17503 DefineImplicitDefaultConstructor(Loc, Constructor);
17504 } else if (Constructor->isCopyConstructor()) {
17505 DefineImplicitCopyConstructor(Loc, Constructor);
17506 } else if (Constructor->isMoveConstructor()) {
17507 DefineImplicitMoveConstructor(Loc, Constructor);
17508 }
17509 } else if (Constructor->getInheritedConstructor()) {
17510 DefineInheritingConstructor(Loc, Constructor);
17511 }
17512 } else if (CXXDestructorDecl *Destructor =
17513 dyn_cast<CXXDestructorDecl>(Func)) {
17514 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17515 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17516 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17517 return;
17518 DefineImplicitDestructor(Loc, Destructor);
17519 }
17520 if (Destructor->isVirtual() && getLangOpts().AppleKext)
17521 MarkVTableUsed(Loc, Destructor->getParent());
17522 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17523 if (MethodDecl->isOverloadedOperator() &&
17524 MethodDecl->getOverloadedOperator() == OO_Equal) {
17525 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17526 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17527 if (MethodDecl->isCopyAssignmentOperator())
17528 DefineImplicitCopyAssignment(Loc, MethodDecl);
17529 else if (MethodDecl->isMoveAssignmentOperator())
17530 DefineImplicitMoveAssignment(Loc, MethodDecl);
17531 }
17532 } else if (isa<CXXConversionDecl>(MethodDecl) &&
17533 MethodDecl->getParent()->isLambda()) {
17534 CXXConversionDecl *Conversion =
17535 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17536 if (Conversion->isLambdaToBlockPointerConversion())
17537 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17538 else
17539 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17540 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17541 MarkVTableUsed(Loc, MethodDecl->getParent());
17542 }
17543
17544 if (Func->isDefaulted() && !Func->isDeleted()) {
17545 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17546 if (DCK != DefaultedComparisonKind::None)
17547 DefineDefaultedComparison(Loc, Func, DCK);
17548 }
17549
17550 // Implicit instantiation of function templates and member functions of
17551 // class templates.
17552 if (Func->isImplicitlyInstantiable()) {
17553 TemplateSpecializationKind TSK =
17554 Func->getTemplateSpecializationKindForInstantiation();
17555 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17556 bool FirstInstantiation = PointOfInstantiation.isInvalid();
17557 if (FirstInstantiation) {
17558 PointOfInstantiation = Loc;
17559 if (auto *MSI = Func->getMemberSpecializationInfo())
17560 MSI->setPointOfInstantiation(Loc);
17561 // FIXME: Notify listener.
17562 else
17563 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17564 } else if (TSK != TSK_ImplicitInstantiation) {
17565 // Use the point of use as the point of instantiation, instead of the
17566 // point of explicit instantiation (which we track as the actual point
17567 // of instantiation). This gives better backtraces in diagnostics.
17568 PointOfInstantiation = Loc;
17569 }
17570
17571 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17572 Func->isConstexpr()) {
17573 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17574 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17575 CodeSynthesisContexts.size())
17576 PendingLocalImplicitInstantiations.push_back(
17577 std::make_pair(Func, PointOfInstantiation));
17578 else if (Func->isConstexpr())
17579 // Do not defer instantiations of constexpr functions, to avoid the
17580 // expression evaluator needing to call back into Sema if it sees a
17581 // call to such a function.
17582 InstantiateFunctionDefinition(PointOfInstantiation, Func);
17583 else {
17584 Func->setInstantiationIsPending(true);
17585 PendingInstantiations.push_back(
17586 std::make_pair(Func, PointOfInstantiation));
17587 // Notify the consumer that a function was implicitly instantiated.
17588 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17589 }
17590 }
17591 } else {
17592 // Walk redefinitions, as some of them may be instantiable.
17593 for (auto i : Func->redecls()) {
17594 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17595 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17596 }
17597 }
17598 });
17599 }
17600
17601 // C++14 [except.spec]p17:
17602 // An exception-specification is considered to be needed when:
17603 // - the function is odr-used or, if it appears in an unevaluated operand,
17604 // would be odr-used if the expression were potentially-evaluated;
17605 //
17606 // Note, we do this even if MightBeOdrUse is false. That indicates that the
17607 // function is a pure virtual function we're calling, and in that case the
17608 // function was selected by overload resolution and we need to resolve its
17609 // exception specification for a different reason.
17610 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17611 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17612 ResolveExceptionSpec(Loc, FPT);
17613
17614 // If this is the first "real" use, act on that.
17615 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17616 // Keep track of used but undefined functions.
17617 if (!Func->isDefined()) {
17618 if (mightHaveNonExternalLinkage(Func))
17619 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17620 else if (Func->getMostRecentDecl()->isInlined() &&
17621 !LangOpts.GNUInline &&
17622 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17623 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17624 else if (isExternalWithNoLinkageType(Func))
17625 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17626 }
17627
17628 // Some x86 Windows calling conventions mangle the size of the parameter
17629 // pack into the name. Computing the size of the parameters requires the
17630 // parameter types to be complete. Check that now.
17631 if (funcHasParameterSizeMangling(*this, Func))
17632 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17633
17634 // In the MS C++ ABI, the compiler emits destructor variants where they are
17635 // used. If the destructor is used here but defined elsewhere, mark the
17636 // virtual base destructors referenced. If those virtual base destructors
17637 // are inline, this will ensure they are defined when emitting the complete
17638 // destructor variant. This checking may be redundant if the destructor is
17639 // provided later in this TU.
17640 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17641 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17642 CXXRecordDecl *Parent = Dtor->getParent();
17643 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17644 CheckCompleteDestructorVariant(Loc, Dtor);
17645 }
17646 }
17647
17648 Func->markUsed(Context);
17649 }
17650}
17651
17652/// Directly mark a variable odr-used. Given a choice, prefer to use
17653/// MarkVariableReferenced since it does additional checks and then
17654/// calls MarkVarDeclODRUsed.
17655/// If the variable must be captured:
17656/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17657/// - else capture it in the DeclContext that maps to the
17658/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17659static void
17660MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17661 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17662 // Keep track of used but undefined variables.
17663 // FIXME: We shouldn't suppress this warning for static data members.
17664 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17665 (!Var->isExternallyVisible() || Var->isInline() ||
17666 SemaRef.isExternalWithNoLinkageType(Var)) &&
17667 !(Var->isStaticDataMember() && Var->hasInit())) {
17668 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17669 if (old.isInvalid())
17670 old = Loc;
17671 }
17672 QualType CaptureType, DeclRefType;
17673 if (SemaRef.LangOpts.OpenMP)
17674 SemaRef.tryCaptureOpenMPLambdas(Var);
17675 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17676 /*EllipsisLoc*/ SourceLocation(),
17677 /*BuildAndDiagnose*/ true,
17678 CaptureType, DeclRefType,
17679 FunctionScopeIndexToStopAt);
17680
17681 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
17682 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
17683 auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
17684 auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
17685 if (VarTarget == Sema::CVT_Host &&
17686 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
17687 UserTarget == Sema::CFT_Global)) {
17688 // Diagnose ODR-use of host global variables in device functions.
17689 // Reference of device global variables in host functions is allowed
17690 // through shadow variables therefore it is not diagnosed.
17691 if (SemaRef.LangOpts.CUDAIsDevice) {
17692 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
17693 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
17694 SemaRef.targetDiag(Var->getLocation(),
17695 Var->getType().isConstQualified()
17696 ? diag::note_cuda_const_var_unpromoted
17697 : diag::note_cuda_host_var);
17698 }
17699 } else if (VarTarget == Sema::CVT_Device &&
17700 (UserTarget == Sema::CFT_Host ||
17701 UserTarget == Sema::CFT_HostDevice) &&
17702 !Var->hasExternalStorage()) {
17703 // Record a CUDA/HIP device side variable if it is ODR-used
17704 // by host code. This is done conservatively, when the variable is
17705 // referenced in any of the following contexts:
17706 // - a non-function context
17707 // - a host function
17708 // - a host device function
17709 // This makes the ODR-use of the device side variable by host code to
17710 // be visible in the device compilation for the compiler to be able to
17711 // emit template variables instantiated by host code only and to
17712 // externalize the static device side variable ODR-used by host code.
17713 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
17714 }
17715 }
17716
17717 Var->markUsed(SemaRef.Context);
17718}
17719
17720void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17721 SourceLocation Loc,
17722 unsigned CapturingScopeIndex) {
17723 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17724}
17725
17726static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17727 ValueDecl *var) {
17728 DeclContext *VarDC = var->getDeclContext();
17729
17730 // If the parameter still belongs to the translation unit, then
17731 // we're actually just using one parameter in the declaration of
17732 // the next.
17733 if (isa<ParmVarDecl>(var) &&
17734 isa<TranslationUnitDecl>(VarDC))
17735 return;
17736
17737 // For C code, don't diagnose about capture if we're not actually in code
17738 // right now; it's impossible to write a non-constant expression outside of
17739 // function context, so we'll get other (more useful) diagnostics later.
17740 //
17741 // For C++, things get a bit more nasty... it would be nice to suppress this
17742 // diagnostic for certain cases like using a local variable in an array bound
17743 // for a member of a local class, but the correct predicate is not obvious.
17744 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17745 return;
17746
17747 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17748 unsigned ContextKind = 3; // unknown
17749 if (isa<CXXMethodDecl>(VarDC) &&
17750 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17751 ContextKind = 2;
17752 } else if (isa<FunctionDecl>(VarDC)) {
17753 ContextKind = 0;
17754 } else if (isa<BlockDecl>(VarDC)) {
17755 ContextKind = 1;
17756 }
17757
17758 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17759 << var << ValueKind << ContextKind << VarDC;
17760 S.Diag(var->getLocation(), diag::note_entity_declared_at)
17761 << var;
17762
17763 // FIXME: Add additional diagnostic info about class etc. which prevents
17764 // capture.
17765}
17766
17767
17768static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17769 bool &SubCapturesAreNested,
17770 QualType &CaptureType,
17771 QualType &DeclRefType) {
17772 // Check whether we've already captured it.
17773 if (CSI->CaptureMap.count(Var)) {
17774 // If we found a capture, any subcaptures are nested.
17775 SubCapturesAreNested = true;
17776
17777 // Retrieve the capture type for this variable.
17778 CaptureType = CSI->getCapture(Var).getCaptureType();
17779
17780 // Compute the type of an expression that refers to this variable.
17781 DeclRefType = CaptureType.getNonReferenceType();
17782
17783 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17784 // are mutable in the sense that user can change their value - they are
17785 // private instances of the captured declarations.
17786 const Capture &Cap = CSI->getCapture(Var);
17787 if (Cap.isCopyCapture() &&
17788 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17789 !(isa<CapturedRegionScopeInfo>(CSI) &&
17790 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17791 DeclRefType.addConst();
17792 return true;
17793 }
17794 return false;
17795}
17796
17797// Only block literals, captured statements, and lambda expressions can
17798// capture; other scopes don't work.
17799static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17800 SourceLocation Loc,
17801 const bool Diagnose, Sema &S) {
17802 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17803 return getLambdaAwareParentOfDeclContext(DC);
17804 else if (Var->hasLocalStorage()) {
17805 if (Diagnose)
17806 diagnoseUncapturableValueReference(S, Loc, Var);
17807 }
17808 return nullptr;
17809}
17810
17811// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17812// certain types of variables (unnamed, variably modified types etc.)
17813// so check for eligibility.
17814static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17815 SourceLocation Loc,
17816 const bool Diagnose, Sema &S) {
17817
17818 bool IsBlock = isa<BlockScopeInfo>(CSI);
17819 bool IsLambda = isa<LambdaScopeInfo>(CSI);
17820
17821 // Lambdas are not allowed to capture unnamed variables
17822 // (e.g. anonymous unions).
17823 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17824 // assuming that's the intent.
17825 if (IsLambda && !Var->getDeclName()) {
17826 if (Diagnose) {
17827 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17828 S.Diag(Var->getLocation(), diag::note_declared_at);
17829 }
17830 return false;
17831 }
17832
17833 // Prohibit variably-modified types in blocks; they're difficult to deal with.
17834 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17835 if (Diagnose) {
17836 S.Diag(Loc, diag::err_ref_vm_type);
17837 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17838 }
17839 return false;
17840 }
17841 // Prohibit structs with flexible array members too.
17842 // We cannot capture what is in the tail end of the struct.
17843 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17844 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17845 if (Diagnose) {
17846 if (IsBlock)
17847 S.Diag(Loc, diag::err_ref_flexarray_type);
17848 else
17849 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17850 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17851 }
17852 return false;
17853 }
17854 }
17855 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17856 // Lambdas and captured statements are not allowed to capture __block
17857 // variables; they don't support the expected semantics.
17858 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17859 if (Diagnose) {
17860 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17861 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17862 }
17863 return false;
17864 }
17865 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17866 if (S.getLangOpts().OpenCL && IsBlock &&
17867 Var->getType()->isBlockPointerType()) {
17868 if (Diagnose)
17869 S.Diag(Loc, diag::err_opencl_block_ref_block);
17870 return false;
17871 }
17872
17873 return true;
17874}
17875
17876// Returns true if the capture by block was successful.
17877static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17878 SourceLocation Loc,
17879 const bool BuildAndDiagnose,
17880 QualType &CaptureType,
17881 QualType &DeclRefType,
17882 const bool Nested,
17883 Sema &S, bool Invalid) {
17884 bool ByRef = false;
17885
17886 // Blocks are not allowed to capture arrays, excepting OpenCL.
17887 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17888 // (decayed to pointers).
17889 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17890 if (BuildAndDiagnose) {
17891 S.Diag(Loc, diag::err_ref_array_type);
17892 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17893 Invalid = true;
17894 } else {
17895 return false;
17896 }
17897 }
17898
17899 // Forbid the block-capture of autoreleasing variables.
17900 if (!Invalid &&
17901 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17902 if (BuildAndDiagnose) {
17903 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17904 << /*block*/ 0;
17905 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17906 Invalid = true;
17907 } else {
17908 return false;
17909 }
17910 }
17911
17912 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17913 if (const auto *PT = CaptureType->getAs<PointerType>()) {
17914 QualType PointeeTy = PT->getPointeeType();
17915
17916 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17917 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17918 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17919 if (BuildAndDiagnose) {
17920 SourceLocation VarLoc = Var->getLocation();
17921 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17922 S.Diag(VarLoc, diag::note_declare_parameter_strong);
17923 }
17924 }
17925 }
17926
17927 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17928 if (HasBlocksAttr || CaptureType->isReferenceType() ||
17929 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17930 // Block capture by reference does not change the capture or
17931 // declaration reference types.
17932 ByRef = true;
17933 } else {
17934 // Block capture by copy introduces 'const'.
17935 CaptureType = CaptureType.getNonReferenceType().withConst();
17936 DeclRefType = CaptureType;
17937 }
17938
17939 // Actually capture the variable.
17940 if (BuildAndDiagnose)
17941 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17942 CaptureType, Invalid);
17943
17944 return !Invalid;
17945}
17946
17947
17948/// Capture the given variable in the captured region.
17949static bool captureInCapturedRegion(
17950 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
17951 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
17952 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
17953 bool IsTopScope, Sema &S, bool Invalid) {
17954 // By default, capture variables by reference.
17955 bool ByRef = true;
17956 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17957 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17958 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17959 // Using an LValue reference type is consistent with Lambdas (see below).
17960 if (S.isOpenMPCapturedDecl(Var)) {
17961 bool HasConst = DeclRefType.isConstQualified();
17962 DeclRefType = DeclRefType.getUnqualifiedType();
17963 // Don't lose diagnostics about assignments to const.
17964 if (HasConst)
17965 DeclRefType.addConst();
17966 }
17967 // Do not capture firstprivates in tasks.
17968 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17969 OMPC_unknown)
17970 return true;
17971 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17972 RSI->OpenMPCaptureLevel);
17973 }
17974
17975 if (ByRef)
17976 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17977 else
17978 CaptureType = DeclRefType;
17979
17980 // Actually capture the variable.
17981 if (BuildAndDiagnose)
17982 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17983 Loc, SourceLocation(), CaptureType, Invalid);
17984
17985 return !Invalid;
17986}
17987
17988/// Capture the given variable in the lambda.
17989static bool captureInLambda(LambdaScopeInfo *LSI,
17990 VarDecl *Var,
17991 SourceLocation Loc,
17992 const bool BuildAndDiagnose,
17993 QualType &CaptureType,
17994 QualType &DeclRefType,
17995 const bool RefersToCapturedVariable,
17996 const Sema::TryCaptureKind Kind,
17997 SourceLocation EllipsisLoc,
17998 const bool IsTopScope,
17999 Sema &S, bool Invalid) {
18000 // Determine whether we are capturing by reference or by value.
18001 bool ByRef = false;
18002 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18003 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18004 } else {
18005 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18006 }
18007
18008 // Compute the type of the field that will capture this variable.
18009 if (ByRef) {
18010 // C++11 [expr.prim.lambda]p15:
18011 // An entity is captured by reference if it is implicitly or
18012 // explicitly captured but not captured by copy. It is
18013 // unspecified whether additional unnamed non-static data
18014 // members are declared in the closure type for entities
18015 // captured by reference.
18016 //
18017 // FIXME: It is not clear whether we want to build an lvalue reference
18018 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18019 // to do the former, while EDG does the latter. Core issue 1249 will
18020 // clarify, but for now we follow GCC because it's a more permissive and
18021 // easily defensible position.
18022 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18023 } else {
18024 // C++11 [expr.prim.lambda]p14:
18025 // For each entity captured by copy, an unnamed non-static
18026 // data member is declared in the closure type. The
18027 // declaration order of these members is unspecified. The type
18028 // of such a data member is the type of the corresponding
18029 // captured entity if the entity is not a reference to an
18030 // object, or the referenced type otherwise. [Note: If the
18031 // captured entity is a reference to a function, the
18032 // corresponding data member is also a reference to a
18033 // function. - end note ]
18034 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18035 if (!RefType->getPointeeType()->isFunctionType())
18036 CaptureType = RefType->getPointeeType();
18037 }
18038
18039 // Forbid the lambda copy-capture of autoreleasing variables.
18040 if (!Invalid &&
18041 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18042 if (BuildAndDiagnose) {
18043 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18044 S.Diag(Var->getLocation(), diag::note_previous_decl)
18045 << Var->getDeclName();
18046 Invalid = true;
18047 } else {
18048 return false;
18049 }
18050 }
18051
18052 // Make sure that by-copy captures are of a complete and non-abstract type.
18053 if (!Invalid && BuildAndDiagnose) {
18054 if (!CaptureType->isDependentType() &&
18055 S.RequireCompleteSizedType(
18056 Loc, CaptureType,
18057 diag::err_capture_of_incomplete_or_sizeless_type,
18058 Var->getDeclName()))
18059 Invalid = true;
18060 else if (S.RequireNonAbstractType(Loc, CaptureType,
18061 diag::err_capture_of_abstract_type))
18062 Invalid = true;
18063 }
18064 }
18065
18066 // Compute the type of a reference to this captured variable.
18067 if (ByRef)
18068 DeclRefType = CaptureType.getNonReferenceType();
18069 else {
18070 // C++ [expr.prim.lambda]p5:
18071 // The closure type for a lambda-expression has a public inline
18072 // function call operator [...]. This function call operator is
18073 // declared const (9.3.1) if and only if the lambda-expression's
18074 // parameter-declaration-clause is not followed by mutable.
18075 DeclRefType = CaptureType.getNonReferenceType();
18076 if (!LSI->Mutable && !CaptureType->isReferenceType())
18077 DeclRefType.addConst();
18078 }
18079
18080 // Add the capture.
18081 if (BuildAndDiagnose)
18082 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18083 Loc, EllipsisLoc, CaptureType, Invalid);
18084
18085 return !Invalid;
18086}
18087
18088static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
18089 // Offer a Copy fix even if the type is dependent.
18090 if (Var->getType()->isDependentType())
18091 return true;
18092 QualType T = Var->getType().getNonReferenceType();
18093 if (T.isTriviallyCopyableType(Context))
18094 return true;
18095 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18096
18097 if (!(RD = RD->getDefinition()))
18098 return false;
18099 if (RD->hasSimpleCopyConstructor())
18100 return true;
18101 if (RD->hasUserDeclaredCopyConstructor())
18102 for (CXXConstructorDecl *Ctor : RD->ctors())
18103 if (Ctor->isCopyConstructor())
18104 return !Ctor->isDeleted();
18105 }
18106 return false;
18107}
18108
18109/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18110/// default capture. Fixes may be omitted if they aren't allowed by the
18111/// standard, for example we can't emit a default copy capture fix-it if we
18112/// already explicitly copy capture capture another variable.
18113static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
18114 VarDecl *Var) {
18115 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", 18115, __extension__ __PRETTY_FUNCTION__
))
;
18116 // Don't offer Capture by copy of default capture by copy fixes if Var is
18117 // known not to be copy constructible.
18118 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18119
18120 SmallString<32> FixBuffer;
18121 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18122 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18123 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18124 if (ShouldOfferCopyFix) {
18125 // Offer fixes to insert an explicit capture for the variable.
18126 // [] -> [VarName]
18127 // [OtherCapture] -> [OtherCapture, VarName]
18128 FixBuffer.assign({Separator, Var->getName()});
18129 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18130 << Var << /*value*/ 0
18131 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18132 }
18133 // As above but capture by reference.
18134 FixBuffer.assign({Separator, "&", Var->getName()});
18135 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18136 << Var << /*reference*/ 1
18137 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18138 }
18139
18140 // Only try to offer default capture if there are no captures excluding this
18141 // and init captures.
18142 // [this]: OK.
18143 // [X = Y]: OK.
18144 // [&A, &B]: Don't offer.
18145 // [A, B]: Don't offer.
18146 if (llvm::any_of(LSI->Captures, [](Capture &C) {
18147 return !C.isThisCapture() && !C.isInitCapture();
18148 }))
18149 return;
18150
18151 // The default capture specifiers, '=' or '&', must appear first in the
18152 // capture body.
18153 SourceLocation DefaultInsertLoc =
18154 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
18155
18156 if (ShouldOfferCopyFix) {
18157 bool CanDefaultCopyCapture = true;
18158 // [=, *this] OK since c++17
18159 // [=, this] OK since c++20
18160 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18161 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18162 ? LSI->getCXXThisCapture().isCopyCapture()
18163 : false;
18164 // We can't use default capture by copy if any captures already specified
18165 // capture by copy.
18166 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18167 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18168 })) {
18169 FixBuffer.assign({"=", Separator});
18170 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18171 << /*value*/ 0
18172 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18173 }
18174 }
18175
18176 // We can't use default capture by reference if any captures already specified
18177 // capture by reference.
18178 if (llvm::none_of(LSI->Captures, [](Capture &C) {
18179 return !C.isInitCapture() && C.isReferenceCapture() &&
18180 !C.isThisCapture();
18181 })) {
18182 FixBuffer.assign({"&", Separator});
18183 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18184 << /*reference*/ 1
18185 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18186 }
18187}
18188
18189bool Sema::tryCaptureVariable(
18190 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18191 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18192 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18193 // An init-capture is notionally from the context surrounding its
18194 // declaration, but its parent DC is the lambda class.
18195 DeclContext *VarDC = Var->getDeclContext();
18196 if (Var->isInitCapture())
18197 VarDC = VarDC->getParent();
18198
18199 DeclContext *DC = CurContext;
18200 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18201 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18202 // We need to sync up the Declaration Context with the
18203 // FunctionScopeIndexToStopAt
18204 if (FunctionScopeIndexToStopAt) {
18205 unsigned FSIndex = FunctionScopes.size() - 1;
18206 while (FSIndex != MaxFunctionScopesIndex) {
18207 DC = getLambdaAwareParentOfDeclContext(DC);
18208 --FSIndex;
18209 }
18210 }
18211
18212
18213 // If the variable is declared in the current context, there is no need to
18214 // capture it.
18215 if (VarDC == DC) return true;
18216
18217 // Capture global variables if it is required to use private copy of this
18218 // variable.
18219 bool IsGlobal = !Var->hasLocalStorage();
18220 if (IsGlobal &&
18221 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18222 MaxFunctionScopesIndex)))
18223 return true;
18224 Var = Var->getCanonicalDecl();
18225
18226 // Walk up the stack to determine whether we can capture the variable,
18227 // performing the "simple" checks that don't depend on type. We stop when
18228 // we've either hit the declared scope of the variable or find an existing
18229 // capture of that variable. We start from the innermost capturing-entity
18230 // (the DC) and ensure that all intervening capturing-entities
18231 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18232 // declcontext can either capture the variable or have already captured
18233 // the variable.
18234 CaptureType = Var->getType();
18235 DeclRefType = CaptureType.getNonReferenceType();
18236 bool Nested = false;
18237 bool Explicit = (Kind != TryCapture_Implicit);
18238 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18239 do {
18240 // Only block literals, captured statements, and lambda expressions can
18241 // capture; other scopes don't work.
18242 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
18243 ExprLoc,
18244 BuildAndDiagnose,
18245 *this);
18246 // We need to check for the parent *first* because, if we *have*
18247 // private-captured a global variable, we need to recursively capture it in
18248 // intermediate blocks, lambdas, etc.
18249 if (!ParentDC) {
18250 if (IsGlobal) {
18251 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18252 break;
18253 }
18254 return true;
18255 }
18256
18257 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
18258 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18259
18260
18261 // Check whether we've already captured it.
18262 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18263 DeclRefType)) {
18264 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18265 break;
18266 }
18267 // If we are instantiating a generic lambda call operator body,
18268 // we do not want to capture new variables. What was captured
18269 // during either a lambdas transformation or initial parsing
18270 // should be used.
18271 if (isGenericLambdaCallOperatorSpecialization(DC)) {
18272 if (BuildAndDiagnose) {
18273 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18274 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18275 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18276 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18277 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18278 buildLambdaCaptureFixit(*this, LSI, Var);
18279 } else
18280 diagnoseUncapturableValueReference(*this, ExprLoc, Var);
18281 }
18282 return true;
18283 }
18284
18285 // Try to capture variable-length arrays types.
18286 if (Var->getType()->isVariablyModifiedType()) {
18287 // We're going to walk down into the type and look for VLA
18288 // expressions.
18289 QualType QTy = Var->getType();
18290 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18291 QTy = PVD->getOriginalType();
18292 captureVariablyModifiedType(Context, QTy, CSI);
18293 }
18294
18295 if (getLangOpts().OpenMP) {
18296 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18297 // OpenMP private variables should not be captured in outer scope, so
18298 // just break here. Similarly, global variables that are captured in a
18299 // target region should not be captured outside the scope of the region.
18300 if (RSI->CapRegionKind == CR_OpenMP) {
18301 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
18302 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18303 // If the variable is private (i.e. not captured) and has variably
18304 // modified type, we still need to capture the type for correct
18305 // codegen in all regions, associated with the construct. Currently,
18306 // it is captured in the innermost captured region only.
18307 if (IsOpenMPPrivateDecl != OMPC_unknown &&
18308 Var->getType()->isVariablyModifiedType()) {
18309 QualType QTy = Var->getType();
18310 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18311 QTy = PVD->getOriginalType();
18312 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
18313 I < E; ++I) {
18314 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18315 FunctionScopes[FunctionScopesIndex - I]);
18316 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", 18318, __extension__ __PRETTY_FUNCTION__
))
18317 "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", 18318, __extension__ __PRETTY_FUNCTION__
))
18318 "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", 18318, __extension__ __PRETTY_FUNCTION__
))
;
18319 captureVariablyModifiedType(Context, QTy, OuterRSI);
18320 }
18321 }
18322 bool IsTargetCap =
18323 IsOpenMPPrivateDecl != OMPC_private &&
18324 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18325 RSI->OpenMPCaptureLevel);
18326 // Do not capture global if it is not privatized in outer regions.
18327 bool IsGlobalCap =
18328 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18329 RSI->OpenMPCaptureLevel);
18330
18331 // When we detect target captures we are looking from inside the
18332 // target region, therefore we need to propagate the capture from the
18333 // enclosing region. Therefore, the capture is not initially nested.
18334 if (IsTargetCap)
18335 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18336
18337 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18338 (IsGlobal && !IsGlobalCap)) {
18339 Nested = !IsTargetCap;
18340 bool HasConst = DeclRefType.isConstQualified();
18341 DeclRefType = DeclRefType.getUnqualifiedType();
18342 // Don't lose diagnostics about assignments to const.
18343 if (HasConst)
18344 DeclRefType.addConst();
18345 CaptureType = Context.getLValueReferenceType(DeclRefType);
18346 break;
18347 }
18348 }
18349 }
18350 }
18351 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18352 // No capture-default, and this is not an explicit capture
18353 // so cannot capture this variable.
18354 if (BuildAndDiagnose) {
18355 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18356 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18357 auto *LSI = cast<LambdaScopeInfo>(CSI);
18358 if (LSI->Lambda) {
18359 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18360 buildLambdaCaptureFixit(*this, LSI, Var);
18361 }
18362 // FIXME: If we error out because an outer lambda can not implicitly
18363 // capture a variable that an inner lambda explicitly captures, we
18364 // should have the inner lambda do the explicit capture - because
18365 // it makes for cleaner diagnostics later. This would purely be done
18366 // so that the diagnostic does not misleadingly claim that a variable
18367 // can not be captured by a lambda implicitly even though it is captured
18368 // explicitly. Suggestion:
18369 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18370 // at the function head
18371 // - cache the StartingDeclContext - this must be a lambda
18372 // - captureInLambda in the innermost lambda the variable.
18373 }
18374 return true;
18375 }
18376
18377 FunctionScopesIndex--;
18378 DC = ParentDC;
18379 Explicit = false;
18380 } while (!VarDC->Equals(DC));
18381
18382 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18383 // computing the type of the capture at each step, checking type-specific
18384 // requirements, and adding captures if requested.
18385 // If the variable had already been captured previously, we start capturing
18386 // at the lambda nested within that one.
18387 bool Invalid = false;
18388 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18389 ++I) {
18390 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18391
18392 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18393 // certain types of variables (unnamed, variably modified types etc.)
18394 // so check for eligibility.
18395 if (!Invalid)
18396 Invalid =
18397 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18398
18399 // After encountering an error, if we're actually supposed to capture, keep
18400 // capturing in nested contexts to suppress any follow-on diagnostics.
18401 if (Invalid && !BuildAndDiagnose)
18402 return true;
18403
18404 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18405 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18406 DeclRefType, Nested, *this, Invalid);
18407 Nested = true;
18408 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18409 Invalid = !captureInCapturedRegion(
18410 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18411 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18412 Nested = true;
18413 } else {
18414 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18415 Invalid =
18416 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18417 DeclRefType, Nested, Kind, EllipsisLoc,
18418 /*IsTopScope*/ I == N - 1, *this, Invalid);
18419 Nested = true;
18420 }
18421
18422 if (Invalid && !BuildAndDiagnose)
18423 return true;
18424 }
18425 return Invalid;
18426}
18427
18428bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18429 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18430 QualType CaptureType;
18431 QualType DeclRefType;
18432 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18433 /*BuildAndDiagnose=*/true, CaptureType,
18434 DeclRefType, nullptr);
18435}
18436
18437bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18438 QualType CaptureType;
18439 QualType DeclRefType;
18440 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18441 /*BuildAndDiagnose=*/false, CaptureType,
18442 DeclRefType, nullptr);
18443}
18444
18445QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18446 QualType CaptureType;
18447 QualType DeclRefType;
18448
18449 // Determine whether we can capture this variable.
18450 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18451 /*BuildAndDiagnose=*/false, CaptureType,
18452 DeclRefType, nullptr))
18453 return QualType();
18454
18455 return DeclRefType;
18456}
18457
18458namespace {
18459// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18460// The produced TemplateArgumentListInfo* points to data stored within this
18461// object, so should only be used in contexts where the pointer will not be
18462// used after the CopiedTemplateArgs object is destroyed.
18463class CopiedTemplateArgs {
18464 bool HasArgs;
18465 TemplateArgumentListInfo TemplateArgStorage;
18466public:
18467 template<typename RefExpr>
18468 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18469 if (HasArgs)
18470 E->copyTemplateArgumentsInto(TemplateArgStorage);
18471 }
18472 operator TemplateArgumentListInfo*()
18473#ifdef __has_cpp_attribute
18474#if0 __has_cpp_attribute(clang::lifetimebound)1
18475 [[clang::lifetimebound]]
18476#endif
18477#endif
18478 {
18479 return HasArgs ? &TemplateArgStorage : nullptr;
18480 }
18481};
18482}
18483
18484/// Walk the set of potential results of an expression and mark them all as
18485/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18486///
18487/// \return A new expression if we found any potential results, ExprEmpty() if
18488/// not, and ExprError() if we diagnosed an error.
18489static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18490 NonOdrUseReason NOUR) {
18491 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18492 // an object that satisfies the requirements for appearing in a
18493 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18494 // is immediately applied." This function handles the lvalue-to-rvalue
18495 // conversion part.
18496 //
18497 // If we encounter a node that claims to be an odr-use but shouldn't be, we
18498 // transform it into the relevant kind of non-odr-use node and rebuild the
18499 // tree of nodes leading to it.
18500 //
18501 // This is a mini-TreeTransform that only transforms a restricted subset of
18502 // nodes (and only certain operands of them).
18503
18504 // Rebuild a subexpression.
18505 auto Rebuild = [&](Expr *Sub) {
18506 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18507 };
18508
18509 // Check whether a potential result satisfies the requirements of NOUR.
18510 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18511 // Any entity other than a VarDecl is always odr-used whenever it's named
18512 // in a potentially-evaluated expression.
18513 auto *VD = dyn_cast<VarDecl>(D);
18514 if (!VD)
18515 return true;
18516
18517 // C++2a [basic.def.odr]p4:
18518 // A variable x whose name appears as a potentially-evalauted expression
18519 // e is odr-used by e unless
18520 // -- x is a reference that is usable in constant expressions, or
18521 // -- x is a variable of non-reference type that is usable in constant
18522 // expressions and has no mutable subobjects, and e is an element of
18523 // the set of potential results of an expression of
18524 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
18525 // conversion is applied, or
18526 // -- x is a variable of non-reference type, and e is an element of the
18527 // set of potential results of a discarded-value expression to which
18528 // the lvalue-to-rvalue conversion is not applied
18529 //
18530 // We check the first bullet and the "potentially-evaluated" condition in
18531 // BuildDeclRefExpr. We check the type requirements in the second bullet
18532 // in CheckLValueToRValueConversionOperand below.
18533 switch (NOUR) {
18534 case NOUR_None:
18535 case NOUR_Unevaluated:
18536 llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason"
, "clang/lib/Sema/SemaExpr.cpp", 18536)
;
18537
18538 case NOUR_Constant:
18539 // Constant references were handled when they were built.
18540 if (VD->getType()->isReferenceType())
18541 return true;
18542 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18543 if (RD->hasMutableFields())
18544 return true;
18545 if (!VD->isUsableInConstantExpressions(S.Context))
18546 return true;
18547 break;
18548
18549 case NOUR_Discarded:
18550 if (VD->getType()->isReferenceType())
18551 return true;
18552 break;
18553 }
18554 return false;
18555 };
18556
18557 // Mark that this expression does not constitute an odr-use.
18558 auto MarkNotOdrUsed = [&] {
18559 S.MaybeODRUseExprs.remove(E);
18560 if (LambdaScopeInfo *LSI = S.getCurLambda())
18561 LSI->markVariableExprAsNonODRUsed(E);
18562 };
18563
18564 // C++2a [basic.def.odr]p2:
18565 // The set of potential results of an expression e is defined as follows:
18566 switch (E->getStmtClass()) {
18567 // -- If e is an id-expression, ...
18568 case Expr::DeclRefExprClass: {
18569 auto *DRE = cast<DeclRefExpr>(E);
18570 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18571 break;
18572
18573 // Rebuild as a non-odr-use DeclRefExpr.
18574 MarkNotOdrUsed();
18575 return DeclRefExpr::Create(
18576 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18577 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18578 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18579 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18580 }
18581
18582 case Expr::FunctionParmPackExprClass: {
18583 auto *FPPE = cast<FunctionParmPackExpr>(E);
18584 // If any of the declarations in the pack is odr-used, then the expression
18585 // as a whole constitutes an odr-use.
18586 for (VarDecl *D : *FPPE)
18587 if (IsPotentialResultOdrUsed(D))
18588 return ExprEmpty();
18589
18590 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18591 // nothing cares about whether we marked this as an odr-use, but it might
18592 // be useful for non-compiler tools.
18593 MarkNotOdrUsed();
18594 break;
18595 }
18596
18597 // -- If e is a subscripting operation with an array operand...
18598 case Expr::ArraySubscriptExprClass: {
18599 auto *ASE = cast<ArraySubscriptExpr>(E);
18600 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18601 if (!OldBase->getType()->isArrayType())
18602 break;
18603 ExprResult Base = Rebuild(OldBase);
18604 if (!Base.isUsable())
18605 return Base;
18606 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18607 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18608 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18609 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
18610 ASE->getRBracketLoc());
18611 }
18612
18613 case Expr::MemberExprClass: {
18614 auto *ME = cast<MemberExpr>(E);
18615 // -- If e is a class member access expression [...] naming a non-static
18616 // data member...
18617 if (isa<FieldDecl>(ME->getMemberDecl())) {
18618 ExprResult Base = Rebuild(ME->getBase());
18619 if (!Base.isUsable())
18620 return Base;
18621 return MemberExpr::Create(
18622 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
18623 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
18624 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
18625 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
18626 ME->getObjectKind(), ME->isNonOdrUse());
18627 }
18628
18629 if (ME->getMemberDecl()->isCXXInstanceMember())
18630 break;
18631
18632 // -- If e is a class member access expression naming a static data member,
18633 // ...
18634 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
18635 break;
18636
18637 // Rebuild as a non-odr-use MemberExpr.
18638 MarkNotOdrUsed();
18639 return MemberExpr::Create(
18640 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
18641 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
18642 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
18643 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
18644 }
18645
18646 case Expr::BinaryOperatorClass: {
18647 auto *BO = cast<BinaryOperator>(E);
18648 Expr *LHS = BO->getLHS();
18649 Expr *RHS = BO->getRHS();
18650 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
18651 if (BO->getOpcode() == BO_PtrMemD) {
18652 ExprResult Sub = Rebuild(LHS);
18653 if (!Sub.isUsable())
18654 return Sub;
18655 LHS = Sub.get();
18656 // -- If e is a comma expression, ...
18657 } else if (BO->getOpcode() == BO_Comma) {
18658 ExprResult Sub = Rebuild(RHS);
18659 if (!Sub.isUsable())
18660 return Sub;
18661 RHS = Sub.get();
18662 } else {
18663 break;
18664 }
18665 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18666 LHS, RHS);
18667 }
18668
18669 // -- If e has the form (e1)...
18670 case Expr::ParenExprClass: {
18671 auto *PE = cast<ParenExpr>(E);
18672 ExprResult Sub = Rebuild(PE->getSubExpr());
18673 if (!Sub.isUsable())
18674 return Sub;
18675 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18676 }
18677
18678 // -- If e is a glvalue conditional expression, ...
18679 // We don't apply this to a binary conditional operator. FIXME: Should we?
18680 case Expr::ConditionalOperatorClass: {
18681 auto *CO = cast<ConditionalOperator>(E);
18682 ExprResult LHS = Rebuild(CO->getLHS());
18683 if (LHS.isInvalid())
18684 return ExprError();
18685 ExprResult RHS = Rebuild(CO->getRHS());
18686 if (RHS.isInvalid())
18687 return ExprError();
18688 if (!LHS.isUsable() && !RHS.isUsable())
18689 return ExprEmpty();
18690 if (!LHS.isUsable())
18691 LHS = CO->getLHS();
18692 if (!RHS.isUsable())
18693 RHS = CO->getRHS();
18694 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18695 CO->getCond(), LHS.get(), RHS.get());
18696 }
18697
18698 // [Clang extension]
18699 // -- If e has the form __extension__ e1...
18700 case Expr::UnaryOperatorClass: {
18701 auto *UO = cast<UnaryOperator>(E);
18702 if (UO->getOpcode() != UO_Extension)
18703 break;
18704 ExprResult Sub = Rebuild(UO->getSubExpr());
18705 if (!Sub.isUsable())
18706 return Sub;
18707 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18708 Sub.get());
18709 }
18710
18711 // [Clang extension]
18712 // -- If e has the form _Generic(...), the set of potential results is the
18713 // union of the sets of potential results of the associated expressions.
18714 case Expr::GenericSelectionExprClass: {
18715 auto *GSE = cast<GenericSelectionExpr>(E);
18716
18717 SmallVector<Expr *, 4> AssocExprs;
18718 bool AnyChanged = false;
18719 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18720 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18721 if (AssocExpr.isInvalid())
18722 return ExprError();
18723 if (AssocExpr.isUsable()) {
18724 AssocExprs.push_back(AssocExpr.get());
18725 AnyChanged = true;
18726 } else {
18727 AssocExprs.push_back(OrigAssocExpr);
18728 }
18729 }
18730
18731 return AnyChanged ? S.CreateGenericSelectionExpr(
18732 GSE->getGenericLoc(), GSE->getDefaultLoc(),
18733 GSE->getRParenLoc(), GSE->getControllingExpr(),
18734 GSE->getAssocTypeSourceInfos(), AssocExprs)
18735 : ExprEmpty();
18736 }
18737
18738 // [Clang extension]
18739 // -- If e has the form __builtin_choose_expr(...), the set of potential
18740 // results is the union of the sets of potential results of the
18741 // second and third subexpressions.
18742 case Expr::ChooseExprClass: {
18743 auto *CE = cast<ChooseExpr>(E);
18744
18745 ExprResult LHS = Rebuild(CE->getLHS());
18746 if (LHS.isInvalid())
18747 return ExprError();
18748
18749 ExprResult RHS = Rebuild(CE->getLHS());
18750 if (RHS.isInvalid())
18751 return ExprError();
18752
18753 if (!LHS.get() && !RHS.get())
18754 return ExprEmpty();
18755 if (!LHS.isUsable())
18756 LHS = CE->getLHS();
18757 if (!RHS.isUsable())
18758 RHS = CE->getRHS();
18759
18760 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18761 RHS.get(), CE->getRParenLoc());
18762 }
18763
18764 // Step through non-syntactic nodes.
18765 case Expr::ConstantExprClass: {
18766 auto *CE = cast<ConstantExpr>(E);
18767 ExprResult Sub = Rebuild(CE->getSubExpr());
18768 if (!Sub.isUsable())
18769 return Sub;
18770 return ConstantExpr::Create(S.Context, Sub.get());
18771 }
18772
18773 // We could mostly rely on the recursive rebuilding to rebuild implicit
18774 // casts, but not at the top level, so rebuild them here.
18775 case Expr::ImplicitCastExprClass: {
18776 auto *ICE = cast<ImplicitCastExpr>(E);
18777 // Only step through the narrow set of cast kinds we expect to encounter.
18778 // Anything else suggests we've left the region in which potential results
18779 // can be found.
18780 switch (ICE->getCastKind()) {
18781 case CK_NoOp:
18782 case CK_DerivedToBase:
18783 case CK_UncheckedDerivedToBase: {
18784 ExprResult Sub = Rebuild(ICE->getSubExpr());
18785 if (!Sub.isUsable())
18786 return Sub;
18787 CXXCastPath Path(ICE->path());
18788 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18789 ICE->getValueKind(), &Path);
18790 }
18791
18792 default:
18793 break;
18794 }
18795 break;
18796 }
18797
18798 default:
18799 break;
18800 }
18801
18802 // Can't traverse through this node. Nothing to do.
18803 return ExprEmpty();
18804}
18805
18806ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18807 // Check whether the operand is or contains an object of non-trivial C union
18808 // type.
18809 if (E->getType().isVolatileQualified() &&
18810 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18811 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18812 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18813 Sema::NTCUC_LValueToRValueVolatile,
18814 NTCUK_Destruct|NTCUK_Copy);
18815
18816 // C++2a [basic.def.odr]p4:
18817 // [...] an expression of non-volatile-qualified non-class type to which
18818 // the lvalue-to-rvalue conversion is applied [...]
18819 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18820 return E;
18821
18822 ExprResult Result =
18823 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18824 if (Result.isInvalid())
18825 return ExprError();
18826 return Result.get() ? Result : E;
18827}
18828
18829ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18830 Res = CorrectDelayedTyposInExpr(Res);
18831
18832 if (!Res.isUsable())
18833 return Res;
18834
18835 // If a constant-expression is a reference to a variable where we delay
18836 // deciding whether it is an odr-use, just assume we will apply the
18837 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
18838 // (a non-type template argument), we have special handling anyway.
18839 return CheckLValueToRValueConversionOperand(Res.get());
18840}
18841
18842void Sema::CleanupVarDeclMarking() {
18843 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18844 // call.
18845 MaybeODRUseExprSet LocalMaybeODRUseExprs;
18846 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18847
18848 for (Expr *E : LocalMaybeODRUseExprs) {
18849 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18850 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18851 DRE->getLocation(), *this);
18852 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18853 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18854 *this);
18855 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18856 for (VarDecl *VD : *FP)
18857 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18858 } else {
18859 llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "clang/lib/Sema/SemaExpr.cpp"
, 18859)
;
18860 }
18861 }
18862
18863 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", 18864, __extension__ __PRETTY_FUNCTION__
))
18864 "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", 18864, __extension__ __PRETTY_FUNCTION__
))
;
18865}
18866
18867static void DoMarkVarDeclReferenced(
18868 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
18869 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18870 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", 18872, __extension__ __PRETTY_FUNCTION__
))
18871 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", 18872, __extension__ __PRETTY_FUNCTION__
))
18872 "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", 18872, __extension__ __PRETTY_FUNCTION__
))
;
18873 Var->setReferenced();
18874
18875 if (Var->isInvalidDecl())
18876 return;
18877
18878 auto *MSI = Var->getMemberSpecializationInfo();
18879 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18880 : Var->getTemplateSpecializationKind();
18881
18882 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18883 bool UsableInConstantExpr =
18884 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18885
18886 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
18887 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
18888 }
18889
18890 // C++20 [expr.const]p12:
18891 // A variable [...] is needed for constant evaluation if it is [...] a
18892 // variable whose name appears as a potentially constant evaluated
18893 // expression that is either a contexpr variable or is of non-volatile
18894 // const-qualified integral type or of reference type
18895 bool NeededForConstantEvaluation =
18896 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18897
18898 bool NeedDefinition =
18899 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18900
18901 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", 18902, __extension__ __PRETTY_FUNCTION__
))
18902 "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", 18902, __extension__ __PRETTY_FUNCTION__
))
;
18903
18904 // If this might be a member specialization of a static data member, check
18905 // the specialization is visible. We already did the checks for variable
18906 // template specializations when we created them.
18907 if (NeedDefinition && TSK != TSK_Undeclared &&
18908 !isa<VarTemplateSpecializationDecl>(Var))
18909 SemaRef.checkSpecializationVisibility(Loc, Var);
18910
18911 // Perform implicit instantiation of static data members, static data member
18912 // templates of class templates, and variable template specializations. Delay
18913 // instantiations of variable templates, except for those that could be used
18914 // in a constant expression.
18915 if (NeedDefinition && isTemplateInstantiation(TSK)) {
18916 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18917 // instantiation declaration if a variable is usable in a constant
18918 // expression (among other cases).
18919 bool TryInstantiating =
18920 TSK == TSK_ImplicitInstantiation ||
18921 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18922
18923 if (TryInstantiating) {
18924 SourceLocation PointOfInstantiation =
18925 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18926 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18927 if (FirstInstantiation) {
18928 PointOfInstantiation = Loc;
18929 if (MSI)
18930 MSI->setPointOfInstantiation(PointOfInstantiation);
18931 // FIXME: Notify listener.
18932 else
18933 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18934 }
18935
18936 if (UsableInConstantExpr) {
18937 // Do not defer instantiations of variables that could be used in a
18938 // constant expression.
18939 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18940 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18941 });
18942
18943 // Re-set the member to trigger a recomputation of the dependence bits
18944 // for the expression.
18945 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18946 DRE->setDecl(DRE->getDecl());
18947 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18948 ME->setMemberDecl(ME->getMemberDecl());
18949 } else if (FirstInstantiation ||
18950 isa<VarTemplateSpecializationDecl>(Var)) {
18951 // FIXME: For a specialization of a variable template, we don't
18952 // distinguish between "declaration and type implicitly instantiated"
18953 // and "implicit instantiation of definition requested", so we have
18954 // no direct way to avoid enqueueing the pending instantiation
18955 // multiple times.
18956 SemaRef.PendingInstantiations
18957 .push_back(std::make_pair(Var, PointOfInstantiation));
18958 }
18959 }
18960 }
18961
18962 // C++2a [basic.def.odr]p4:
18963 // A variable x whose name appears as a potentially-evaluated expression e
18964 // is odr-used by e unless
18965 // -- x is a reference that is usable in constant expressions
18966 // -- x is a variable of non-reference type that is usable in constant
18967 // expressions and has no mutable subobjects [FIXME], and e is an
18968 // element of the set of potential results of an expression of
18969 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
18970 // conversion is applied
18971 // -- x is a variable of non-reference type, and e is an element of the set
18972 // of potential results of a discarded-value expression to which the
18973 // lvalue-to-rvalue conversion is not applied [FIXME]
18974 //
18975 // We check the first part of the second bullet here, and
18976 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18977 // FIXME: To get the third bullet right, we need to delay this even for
18978 // variables that are not usable in constant expressions.
18979
18980 // If we already know this isn't an odr-use, there's nothing more to do.
18981 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18982 if (DRE->isNonOdrUse())
18983 return;
18984 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18985 if (ME->isNonOdrUse())
18986 return;
18987
18988 switch (OdrUse) {
18989 case OdrUseContext::None:
18990 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", 18991, __extension__ __PRETTY_FUNCTION__
))
18991 "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", 18991, __extension__ __PRETTY_FUNCTION__
))
;
18992 break;
18993
18994 case OdrUseContext::FormallyOdrUsed:
18995 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18996 // behavior.
18997 break;
18998
18999 case OdrUseContext::Used:
19000 // If we might later find that this expression isn't actually an odr-use,
19001 // delay the marking.
19002 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19003 SemaRef.MaybeODRUseExprs.insert(E);
19004 else
19005 MarkVarDeclODRUsed(Var, Loc, SemaRef);
19006 break;
19007
19008 case OdrUseContext::Dependent:
19009 // If this is a dependent context, we don't need to mark variables as
19010 // odr-used, but we may still need to track them for lambda capture.
19011 // FIXME: Do we also need to do this inside dependent typeid expressions
19012 // (which are modeled as unevaluated at this point)?
19013 const bool RefersToEnclosingScope =
19014 (SemaRef.CurContext != Var->getDeclContext() &&
19015 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
19016 if (RefersToEnclosingScope) {
19017 LambdaScopeInfo *const LSI =
19018 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19019 if (LSI && (!LSI->CallOperator ||
19020 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19021 // If a variable could potentially be odr-used, defer marking it so
19022 // until we finish analyzing the full expression for any
19023 // lvalue-to-rvalue
19024 // or discarded value conversions that would obviate odr-use.
19025 // Add it to the list of potential captures that will be analyzed
19026 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19027 // unless the variable is a reference that was initialized by a constant
19028 // expression (this will never need to be captured or odr-used).
19029 //
19030 // FIXME: We can simplify this a lot after implementing P0588R1.
19031 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", 19031, __extension__ __PRETTY_FUNCTION__
))
;
19032 if (!Var->getType()->isReferenceType() ||
19033 !Var->isUsableInConstantExpressions(SemaRef.Context))
19034 LSI->addPotentialCapture(E->IgnoreParens());
19035 }
19036 }
19037 break;
19038 }
19039}
19040
19041/// Mark a variable referenced, and check whether it is odr-used
19042/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
19043/// used directly for normal expressions referring to VarDecl.
19044void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
19045 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19046}
19047
19048static void
19049MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
19050 bool MightBeOdrUse,
19051 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19052 if (SemaRef.isInOpenMPDeclareTargetContext())
19053 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
19054
19055 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19056 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
19057 return;
19058 }
19059
19060 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19061
19062 // If this is a call to a method via a cast, also mark the method in the
19063 // derived class used in case codegen can devirtualize the call.
19064 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19065 if (!ME)
19066 return;
19067 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19068 if (!MD)
19069 return;
19070 // Only attempt to devirtualize if this is truly a virtual call.
19071 bool IsVirtualCall = MD->isVirtual() &&
19072 ME->performsVirtualDispatch(SemaRef.getLangOpts());
19073 if (!IsVirtualCall)
19074 return;
19075
19076 // If it's possible to devirtualize the call, mark the called function
19077 // referenced.
19078 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
19079 ME->getBase(), SemaRef.getLangOpts().AppleKext);
19080 if (DM)
19081 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19082}
19083
19084/// Perform reference-marking and odr-use handling for a DeclRefExpr.
19085///
19086/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19087/// handled with care if the DeclRefExpr is not newly-created.
19088void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
19089 // TODO: update this with DR# once a defect report is filed.
19090 // C++11 defect. The address of a pure member should not be an ODR use, even
19091 // if it's a qualified reference.
19092 bool OdrUse = true;
19093 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19094 if (Method->isVirtual() &&
19095 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19096 OdrUse = false;
19097
19098 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
19099 if (!isUnevaluatedContext() && !isConstantEvaluated() &&
19100 FD->isConsteval() && !RebuildingImmediateInvocation)
19101 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19102 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19103 RefsMinusAssignments);
19104}
19105
19106/// Perform reference-marking and odr-use handling for a MemberExpr.
19107void Sema::MarkMemberReferenced(MemberExpr *E) {
19108 // C++11 [basic.def.odr]p2:
19109 // A non-overloaded function whose name appears as a potentially-evaluated
19110 // expression or a member of a set of candidate functions, if selected by
19111 // overload resolution when referred to from a potentially-evaluated
19112 // expression, is odr-used, unless it is a pure virtual function and its
19113 // name is not explicitly qualified.
19114 bool MightBeOdrUse = true;
19115 if (E->performsVirtualDispatch(getLangOpts())) {
19116 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19117 if (Method->isPure())
19118 MightBeOdrUse = false;
19119 }
19120 SourceLocation Loc =
19121 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19122 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19123 RefsMinusAssignments);
19124}
19125
19126/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
19127void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
19128 for (VarDecl *VD : *E)
19129 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19130 RefsMinusAssignments);
19131}
19132
19133/// Perform marking for a reference to an arbitrary declaration. It
19134/// marks the declaration referenced, and performs odr-use checking for
19135/// functions and variables. This method should not be used when building a
19136/// normal expression which refers to a variable.
19137void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
19138 bool MightBeOdrUse) {
19139 if (MightBeOdrUse) {
19140 if (auto *VD = dyn_cast<VarDecl>(D)) {
19141 MarkVariableReferenced(Loc, VD);
19142 return;
19143 }
19144 }
19145 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19146 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19147 return;
19148 }
19149 D->setReferenced();
19150}
19151
19152namespace {
19153 // Mark all of the declarations used by a type as referenced.
19154 // FIXME: Not fully implemented yet! We need to have a better understanding
19155 // of when we're entering a context we should not recurse into.
19156 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19157 // TreeTransforms rebuilding the type in a new context. Rather than
19158 // duplicating the TreeTransform logic, we should consider reusing it here.
19159 // Currently that causes problems when rebuilding LambdaExprs.
19160 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19161 Sema &S;
19162 SourceLocation Loc;
19163
19164 public:
19165 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
19166
19167 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19168
19169 bool TraverseTemplateArgument(const TemplateArgument &Arg);
19170 };
19171}
19172
19173bool MarkReferencedDecls::TraverseTemplateArgument(
19174 const TemplateArgument &Arg) {
19175 {
19176 // A non-type template argument is a constant-evaluated context.
19177 EnterExpressionEvaluationContext Evaluated(
19178 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
19179 if (Arg.getKind() == TemplateArgument::Declaration) {
19180 if (Decl *D = Arg.getAsDecl())
19181 S.MarkAnyDeclReferenced(Loc, D, true);
19182 } else if (Arg.getKind() == TemplateArgument::Expression) {
19183 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
19184 }
19185 }
19186
19187 return Inherited::TraverseTemplateArgument(Arg);
19188}
19189
19190void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
19191 MarkReferencedDecls Marker(*this, Loc);
19192 Marker.TraverseType(T);
19193}
19194
19195namespace {
19196/// Helper class that marks all of the declarations referenced by
19197/// potentially-evaluated subexpressions as "referenced".
19198class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19199public:
19200 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19201 bool SkipLocalVariables;
19202 ArrayRef<const Expr *> StopAt;
19203
19204 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19205 ArrayRef<const Expr *> StopAt)
19206 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19207
19208 void visitUsedDecl(SourceLocation Loc, Decl *D) {
19209 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19210 }
19211
19212 void Visit(Expr *E) {
19213 if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end())
19214 return;
19215 Inherited::Visit(E);
19216 }
19217
19218 void VisitDeclRefExpr(DeclRefExpr *E) {
19219 // If we were asked not to visit local variables, don't.
19220 if (SkipLocalVariables) {
19221 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19222 if (VD->hasLocalStorage())
19223 return;
19224 }
19225
19226 // FIXME: This can trigger the instantiation of the initializer of a
19227 // variable, which can cause the expression to become value-dependent
19228 // or error-dependent. Do we need to propagate the new dependence bits?
19229 S.MarkDeclRefReferenced(E);
19230 }
19231
19232 void VisitMemberExpr(MemberExpr *E) {
19233 S.MarkMemberReferenced(E);
19234 Visit(E->getBase());
19235 }
19236};
19237} // namespace
19238
19239/// Mark any declarations that appear within this expression or any
19240/// potentially-evaluated subexpressions as "referenced".
19241///
19242/// \param SkipLocalVariables If true, don't mark local variables as
19243/// 'referenced'.
19244/// \param StopAt Subexpressions that we shouldn't recurse into.
19245void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
19246 bool SkipLocalVariables,
19247 ArrayRef<const Expr*> StopAt) {
19248 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19249}
19250
19251/// Emit a diagnostic when statements are reachable.
19252/// FIXME: check for reachability even in expressions for which we don't build a
19253/// CFG (eg, in the initializer of a global or in a constant expression).
19254/// For example,
19255/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19256bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
19257 const PartialDiagnostic &PD) {
19258 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19259 if (!FunctionScopes.empty())
19260 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19261 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
19262 return true;
19263 }
19264
19265 // The initializer of a constexpr variable or of the first declaration of a
19266 // static data member is not syntactically a constant evaluated constant,
19267 // but nonetheless is always required to be a constant expression, so we
19268 // can skip diagnosing.
19269 // FIXME: Using the mangling context here is a hack.
19270 if (auto *VD = dyn_cast_or_null<VarDecl>(
19271 ExprEvalContexts.back().ManglingContextDecl)) {
19272 if (VD->isConstexpr() ||
19273 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19274 return false;
19275 // FIXME: For any other kind of variable, we should build a CFG for its
19276 // initializer and check whether the context in question is reachable.
19277 }
19278
19279 Diag(Loc, PD);
19280 return true;
19281}
19282
19283/// Emit a diagnostic that describes an effect on the run-time behavior
19284/// of the program being compiled.
19285///
19286/// This routine emits the given diagnostic when the code currently being
19287/// type-checked is "potentially evaluated", meaning that there is a
19288/// possibility that the code will actually be executable. Code in sizeof()
19289/// expressions, code used only during overload resolution, etc., are not
19290/// potentially evaluated. This routine will suppress such diagnostics or,
19291/// in the absolutely nutty case of potentially potentially evaluated
19292/// expressions (C++ typeid), queue the diagnostic to potentially emit it
19293/// later.
19294///
19295/// This routine should be used for all diagnostics that describe the run-time
19296/// behavior of a program, such as passing a non-POD value through an ellipsis.
19297/// Failure to do so will likely result in spurious diagnostics or failures
19298/// during overload resolution or within sizeof/alignof/typeof/typeid.
19299bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19300 const PartialDiagnostic &PD) {
19301
19302 if (ExprEvalContexts.back().isDiscardedStatementContext())
19303 return false;
19304
19305 switch (ExprEvalContexts.back().Context) {
19306 case ExpressionEvaluationContext::Unevaluated:
19307 case ExpressionEvaluationContext::UnevaluatedList:
19308 case ExpressionEvaluationContext::UnevaluatedAbstract:
19309 case ExpressionEvaluationContext::DiscardedStatement:
19310 // The argument will never be evaluated, so don't complain.
19311 break;
19312
19313 case ExpressionEvaluationContext::ConstantEvaluated:
19314 case ExpressionEvaluationContext::ImmediateFunctionContext:
19315 // Relevant diagnostics should be produced by constant evaluation.
19316 break;
19317
19318 case ExpressionEvaluationContext::PotentiallyEvaluated:
19319 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19320 return DiagIfReachable(Loc, Stmts, PD);
19321 }
19322
19323 return false;
19324}
19325
19326bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19327 const PartialDiagnostic &PD) {
19328 return DiagRuntimeBehavior(
19329 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
19330}
19331
19332bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19333 CallExpr *CE, FunctionDecl *FD) {
19334 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19335 return false;
19336
19337 // If we're inside a decltype's expression, don't check for a valid return
19338 // type or construct temporaries until we know whether this is the last call.
19339 if (ExprEvalContexts.back().ExprContext ==
19340 ExpressionEvaluationContextRecord::EK_Decltype) {
19341 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19342 return false;
19343 }
19344
19345 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19346 FunctionDecl *FD;
19347 CallExpr *CE;
19348
19349 public:
19350 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19351 : FD(FD), CE(CE) { }
19352
19353 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19354 if (!FD) {
19355 S.Diag(Loc, diag::err_call_incomplete_return)
19356 << T << CE->getSourceRange();
19357 return;
19358 }
19359
19360 S.Diag(Loc, diag::err_call_function_incomplete_return)
19361 << CE->getSourceRange() << FD << T;
19362 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19363 << FD->getDeclName();
19364 }
19365 } Diagnoser(FD, CE);
19366
19367 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19368 return true;
19369
19370 return false;
19371}
19372
19373// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19374// will prevent this condition from triggering, which is what we want.
19375void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19376 SourceLocation Loc;
19377
19378 unsigned diagnostic = diag::warn_condition_is_assignment;
19379 bool IsOrAssign = false;
19380
19381 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19382 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19383 return;
19384
19385 IsOrAssign = Op->getOpcode() == BO_OrAssign;
19386
19387 // Greylist some idioms by putting them into a warning subcategory.
19388 if (ObjCMessageExpr *ME
19389 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19390 Selector Sel = ME->getSelector();
19391
19392 // self = [<foo> init...]
19393 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19394 diagnostic = diag::warn_condition_is_idiomatic_assignment;
19395
19396 // <foo> = [<bar> nextObject]
19397 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19398 diagnostic = diag::warn_condition_is_idiomatic_assignment;
19399 }
19400
19401 Loc = Op->getOperatorLoc();
19402 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19403 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19404 return;
19405
19406 IsOrAssign = Op->getOperator() == OO_PipeEqual;
19407 Loc = Op->getOperatorLoc();
19408 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19409 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19410 else {
19411 // Not an assignment.
19412 return;
19413 }
19414
19415 Diag(Loc, diagnostic) << E->getSourceRange();
19416
19417 SourceLocation Open = E->getBeginLoc();
19418 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19419 Diag(Loc, diag::note_condition_assign_silence)
19420 << FixItHint::CreateInsertion(Open, "(")
19421 << FixItHint::CreateInsertion(Close, ")");
19422
19423 if (IsOrAssign)
19424 Diag(Loc, diag::note_condition_or_assign_to_comparison)
19425 << FixItHint::CreateReplacement(Loc, "!=");
19426 else
19427 Diag(Loc, diag::note_condition_assign_to_comparison)
19428 << FixItHint::CreateReplacement(Loc, "==");
19429}
19430
19431/// Redundant parentheses over an equality comparison can indicate
19432/// that the user intended an assignment used as condition.
19433void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19434 // Don't warn if the parens came from a macro.
19435 SourceLocation parenLoc = ParenE->getBeginLoc();
19436 if (parenLoc.isInvalid() || parenLoc.isMacroID())
19437 return;
19438 // Don't warn for dependent expressions.
19439 if (ParenE->isTypeDependent())
19440 return;
19441
19442 Expr *E = ParenE->IgnoreParens();
19443
19444 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19445 if (opE->getOpcode() == BO_EQ &&
19446 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19447 == Expr::MLV_Valid) {
19448 SourceLocation Loc = opE->getOperatorLoc();
19449
19450 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19451 SourceRange ParenERange = ParenE->getSourceRange();
19452 Diag(Loc, diag::note_equality_comparison_silence)
19453 << FixItHint::CreateRemoval(ParenERange.getBegin())
19454 << FixItHint::CreateRemoval(ParenERange.getEnd());
19455 Diag(Loc, diag::note_equality_comparison_to_assign)
19456 << FixItHint::CreateReplacement(Loc, "=");
19457 }
19458}
19459
19460ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19461 bool IsConstexpr) {
19462 DiagnoseAssignmentAsCondition(E);
19463 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19464 DiagnoseEqualityWithExtraParens(parenE);
19465
19466 ExprResult result = CheckPlaceholderExpr(E);
19467 if (result.isInvalid()) return ExprError();
19468 E = result.get();
19469
19470 if (!E->isTypeDependent()) {
19471 if (getLangOpts().CPlusPlus)
19472 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19473
19474 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19475 if (ERes.isInvalid())
19476 return ExprError();
19477 E = ERes.get();
19478
19479 QualType T = E->getType();
19480 if (!T->isScalarType()) { // C99 6.8.4.1p1
19481 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19482 << T << E->getSourceRange();
19483 return ExprError();
19484 }
19485 CheckBoolLikeConversion(E, Loc);
19486 }
19487
19488 return E;
19489}
19490
19491Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19492 Expr *SubExpr, ConditionKind CK,
19493 bool MissingOK) {
19494 // MissingOK indicates whether having no condition expression is valid
19495 // (for loop) or invalid (e.g. while loop).
19496 if (!SubExpr)
19497 return MissingOK ? ConditionResult() : ConditionError();
19498
19499 ExprResult Cond;
19500 switch (CK) {
19501 case ConditionKind::Boolean:
19502 Cond = CheckBooleanCondition(Loc, SubExpr);
19503 break;
19504
19505 case ConditionKind::ConstexprIf:
19506 Cond = CheckBooleanCondition(Loc, SubExpr, true);
19507 break;
19508
19509 case ConditionKind::Switch:
19510 Cond = CheckSwitchCondition(Loc, SubExpr);
19511 break;
19512 }
19513 if (Cond.isInvalid()) {
19514 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19515 {SubExpr}, PreferredConditionType(CK));
19516 if (!Cond.get())
19517 return ConditionError();
19518 }
19519 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19520 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19521 if (!FullExpr.get())
19522 return ConditionError();
19523
19524 return ConditionResult(*this, nullptr, FullExpr,
19525 CK == ConditionKind::ConstexprIf);
19526}
19527
19528namespace {
19529 /// A visitor for rebuilding a call to an __unknown_any expression
19530 /// to have an appropriate type.
19531 struct RebuildUnknownAnyFunction
19532 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19533
19534 Sema &S;
19535
19536 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19537
19538 ExprResult VisitStmt(Stmt *S) {
19539 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp"
, 19539)
;
19540 }
19541
19542 ExprResult VisitExpr(Expr *E) {
19543 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19544 << E->getSourceRange();
19545 return ExprError();
19546 }
19547
19548 /// Rebuild an expression which simply semantically wraps another
19549 /// expression which it shares the type and value kind of.
19550 template <class T> ExprResult rebuildSugarExpr(T *E) {
19551 ExprResult SubResult = Visit(E->getSubExpr());
19552 if (SubResult.isInvalid()) return ExprError();
19553
19554 Expr *SubExpr = SubResult.get();
19555 E->setSubExpr(SubExpr);
19556 E->setType(SubExpr->getType());
19557 E->setValueKind(SubExpr->getValueKind());
19558 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", 19558, __extension__ __PRETTY_FUNCTION__
))
;
19559 return E;
19560 }
19561
19562 ExprResult VisitParenExpr(ParenExpr *E) {
19563 return rebuildSugarExpr(E);
19564 }
19565
19566 ExprResult VisitUnaryExtension(UnaryOperator *E) {
19567 return rebuildSugarExpr(E);
19568 }
19569
19570 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19571 ExprResult SubResult = Visit(E->getSubExpr());
19572 if (SubResult.isInvalid()) return ExprError();
19573
19574 Expr *SubExpr = SubResult.get();
19575 E->setSubExpr(SubExpr);
19576 E->setType(S.Context.getPointerType(SubExpr->getType()));
19577 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 19577, __extension__
__PRETTY_FUNCTION__))
;
19578 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", 19578, __extension__ __PRETTY_FUNCTION__
))
;
19579 return E;
19580 }
19581
19582 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
19583 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
19584
19585 E->setType(VD->getType());
19586
19587 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 19587, __extension__
__PRETTY_FUNCTION__))
;
19588 if (S.getLangOpts().CPlusPlus &&
19589 !(isa<CXXMethodDecl>(VD) &&
19590 cast<CXXMethodDecl>(VD)->isInstance()))
19591 E->setValueKind(VK_LValue);
19592
19593 return E;
19594 }
19595
19596 ExprResult VisitMemberExpr(MemberExpr *E) {
19597 return resolveDecl(E, E->getMemberDecl());
19598 }
19599
19600 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19601 return resolveDecl(E, E->getDecl());
19602 }
19603 };
19604}
19605
19606/// Given a function expression of unknown-any type, try to rebuild it
19607/// to have a function type.
19608static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19609 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
19610 if (Result.isInvalid()) return ExprError();
19611 return S.DefaultFunctionArrayConversion(Result.get());
19612}
19613
19614namespace {
19615 /// A visitor for rebuilding an expression of type __unknown_anytype
19616 /// into one which resolves the type directly on the referring
19617 /// expression. Strict preservation of the original source
19618 /// structure is not a goal.
19619 struct RebuildUnknownAnyExpr
19620 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
19621
19622 Sema &S;
19623
19624 /// The current destination type.
19625 QualType DestType;
19626
19627 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
19628 : S(S), DestType(CastType) {}
19629
19630 ExprResult VisitStmt(Stmt *S) {
19631 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp"
, 19631)
;
19632 }
19633
19634 ExprResult VisitExpr(Expr *E) {
19635 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19636 << E->getSourceRange();
19637 return ExprError();
19638 }
19639
19640 ExprResult VisitCallExpr(CallExpr *E);
19641 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
19642
19643 /// Rebuild an expression which simply semantically wraps another
19644 /// expression which it shares the type and value kind of.
19645 template <class T> ExprResult rebuildSugarExpr(T *E) {
19646 ExprResult SubResult = Visit(E->getSubExpr());
19647 if (SubResult.isInvalid()) return ExprError();
19648 Expr *SubExpr = SubResult.get();
19649 E->setSubExpr(SubExpr);
19650 E->setType(SubExpr->getType());
19651 E->setValueKind(SubExpr->getValueKind());
19652 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", 19652, __extension__ __PRETTY_FUNCTION__
))
;
19653 return E;
19654 }
19655
19656 ExprResult VisitParenExpr(ParenExpr *E) {
19657 return rebuildSugarExpr(E);
19658 }
19659
19660 ExprResult VisitUnaryExtension(UnaryOperator *E) {
19661 return rebuildSugarExpr(E);
19662 }
19663
19664 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19665 const PointerType *Ptr = DestType->getAs<PointerType>();
19666 if (!Ptr) {
19667 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
19668 << E->getSourceRange();
19669 return ExprError();
19670 }
19671
19672 if (isa<CallExpr>(E->getSubExpr())) {
19673 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
19674 << E->getSourceRange();
19675 return ExprError();
19676 }
19677
19678 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 19678, __extension__
__PRETTY_FUNCTION__))
;
19679 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", 19679, __extension__ __PRETTY_FUNCTION__
))
;
19680 E->setType(DestType);
19681
19682 // Build the sub-expression as if it were an object of the pointee type.
19683 DestType = Ptr->getPointeeType();
19684 ExprResult SubResult = Visit(E->getSubExpr());
19685 if (SubResult.isInvalid()) return ExprError();
19686 E->setSubExpr(SubResult.get());
19687 return E;
19688 }
19689
19690 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
19691
19692 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
19693
19694 ExprResult VisitMemberExpr(MemberExpr *E) {
19695 return resolveDecl(E, E->getMemberDecl());
19696 }
19697
19698 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19699 return resolveDecl(E, E->getDecl());
19700 }
19701 };
19702}
19703
19704/// Rebuilds a call expression which yielded __unknown_anytype.
19705ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19706 Expr *CalleeExpr = E->getCallee();
19707
19708 enum FnKind {
19709 FK_MemberFunction,
19710 FK_FunctionPointer,
19711 FK_BlockPointer
19712 };
19713
19714 FnKind Kind;
19715 QualType CalleeType = CalleeExpr->getType();
19716 if (CalleeType == S.Context.BoundMemberTy) {
19717 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", 19717, __extension__ __PRETTY_FUNCTION__
))
;
19718 Kind = FK_MemberFunction;
19719 CalleeType = Expr::findBoundMemberType(CalleeExpr);
19720 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19721 CalleeType = Ptr->getPointeeType();
19722 Kind = FK_FunctionPointer;
19723 } else {
19724 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19725 Kind = FK_BlockPointer;
19726 }
19727 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19728
19729 // Verify that this is a legal result type of a function.
19730 if (DestType->isArrayType() || DestType->isFunctionType()) {
19731 unsigned diagID = diag::err_func_returning_array_function;
19732 if (Kind == FK_BlockPointer)
19733 diagID = diag::err_block_returning_array_function;
19734
19735 S.Diag(E->getExprLoc(), diagID)
19736 << DestType->isFunctionType() << DestType;
19737 return ExprError();
19738 }
19739
19740 // Otherwise, go ahead and set DestType as the call's result.
19741 E->setType(DestType.getNonLValueExprType(S.Context));
19742 E->setValueKind(Expr::getValueKindForType(DestType));
19743 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", 19743, __extension__ __PRETTY_FUNCTION__
))
;
19744
19745 // Rebuild the function type, replacing the result type with DestType.
19746 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19747 if (Proto) {
19748 // __unknown_anytype(...) is a special case used by the debugger when
19749 // it has no idea what a function's signature is.
19750 //
19751 // We want to build this call essentially under the K&R
19752 // unprototyped rules, but making a FunctionNoProtoType in C++
19753 // would foul up all sorts of assumptions. However, we cannot
19754 // simply pass all arguments as variadic arguments, nor can we
19755 // portably just call the function under a non-variadic type; see
19756 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19757 // However, it turns out that in practice it is generally safe to
19758 // call a function declared as "A foo(B,C,D);" under the prototype
19759 // "A foo(B,C,D,...);". The only known exception is with the
19760 // Windows ABI, where any variadic function is implicitly cdecl
19761 // regardless of its normal CC. Therefore we change the parameter
19762 // types to match the types of the arguments.
19763 //
19764 // This is a hack, but it is far superior to moving the
19765 // corresponding target-specific code from IR-gen to Sema/AST.
19766
19767 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19768 SmallVector<QualType, 8> ArgTypes;
19769 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19770 ArgTypes.reserve(E->getNumArgs());
19771 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19772 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
19773 }
19774 ParamTypes = ArgTypes;
19775 }
19776 DestType = S.Context.getFunctionType(DestType, ParamTypes,
19777 Proto->getExtProtoInfo());
19778 } else {
19779 DestType = S.Context.getFunctionNoProtoType(DestType,
19780 FnType->getExtInfo());
19781 }
19782
19783 // Rebuild the appropriate pointer-to-function type.
19784 switch (Kind) {
19785 case FK_MemberFunction:
19786 // Nothing to do.
19787 break;
19788
19789 case FK_FunctionPointer:
19790 DestType = S.Context.getPointerType(DestType);
19791 break;
19792
19793 case FK_BlockPointer:
19794 DestType = S.Context.getBlockPointerType(DestType);
19795 break;
19796 }
19797
19798 // Finally, we can recurse.
19799 ExprResult CalleeResult = Visit(CalleeExpr);
19800 if (!CalleeResult.isUsable()) return ExprError();
19801 E->setCallee(CalleeResult.get());
19802
19803 // Bind a temporary if necessary.
19804 return S.MaybeBindToTemporary(E);
19805}
19806
19807ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19808 // Verify that this is a legal result type of a call.
19809 if (DestType->isArrayType() || DestType->isFunctionType()) {
19810 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19811 << DestType->isFunctionType() << DestType;
19812 return ExprError();
19813 }
19814
19815 // Rewrite the method result type if available.
19816 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19817 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", 19817, __extension__ __PRETTY_FUNCTION__
))
;
19818 Method->setReturnType(DestType);
19819 }
19820
19821 // Change the type of the message.
19822 E->setType(DestType.getNonReferenceType());
19823 E->setValueKind(Expr::getValueKindForType(DestType));
19824
19825 return S.MaybeBindToTemporary(E);
19826}
19827
19828ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19829 // The only case we should ever see here is a function-to-pointer decay.
19830 if (E->getCastKind() == CK_FunctionToPointerDecay) {
19831 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 19831, __extension__
__PRETTY_FUNCTION__))
;
19832 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", 19832, __extension__ __PRETTY_FUNCTION__
))
;
19833
19834 E->setType(DestType);
19835
19836 // Rebuild the sub-expression as the pointee (function) type.
19837 DestType = DestType->castAs<PointerType>()->getPointeeType();
19838
19839 ExprResult Result = Visit(E->getSubExpr());
19840 if (!Result.isUsable()) return ExprError();
19841
19842 E->setSubExpr(Result.get());
19843 return E;
19844 } else if (E->getCastKind() == CK_LValueToRValue) {
19845 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 19845, __extension__
__PRETTY_FUNCTION__))
;
19846 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", 19846, __extension__ __PRETTY_FUNCTION__
))
;
19847
19848 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", 19848, __extension__ __PRETTY_FUNCTION__
))
;
19849
19850 E->setType(DestType);
19851
19852 // The sub-expression has to be a lvalue reference, so rebuild it as such.
19853 DestType = S.Context.getLValueReferenceType(DestType);
19854
19855 ExprResult Result = Visit(E->getSubExpr());
19856 if (!Result.isUsable()) return ExprError();
19857
19858 E->setSubExpr(Result.get());
19859 return E;
19860 } else {
19861 llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "clang/lib/Sema/SemaExpr.cpp"
, 19861)
;
19862 }
19863}
19864
19865ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19866 ExprValueKind ValueKind = VK_LValue;
19867 QualType Type = DestType;
19868
19869 // We know how to make this work for certain kinds of decls:
19870
19871 // - functions
19872 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19873 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19874 DestType = Ptr->getPointeeType();
19875 ExprResult Result = resolveDecl(E, VD);
19876 if (Result.isInvalid()) return ExprError();
19877 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
19878 VK_PRValue);
19879 }
19880
19881 if (!Type->isFunctionType()) {
19882 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19883 << VD << E->getSourceRange();
19884 return ExprError();
19885 }
19886 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19887 // We must match the FunctionDecl's type to the hack introduced in
19888 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19889 // type. See the lengthy commentary in that routine.
19890 QualType FDT = FD->getType();
19891 const FunctionType *FnType = FDT->castAs<FunctionType>();
19892 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19893 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19894 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19895 SourceLocation Loc = FD->getLocation();
19896 FunctionDecl *NewFD = FunctionDecl::Create(
19897 S.Context, FD->getDeclContext(), Loc, Loc,
19898 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19899 SC_None, S.getCurFPFeatures().isFPConstrained(),
19900 false /*isInlineSpecified*/, FD->hasPrototype(),
19901 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19902
19903 if (FD->getQualifier())
19904 NewFD->setQualifierInfo(FD->getQualifierLoc());
19905
19906 SmallVector<ParmVarDecl*, 16> Params;
19907 for (const auto &AI : FT->param_types()) {
19908 ParmVarDecl *Param =
19909 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19910 Param->setScopeInfo(0, Params.size());
19911 Params.push_back(Param);
19912 }
19913 NewFD->setParams(Params);
19914 DRE->setDecl(NewFD);
19915 VD = DRE->getDecl();
19916 }
19917 }
19918
19919 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19920 if (MD->isInstance()) {
19921 ValueKind = VK_PRValue;
19922 Type = S.Context.BoundMemberTy;
19923 }
19924
19925 // Function references aren't l-values in C.
19926 if (!S.getLangOpts().CPlusPlus)
19927 ValueKind = VK_PRValue;
19928
19929 // - variables
19930 } else if (isa<VarDecl>(VD)) {
19931 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19932 Type = RefTy->getPointeeType();
19933 } else if (Type->isFunctionType()) {
19934 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19935 << VD << E->getSourceRange();
19936 return ExprError();
19937 }
19938
19939 // - nothing else
19940 } else {
19941 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19942 << VD << E->getSourceRange();
19943 return ExprError();
19944 }
19945
19946 // Modifying the declaration like this is friendly to IR-gen but
19947 // also really dangerous.
19948 VD->setType(DestType);
19949 E->setType(Type);
19950 E->setValueKind(ValueKind);
19951 return E;
19952}
19953
19954/// Check a cast of an unknown-any type. We intentionally only
19955/// trigger this for C-style casts.
19956ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19957 Expr *CastExpr, CastKind &CastKind,
19958 ExprValueKind &VK, CXXCastPath &Path) {
19959 // The type we're casting to must be either void or complete.
19960 if (!CastType->isVoidType() &&
19961 RequireCompleteType(TypeRange.getBegin(), CastType,
19962 diag::err_typecheck_cast_to_incomplete))
19963 return ExprError();
19964
19965 // Rewrite the casted expression from scratch.
19966 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19967 if (!result.isUsable()) return ExprError();
19968
19969 CastExpr = result.get();
19970 VK = CastExpr->getValueKind();
19971 CastKind = CK_NoOp;
19972
19973 return CastExpr;
19974}
19975
19976ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19977 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19978}
19979
19980ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19981 Expr *arg, QualType &paramType) {
19982 // If the syntactic form of the argument is not an explicit cast of
19983 // any sort, just do default argument promotion.
19984 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19985 if (!castArg) {
19986 ExprResult result = DefaultArgumentPromotion(arg);
19987 if (result.isInvalid()) return ExprError();
19988 paramType = result.get()->getType();
19989 return result;
19990 }
19991
19992 // Otherwise, use the type that was written in the explicit cast.
19993 assert(!arg->hasPlaceholderType())(static_cast <bool> (!arg->hasPlaceholderType()) ? void
(0) : __assert_fail ("!arg->hasPlaceholderType()", "clang/lib/Sema/SemaExpr.cpp"
, 19993, __extension__ __PRETTY_FUNCTION__))
;
19994 paramType = castArg->getTypeAsWritten();
19995
19996 // Copy-initialize a parameter of that type.
19997 InitializedEntity entity =
19998 InitializedEntity::InitializeParameter(Context, paramType,
19999 /*consumed*/ false);
20000 return PerformCopyInitialization(entity, callLoc, arg);
20001}
20002
20003static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
20004 Expr *orig = E;
20005 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20006 while (true) {
20007 E = E->IgnoreParenImpCasts();
20008 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20009 E = call->getCallee();
20010 diagID = diag::err_uncasted_call_of_unknown_any;
20011 } else {
20012 break;
20013 }
20014 }
20015
20016 SourceLocation loc;
20017 NamedDecl *d;
20018 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20019 loc = ref->getLocation();
20020 d = ref->getDecl();
20021 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20022 loc = mem->getMemberLoc();
20023 d = mem->getMemberDecl();
20024 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20025 diagID = diag::err_uncasted_call_of_unknown_any;
20026 loc = msg->getSelectorStartLoc();
20027 d = msg->getMethodDecl();
20028 if (!d) {
20029 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20030 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20031 << orig->getSourceRange();
20032 return ExprError();
20033 }
20034 } else {
20035 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20036 << E->getSourceRange();
20037 return ExprError();
20038 }
20039
20040 S.Diag(loc, diagID) << d << orig->getSourceRange();
20041
20042 // Never recoverable.
20043 return ExprError();
20044}
20045
20046/// Check for operands with placeholder types and complain if found.
20047/// Returns ExprError() if there was an error and no recovery was possible.
20048ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
20049 if (!Context.isDependenceAllowed()) {
20050 // C cannot handle TypoExpr nodes on either side of a binop because it
20051 // doesn't handle dependent types properly, so make sure any TypoExprs have
20052 // been dealt with before checking the operands.
20053 ExprResult Result = CorrectDelayedTyposInExpr(E);
20054 if (!Result.isUsable()) return ExprError();
20055 E = Result.get();
20056 }
20057
20058 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20059 if (!placeholderType) return E;
20060
20061 switch (placeholderType->getKind()) {
20062
20063 // Overloaded expressions.
20064 case BuiltinType::Overload: {
20065 // Try to resolve a single function template specialization.
20066 // This is obligatory.
20067 ExprResult Result = E;
20068 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
20069 return Result;
20070
20071 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20072 // leaves Result unchanged on failure.
20073 Result = E;
20074 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
20075 return Result;
20076
20077 // If that failed, try to recover with a call.
20078 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20079 /*complain*/ true);
20080 return Result;
20081 }
20082
20083 // Bound member functions.
20084 case BuiltinType::BoundMember: {
20085 ExprResult result = E;
20086 const Expr *BME = E->IgnoreParens();
20087 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20088 // Try to give a nicer diagnostic if it is a bound member that we recognize.
20089 if (isa<CXXPseudoDestructorExpr>(BME)) {
20090 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20091 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20092 if (ME->getMemberNameInfo().getName().getNameKind() ==
20093 DeclarationName::CXXDestructorName)
20094 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20095 }
20096 tryToRecoverWithCall(result, PD,
20097 /*complain*/ true);
20098 return result;
20099 }
20100
20101 // ARC unbridged casts.
20102 case BuiltinType::ARCUnbridgedCast: {
20103 Expr *realCast = stripARCUnbridgedCast(E);
20104 diagnoseARCUnbridgedCast(realCast);
20105 return realCast;
20106 }
20107
20108 // Expressions of unknown type.
20109 case BuiltinType::UnknownAny:
20110 return diagnoseUnknownAnyExpr(*this, E);
20111
20112 // Pseudo-objects.
20113 case BuiltinType::PseudoObject:
20114 return checkPseudoObjectRValue(E);
20115
20116 case BuiltinType::BuiltinFn: {
20117 // Accept __noop without parens by implicitly converting it to a call expr.
20118 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20119 if (DRE) {
20120 auto *FD = cast<FunctionDecl>(DRE->getDecl());
20121 if (FD->getBuiltinID() == Builtin::BI__noop) {
20122 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20123 CK_BuiltinFnToFnPtr)
20124 .get();
20125 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20126 VK_PRValue, SourceLocation(),
20127 FPOptionsOverride());
20128 }
20129 }
20130
20131 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20132 return ExprError();
20133 }
20134
20135 case BuiltinType::IncompleteMatrixIdx:
20136 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20137 ->getRowIdx()
20138 ->getBeginLoc(),
20139 diag::err_matrix_incomplete_index);
20140 return ExprError();
20141
20142 // Expressions of unknown type.
20143 case BuiltinType::OMPArraySection:
20144 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
20145 return ExprError();
20146
20147 // Expressions of unknown type.
20148 case BuiltinType::OMPArrayShaping:
20149 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20150
20151 case BuiltinType::OMPIterator:
20152 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20153
20154 // Everything else should be impossible.
20155#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20156 case BuiltinType::Id:
20157#include "clang/Basic/OpenCLImageTypes.def"
20158#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20159 case BuiltinType::Id:
20160#include "clang/Basic/OpenCLExtensionTypes.def"
20161#define SVE_TYPE(Name, Id, SingletonId) \
20162 case BuiltinType::Id:
20163#include "clang/Basic/AArch64SVEACLETypes.def"
20164#define PPC_VECTOR_TYPE(Name, Id, Size) \
20165 case BuiltinType::Id:
20166#include "clang/Basic/PPCTypes.def"
20167#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20168#include "clang/Basic/RISCVVTypes.def"
20169#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20170#define PLACEHOLDER_TYPE(Id, SingletonId)
20171#include "clang/AST/BuiltinTypes.def"
20172 break;
20173 }
20174
20175 llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!"
, "clang/lib/Sema/SemaExpr.cpp", 20175)
;
20176}
20177
20178bool Sema::CheckCaseExpression(Expr *E) {
20179 if (E->isTypeDependent())
20180 return true;
20181 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
20182 return E->getType()->isIntegralOrEnumerationType();
20183 return false;
20184}
20185
20186/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
20187ExprResult
20188Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
20189 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", 20190, __extension__ __PRETTY_FUNCTION__
))
20190 "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", 20190, __extension__ __PRETTY_FUNCTION__
))
;
20191 QualType BoolT = Context.ObjCBuiltinBoolTy;
20192 if (!Context.getBOOLDecl()) {
20193 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
20194 Sema::LookupOrdinaryName);
20195 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
20196 NamedDecl *ND = Result.getFoundDecl();
20197 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
20198 Context.setBOOLDecl(TD);
20199 }
20200 }
20201 if (Context.getBOOLDecl())
20202 BoolT = Context.getBOOLType();
20203 return new (Context)
20204 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
20205}
20206
20207ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
20208 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
20209 SourceLocation RParen) {
20210 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
20211 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20212 return Spec.getPlatform() == Platform;
20213 });
20214 // Transcribe the "ios" availability check to "maccatalyst" when compiling
20215 // for "maccatalyst" if "maccatalyst" is not specified.
20216 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
20217 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20218 return Spec.getPlatform() == "ios";
20219 });
20220 }
20221 if (Spec == AvailSpecs.end())
20222 return None;
20223 return Spec->getVersion();
20224 };
20225
20226 VersionTuple Version;
20227 if (auto MaybeVersion =
20228 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
20229 Version = *MaybeVersion;
20230
20231 // The use of `@available` in the enclosing context should be analyzed to
20232 // warn when it's used inappropriately (i.e. not if(@available)).
20233 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
20234 Context->HasPotentialAvailabilityViolations = true;
20235
20236 return new (Context)
20237 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
20238}
20239
20240ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
20241 ArrayRef<Expr *> SubExprs, QualType T) {
20242 if (!Context.getLangOpts().RecoveryAST)
20243 return ExprError();
20244
20245 if (isSFINAEContext())
20246 return ExprError();
20247
20248 if (T.isNull() || T->isUndeducedType() ||
20249 !Context.getLangOpts().RecoveryASTType)
20250 // We don't know the concrete type, fallback to dependent type.
20251 T = Context.DependentTy;
20252
20253 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20254}

/build/llvm-toolchain-snapshot-15~++20220320100729+487629cc61b5/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/DependenceFlags.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/TemplateName.h"
23#include "clang/Basic/AddressSpaces.h"
24#include "clang/Basic/AttrKinds.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/ExceptionSpecificationType.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/Visibility.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/None.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/PointerLikeTypeTraits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include "llvm/Support/type_traits.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <string>
55#include <type_traits>
56#include <utility>
57
58namespace clang {
59
60class BTFTypeTagAttr;
61class ExtQuals;
62class QualType;
63class ConceptDecl;
64class TagDecl;
65class TemplateParameterList;
66class Type;
67
68enum {
69 TypeAlignmentInBits = 4,
70 TypeAlignment = 1 << TypeAlignmentInBits
71};
72
73namespace serialization {
74 template <class T> class AbstractTypeReader;
75 template <class T> class AbstractTypeWriter;
76}
77
78} // namespace clang
79
80namespace llvm {
81
82 template <typename T>
83 struct PointerLikeTypeTraits;
84 template<>
85 struct PointerLikeTypeTraits< ::clang::Type*> {
86 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
87
88 static inline ::clang::Type *getFromVoidPointer(void *P) {
89 return static_cast< ::clang::Type*>(P);
90 }
91
92 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
93 };
94
95 template<>
96 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
97 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
98
99 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
100 return static_cast< ::clang::ExtQuals*>(P);
101 }
102
103 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
104 };
105
106} // namespace llvm
107
108namespace clang {
109
110class ASTContext;
111template <typename> class CanQual;
112class CXXRecordDecl;
113class DeclContext;
114class EnumDecl;
115class Expr;
116class ExtQualsTypeCommonBase;
117class FunctionDecl;
118class IdentifierInfo;
119class NamedDecl;
120class ObjCInterfaceDecl;
121class ObjCProtocolDecl;
122class ObjCTypeParamDecl;
123struct PrintingPolicy;
124class RecordDecl;
125class Stmt;
126class TagDecl;
127class TemplateArgument;
128class TemplateArgumentListInfo;
129class TemplateArgumentLoc;
130class TemplateTypeParmDecl;
131class TypedefNameDecl;
132class UnresolvedUsingTypenameDecl;
133class UsingShadowDecl;
134
135using CanQualType = CanQual<Type>;
136
137// Provide forward declarations for all of the *Type classes.
138#define TYPE(Class, Base) class Class##Type;
139#include "clang/AST/TypeNodes.inc"
140
141/// The collection of all-type qualifiers we support.
142/// Clang supports five independent qualifiers:
143/// * C99: const, volatile, and restrict
144/// * MS: __unaligned
145/// * Embedded C (TR18037): address spaces
146/// * Objective C: the GC attributes (none, weak, or strong)
147class Qualifiers {
148public:
149 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
150 Const = 0x1,
151 Restrict = 0x2,
152 Volatile = 0x4,
153 CVRMask = Const | Volatile | Restrict
154 };
155
156 enum GC {
157 GCNone = 0,
158 Weak,
159 Strong
160 };
161
162 enum ObjCLifetime {
163 /// There is no lifetime qualification on this type.
164 OCL_None,
165
166 /// This object can be modified without requiring retains or
167 /// releases.
168 OCL_ExplicitNone,
169
170 /// Assigning into this object requires the old value to be
171 /// released and the new value to be retained. The timing of the
172 /// release of the old value is inexact: it may be moved to
173 /// immediately after the last known point where the value is
174 /// live.
175 OCL_Strong,
176
177 /// Reading or writing from this object requires a barrier call.
178 OCL_Weak,
179
180 /// Assigning into this object requires a lifetime extension.
181 OCL_Autoreleasing
182 };
183
184 enum {
185 /// The maximum supported address space number.
186 /// 23 bits should be enough for anyone.
187 MaxAddressSpace = 0x7fffffu,
188
189 /// The width of the "fast" qualifier mask.
190 FastWidth = 3,
191
192 /// The fast qualifier mask.
193 FastMask = (1 << FastWidth) - 1
194 };
195
196 /// Returns the common set of qualifiers while removing them from
197 /// the given sets.
198 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
199 // If both are only CVR-qualified, bit operations are sufficient.
200 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
201 Qualifiers Q;
202 Q.Mask = L.Mask & R.Mask;
203 L.Mask &= ~Q.Mask;
204 R.Mask &= ~Q.Mask;
205 return Q;
206 }
207
208 Qualifiers Q;
209 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
210 Q.addCVRQualifiers(CommonCRV);
211 L.removeCVRQualifiers(CommonCRV);
212 R.removeCVRQualifiers(CommonCRV);
213
214 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
215 Q.setObjCGCAttr(L.getObjCGCAttr());
216 L.removeObjCGCAttr();
217 R.removeObjCGCAttr();
218 }
219
220 if (L.getObjCLifetime() == R.getObjCLifetime()) {
221 Q.setObjCLifetime(L.getObjCLifetime());
222 L.removeObjCLifetime();
223 R.removeObjCLifetime();
224 }
225
226 if (L.getAddressSpace() == R.getAddressSpace()) {
227 Q.setAddressSpace(L.getAddressSpace());
228 L.removeAddressSpace();
229 R.removeAddressSpace();
230 }
231 return Q;
232 }
233
234 static Qualifiers fromFastMask(unsigned Mask) {
235 Qualifiers Qs;
236 Qs.addFastQualifiers(Mask);
237 return Qs;
238 }
239
240 static Qualifiers fromCVRMask(unsigned CVR) {
241 Qualifiers Qs;
242 Qs.addCVRQualifiers(CVR);
243 return Qs;
244 }
245
246 static Qualifiers fromCVRUMask(unsigned CVRU) {
247 Qualifiers Qs;
248 Qs.addCVRUQualifiers(CVRU);
249 return Qs;
250 }
251
252 // Deserialize qualifiers from an opaque representation.
253 static Qualifiers fromOpaqueValue(unsigned opaque) {
254 Qualifiers Qs;
255 Qs.Mask = opaque;
256 return Qs;
257 }
258
259 // Serialize these qualifiers into an opaque representation.
260 unsigned getAsOpaqueValue() const {
261 return Mask;
262 }
263
264 bool hasConst() const { return Mask & Const; }
265 bool hasOnlyConst() const { return Mask == Const; }
266 void removeConst() { Mask &= ~Const; }
267 void addConst() { Mask |= Const; }
268
269 bool hasVolatile() const { return Mask & Volatile; }
270 bool hasOnlyVolatile() const { return Mask == Volatile; }
271 void removeVolatile() { Mask &= ~Volatile; }
272 void addVolatile() { Mask |= Volatile; }
273
274 bool hasRestrict() const { return Mask & Restrict; }
275 bool hasOnlyRestrict() const { return Mask == Restrict; }
276 void removeRestrict() { Mask &= ~Restrict; }
277 void addRestrict() { Mask |= Restrict; }
278
279 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
280 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
281 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
282
283 void setCVRQualifiers(unsigned mask) {
284 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "clang/include/clang/AST/Type.h", 284, __extension__ __PRETTY_FUNCTION__
))
;
285 Mask = (Mask & ~CVRMask) | mask;
286 }
287 void removeCVRQualifiers(unsigned mask) {
288 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "clang/include/clang/AST/Type.h", 288, __extension__ __PRETTY_FUNCTION__
))
;
289 Mask &= ~mask;
290 }
291 void removeCVRQualifiers() {
292 removeCVRQualifiers(CVRMask);
293 }
294 void addCVRQualifiers(unsigned mask) {
295 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "clang/include/clang/AST/Type.h", 295, __extension__ __PRETTY_FUNCTION__
))
;
296 Mask |= mask;
297 }
298 void addCVRUQualifiers(unsigned mask) {
299 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")(static_cast <bool> (!(mask & ~CVRMask & ~UMask
) && "bitmask contains non-CVRU bits") ? void (0) : __assert_fail
("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "clang/include/clang/AST/Type.h", 299, __extension__ __PRETTY_FUNCTION__
))
;
300 Mask |= mask;
301 }
302
303 bool hasUnaligned() const { return Mask & UMask; }
304 void setUnaligned(bool flag) {
305 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
306 }
307 void removeUnaligned() { Mask &= ~UMask; }
308 void addUnaligned() { Mask |= UMask; }
309
310 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
311 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
312 void setObjCGCAttr(GC type) {
313 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
314 }
315 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
316 void addObjCGCAttr(GC type) {
317 assert(type)(static_cast <bool> (type) ? void (0) : __assert_fail (
"type", "clang/include/clang/AST/Type.h", 317, __extension__ __PRETTY_FUNCTION__
))
;
318 setObjCGCAttr(type);
319 }
320 Qualifiers withoutObjCGCAttr() const {
321 Qualifiers qs = *this;
322 qs.removeObjCGCAttr();
323 return qs;
324 }
325 Qualifiers withoutObjCLifetime() const {
326 Qualifiers qs = *this;
327 qs.removeObjCLifetime();
328 return qs;
329 }
330 Qualifiers withoutAddressSpace() const {
331 Qualifiers qs = *this;
332 qs.removeAddressSpace();
333 return qs;
334 }
335
336 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
337 ObjCLifetime getObjCLifetime() const {
338 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
339 }
340 void setObjCLifetime(ObjCLifetime type) {
341 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
342 }
343 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
344 void addObjCLifetime(ObjCLifetime type) {
345 assert(type)(static_cast <bool> (type) ? void (0) : __assert_fail (
"type", "clang/include/clang/AST/Type.h", 345, __extension__ __PRETTY_FUNCTION__
))
;
346 assert(!hasObjCLifetime())(static_cast <bool> (!hasObjCLifetime()) ? void (0) : __assert_fail
("!hasObjCLifetime()", "clang/include/clang/AST/Type.h", 346
, __extension__ __PRETTY_FUNCTION__))
;
347 Mask |= (type << LifetimeShift);
348 }
349
350 /// True if the lifetime is neither None or ExplicitNone.
351 bool hasNonTrivialObjCLifetime() const {
352 ObjCLifetime lifetime = getObjCLifetime();
353 return (lifetime > OCL_ExplicitNone);
354 }
355
356 /// True if the lifetime is either strong or weak.
357 bool hasStrongOrWeakObjCLifetime() const {
358 ObjCLifetime lifetime = getObjCLifetime();
359 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
360 }
361
362 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
363 LangAS getAddressSpace() const {
364 return static_cast<LangAS>(Mask >> AddressSpaceShift);
365 }
366 bool hasTargetSpecificAddressSpace() const {
367 return isTargetAddressSpace(getAddressSpace());
368 }
369 /// Get the address space attribute value to be printed by diagnostics.
370 unsigned getAddressSpaceAttributePrintValue() const {
371 auto Addr = getAddressSpace();
372 // This function is not supposed to be used with language specific
373 // address spaces. If that happens, the diagnostic message should consider
374 // printing the QualType instead of the address space value.
375 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())(static_cast <bool> (Addr == LangAS::Default || hasTargetSpecificAddressSpace
()) ? void (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "clang/include/clang/AST/Type.h", 375, __extension__ __PRETTY_FUNCTION__
))
;
376 if (Addr != LangAS::Default)
377 return toTargetAddressSpace(Addr);
378 // TODO: The diagnostic messages where Addr may be 0 should be fixed
379 // since it cannot differentiate the situation where 0 denotes the default
380 // address space or user specified __attribute__((address_space(0))).
381 return 0;
382 }
383 void setAddressSpace(LangAS space) {
384 assert((unsigned)space <= MaxAddressSpace)(static_cast <bool> ((unsigned)space <= MaxAddressSpace
) ? void (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "clang/include/clang/AST/Type.h", 384, __extension__ __PRETTY_FUNCTION__
))
;
385 Mask = (Mask & ~AddressSpaceMask)
386 | (((uint32_t) space) << AddressSpaceShift);
387 }
388 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
389 void addAddressSpace(LangAS space) {
390 assert(space != LangAS::Default)(static_cast <bool> (space != LangAS::Default) ? void (
0) : __assert_fail ("space != LangAS::Default", "clang/include/clang/AST/Type.h"
, 390, __extension__ __PRETTY_FUNCTION__))
;
391 setAddressSpace(space);
392 }
393
394 // Fast qualifiers are those that can be allocated directly
395 // on a QualType object.
396 bool hasFastQualifiers() const { return getFastQualifiers(); }
397 unsigned getFastQualifiers() const { return Mask & FastMask; }
398 void setFastQualifiers(unsigned mask) {
399 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) &&
"bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail
("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "clang/include/clang/AST/Type.h", 399, __extension__ __PRETTY_FUNCTION__
))
;
400 Mask = (Mask & ~FastMask) | mask;
401 }
402 void removeFastQualifiers(unsigned mask) {
403 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) &&
"bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail
("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "clang/include/clang/AST/Type.h", 403, __extension__ __PRETTY_FUNCTION__
))
;
404 Mask &= ~mask;
405 }
406 void removeFastQualifiers() {
407 removeFastQualifiers(FastMask);
408 }
409 void addFastQualifiers(unsigned mask) {
410 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) &&
"bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail
("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "clang/include/clang/AST/Type.h", 410, __extension__ __PRETTY_FUNCTION__
))
;
411 Mask |= mask;
412 }
413
414 /// Return true if the set contains any qualifiers which require an ExtQuals
415 /// node to be allocated.
416 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
417 Qualifiers getNonFastQualifiers() const {
418 Qualifiers Quals = *this;
419 Quals.setFastQualifiers(0);
420 return Quals;
421 }
422
423 /// Return true if the set contains any qualifiers.
424 bool hasQualifiers() const { return Mask; }
425 bool empty() const { return !Mask; }
426
427 /// Add the qualifiers from the given set to this set.
428 void addQualifiers(Qualifiers Q) {
429 // If the other set doesn't have any non-boolean qualifiers, just
430 // bit-or it in.
431 if (!(Q.Mask & ~CVRMask))
432 Mask |= Q.Mask;
433 else {
434 Mask |= (Q.Mask & CVRMask);
435 if (Q.hasAddressSpace())
436 addAddressSpace(Q.getAddressSpace());
437 if (Q.hasObjCGCAttr())
438 addObjCGCAttr(Q.getObjCGCAttr());
439 if (Q.hasObjCLifetime())
440 addObjCLifetime(Q.getObjCLifetime());
441 }
442 }
443
444 /// Remove the qualifiers from the given set from this set.
445 void removeQualifiers(Qualifiers Q) {
446 // If the other set doesn't have any non-boolean qualifiers, just
447 // bit-and the inverse in.
448 if (!(Q.Mask & ~CVRMask))
449 Mask &= ~Q.Mask;
450 else {
451 Mask &= ~(Q.Mask & CVRMask);
452 if (getObjCGCAttr() == Q.getObjCGCAttr())
453 removeObjCGCAttr();
454 if (getObjCLifetime() == Q.getObjCLifetime())
455 removeObjCLifetime();
456 if (getAddressSpace() == Q.getAddressSpace())
457 removeAddressSpace();
458 }
459 }
460
461 /// Add the qualifiers from the given set to this set, given that
462 /// they don't conflict.
463 void addConsistentQualifiers(Qualifiers qs) {
464 assert(getAddressSpace() == qs.getAddressSpace() ||(static_cast <bool> (getAddressSpace() == qs.getAddressSpace
() || !hasAddressSpace() || !qs.hasAddressSpace()) ? void (0)
: __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "clang/include/clang/AST/Type.h", 465, __extension__ __PRETTY_FUNCTION__
))
465 !hasAddressSpace() || !qs.hasAddressSpace())(static_cast <bool> (getAddressSpace() == qs.getAddressSpace
() || !hasAddressSpace() || !qs.hasAddressSpace()) ? void (0)
: __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "clang/include/clang/AST/Type.h", 465, __extension__ __PRETTY_FUNCTION__
))
;
466 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||(static_cast <bool> (getObjCGCAttr() == qs.getObjCGCAttr
() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? void (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "clang/include/clang/AST/Type.h", 467, __extension__ __PRETTY_FUNCTION__
))
467 !hasObjCGCAttr() || !qs.hasObjCGCAttr())(static_cast <bool> (getObjCGCAttr() == qs.getObjCGCAttr
() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? void (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "clang/include/clang/AST/Type.h", 467, __extension__ __PRETTY_FUNCTION__
))
;
468 assert(getObjCLifetime() == qs.getObjCLifetime() ||(static_cast <bool> (getObjCLifetime() == qs.getObjCLifetime
() || !hasObjCLifetime() || !qs.hasObjCLifetime()) ? void (0)
: __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "clang/include/clang/AST/Type.h", 469, __extension__ __PRETTY_FUNCTION__
))
469 !hasObjCLifetime() || !qs.hasObjCLifetime())(static_cast <bool> (getObjCLifetime() == qs.getObjCLifetime
() || !hasObjCLifetime() || !qs.hasObjCLifetime()) ? void (0)
: __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "clang/include/clang/AST/Type.h", 469, __extension__ __PRETTY_FUNCTION__
))
;
470 Mask |= qs.Mask;
471 }
472
473 /// Returns true if address space A is equal to or a superset of B.
474 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
475 /// overlapping address spaces.
476 /// CL1.1 or CL1.2:
477 /// every address space is a superset of itself.
478 /// CL2.0 adds:
479 /// __generic is a superset of any address space except for __constant.
480 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
481 // Address spaces must match exactly.
482 return A == B ||
483 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
484 // for __constant can be used as __generic.
485 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
486 // We also define global_device and global_host address spaces,
487 // to distinguish global pointers allocated on host from pointers
488 // allocated on device, which are a subset of __global.
489 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
490 B == LangAS::opencl_global_host)) ||
491 (A == LangAS::sycl_global && (B == LangAS::sycl_global_device ||
492 B == LangAS::sycl_global_host)) ||
493 // Consider pointer size address spaces to be equivalent to default.
494 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
495 (isPtrSizeAddressSpace(B) || B == LangAS::Default)) ||
496 // Default is a superset of SYCL address spaces.
497 (A == LangAS::Default &&
498 (B == LangAS::sycl_private || B == LangAS::sycl_local ||
499 B == LangAS::sycl_global || B == LangAS::sycl_global_device ||
500 B == LangAS::sycl_global_host)) ||
501 // In HIP device compilation, any cuda address space is allowed
502 // to implicitly cast into the default address space.
503 (A == LangAS::Default &&
504 (B == LangAS::cuda_constant || B == LangAS::cuda_device ||
505 B == LangAS::cuda_shared));
506 }
507
508 /// Returns true if the address space in these qualifiers is equal to or
509 /// a superset of the address space in the argument qualifiers.
510 bool isAddressSpaceSupersetOf(Qualifiers other) const {
511 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
512 }
513
514 /// Determines if these qualifiers compatibly include another set.
515 /// Generally this answers the question of whether an object with the other
516 /// qualifiers can be safely used as an object with these qualifiers.
517 bool compatiblyIncludes(Qualifiers other) const {
518 return isAddressSpaceSupersetOf(other) &&
519 // ObjC GC qualifiers can match, be added, or be removed, but can't
520 // be changed.
521 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
522 !other.hasObjCGCAttr()) &&
523 // ObjC lifetime qualifiers must match exactly.
524 getObjCLifetime() == other.getObjCLifetime() &&
525 // CVR qualifiers may subset.
526 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
527 // U qualifier may superset.
528 (!other.hasUnaligned() || hasUnaligned());
529 }
530
531 /// Determines if these qualifiers compatibly include another set of
532 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
533 ///
534 /// One set of Objective-C lifetime qualifiers compatibly includes the other
535 /// if the lifetime qualifiers match, or if both are non-__weak and the
536 /// including set also contains the 'const' qualifier, or both are non-__weak
537 /// and one is None (which can only happen in non-ARC modes).
538 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
539 if (getObjCLifetime() == other.getObjCLifetime())
540 return true;
541
542 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
543 return false;
544
545 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
546 return true;
547
548 return hasConst();
549 }
550
551 /// Determine whether this set of qualifiers is a strict superset of
552 /// another set of qualifiers, not considering qualifier compatibility.
553 bool isStrictSupersetOf(Qualifiers Other) const;
554
555 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
556 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
557
558 explicit operator bool() const { return hasQualifiers(); }
559
560 Qualifiers &operator+=(Qualifiers R) {
561 addQualifiers(R);
562 return *this;
563 }
564
565 // Union two qualifier sets. If an enumerated qualifier appears
566 // in both sets, use the one from the right.
567 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
568 L += R;
569 return L;
570 }
571
572 Qualifiers &operator-=(Qualifiers R) {
573 removeQualifiers(R);
574 return *this;
575 }
576
577 /// Compute the difference between two qualifier sets.
578 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
579 L -= R;
580 return L;
581 }
582
583 std::string getAsString() const;
584 std::string getAsString(const PrintingPolicy &Policy) const;
585
586 static std::string getAddrSpaceAsString(LangAS AS);
587
588 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
589 void print(raw_ostream &OS, const PrintingPolicy &Policy,
590 bool appendSpaceIfNonEmpty = false) const;
591
592 void Profile(llvm::FoldingSetNodeID &ID) const {
593 ID.AddInteger(Mask);
594 }
595
596private:
597 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
598 // |C R V|U|GCAttr|Lifetime|AddressSpace|
599 uint32_t Mask = 0;
600
601 static const uint32_t UMask = 0x8;
602 static const uint32_t UShift = 3;
603 static const uint32_t GCAttrMask = 0x30;
604 static const uint32_t GCAttrShift = 4;
605 static const uint32_t LifetimeMask = 0x1C0;
606 static const uint32_t LifetimeShift = 6;
607 static const uint32_t AddressSpaceMask =
608 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
609 static const uint32_t AddressSpaceShift = 9;
610};
611
612/// A std::pair-like structure for storing a qualified type split
613/// into its local qualifiers and its locally-unqualified type.
614struct SplitQualType {
615 /// The locally-unqualified type.
616 const Type *Ty = nullptr;
617
618 /// The local qualifiers.
619 Qualifiers Quals;
620
621 SplitQualType() = default;
622 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
623
624 SplitQualType getSingleStepDesugaredType() const; // end of this file
625
626 // Make std::tie work.
627 std::pair<const Type *,Qualifiers> asPair() const {
628 return std::pair<const Type *, Qualifiers>(Ty, Quals);
629 }
630
631 friend bool operator==(SplitQualType a, SplitQualType b) {
632 return a.Ty == b.Ty && a.Quals == b.Quals;
633 }
634 friend bool operator!=(SplitQualType a, SplitQualType b) {
635 return a.Ty != b.Ty || a.Quals != b.Quals;
636 }
637};
638
639/// The kind of type we are substituting Objective-C type arguments into.
640///
641/// The kind of substitution affects the replacement of type parameters when
642/// no concrete type information is provided, e.g., when dealing with an
643/// unspecialized type.
644enum class ObjCSubstitutionContext {
645 /// An ordinary type.
646 Ordinary,
647
648 /// The result type of a method or function.
649 Result,
650
651 /// The parameter type of a method or function.
652 Parameter,
653
654 /// The type of a property.
655 Property,
656
657 /// The superclass of a type.
658 Superclass,
659};
660
661/// A (possibly-)qualified type.
662///
663/// For efficiency, we don't store CV-qualified types as nodes on their
664/// own: instead each reference to a type stores the qualifiers. This
665/// greatly reduces the number of nodes we need to allocate for types (for
666/// example we only need one for 'int', 'const int', 'volatile int',
667/// 'const volatile int', etc).
668///
669/// As an added efficiency bonus, instead of making this a pair, we
670/// just store the two bits we care about in the low bits of the
671/// pointer. To handle the packing/unpacking, we make QualType be a
672/// simple wrapper class that acts like a smart pointer. A third bit
673/// indicates whether there are extended qualifiers present, in which
674/// case the pointer points to a special structure.
675class QualType {
676 friend class QualifierCollector;
677
678 // Thankfully, these are efficiently composable.
679 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
680 Qualifiers::FastWidth> Value;
681
682 const ExtQuals *getExtQualsUnsafe() const {
683 return Value.getPointer().get<const ExtQuals*>();
684 }
685
686 const Type *getTypePtrUnsafe() const {
687 return Value.getPointer().get<const Type*>();
688 }
689
690 const ExtQualsTypeCommonBase *getCommonPtr() const {
691 assert(!isNull() && "Cannot retrieve a NULL type pointer")(static_cast <bool> (!isNull() && "Cannot retrieve a NULL type pointer"
) ? void (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "clang/include/clang/AST/Type.h", 691, __extension__ __PRETTY_FUNCTION__
))
;
692 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
693 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
694 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
695 }
696
697public:
698 QualType() = default;
699 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
700 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
701
702 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
703 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
704
705 /// Retrieves a pointer to the underlying (unqualified) type.
706 ///
707 /// This function requires that the type not be NULL. If the type might be
708 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
709 const Type *getTypePtr() const;
710
711 const Type *getTypePtrOrNull() const;
712
713 /// Retrieves a pointer to the name of the base type.
714 const IdentifierInfo *getBaseTypeIdentifier() const;
715
716 /// Divides a QualType into its unqualified type and a set of local
717 /// qualifiers.
718 SplitQualType split() const;
719
720 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
721
722 static QualType getFromOpaquePtr(const void *Ptr) {
723 QualType T;
724 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
725 return T;
726 }
727
728 const Type &operator*() const {
729 return *getTypePtr();
730 }
731
732 const Type *operator->() const {
733 return getTypePtr();
734 }
735
736 bool isCanonical() const;
737 bool isCanonicalAsParam() const;
738
739 /// Return true if this QualType doesn't point to a type yet.
740 bool isNull() const {
741 return Value.getPointer().isNull();
742 }
743
744 /// Determine whether this particular QualType instance has the
745 /// "const" qualifier set, without looking through typedefs that may have
746 /// added "const" at a different level.
747 bool isLocalConstQualified() const {
748 return (getLocalFastQualifiers() & Qualifiers::Const);
749 }
750
751 /// Determine whether this type is const-qualified.
752 bool isConstQualified() const;
753
754 /// Determine whether this particular QualType instance has the
755 /// "restrict" qualifier set, without looking through typedefs that may have
756 /// added "restrict" at a different level.
757 bool isLocalRestrictQualified() const {
758 return (getLocalFastQualifiers() & Qualifiers::Restrict);
759 }
760
761 /// Determine whether this type is restrict-qualified.
762 bool isRestrictQualified() const;
763
764 /// Determine whether this particular QualType instance has the
765 /// "volatile" qualifier set, without looking through typedefs that may have
766 /// added "volatile" at a different level.
767 bool isLocalVolatileQualified() const {
768 return (getLocalFastQualifiers() & Qualifiers::Volatile);
769 }
770
771 /// Determine whether this type is volatile-qualified.
772 bool isVolatileQualified() const;
773
774 /// Determine whether this particular QualType instance has any
775 /// qualifiers, without looking through any typedefs that might add
776 /// qualifiers at a different level.
777 bool hasLocalQualifiers() const {
778 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
779 }
780
781 /// Determine whether this type has any qualifiers.
782 bool hasQualifiers() const;
783
784 /// Determine whether this particular QualType instance has any
785 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
786 /// instance.
787 bool hasLocalNonFastQualifiers() const {
788 return Value.getPointer().is<const ExtQuals*>();
789 }
790
791 /// Retrieve the set of qualifiers local to this particular QualType
792 /// instance, not including any qualifiers acquired through typedefs or
793 /// other sugar.
794 Qualifiers getLocalQualifiers() const;
795
796 /// Retrieve the set of qualifiers applied to this type.
797 Qualifiers getQualifiers() const;
798
799 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
800 /// local to this particular QualType instance, not including any qualifiers
801 /// acquired through typedefs or other sugar.
802 unsigned getLocalCVRQualifiers() const {
803 return getLocalFastQualifiers();
804 }
805
806 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
807 /// applied to this type.
808 unsigned getCVRQualifiers() const;
809
810 bool isConstant(const ASTContext& Ctx) const {
811 return QualType::isConstant(*this, Ctx);
812 }
813
814 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
815 bool isPODType(const ASTContext &Context) const;
816
817 /// Return true if this is a POD type according to the rules of the C++98
818 /// standard, regardless of the current compilation's language.
819 bool isCXX98PODType(const ASTContext &Context) const;
820
821 /// Return true if this is a POD type according to the more relaxed rules
822 /// of the C++11 standard, regardless of the current compilation's language.
823 /// (C++0x [basic.types]p9). Note that, unlike
824 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
825 bool isCXX11PODType(const ASTContext &Context) const;
826
827 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
828 bool isTrivialType(const ASTContext &Context) const;
829
830 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
831 bool isTriviallyCopyableType(const ASTContext &Context) const;
832
833 /// Return true if this is a trivially relocatable type.
834 bool isTriviallyRelocatableType(const ASTContext &Context) const;
835
836 /// Returns true if it is a class and it might be dynamic.
837 bool mayBeDynamicClass() const;
838
839 /// Returns true if it is not a class or if the class might not be dynamic.
840 bool mayBeNotDynamicClass() const;
841
842 // Don't promise in the API that anything besides 'const' can be
843 // easily added.
844
845 /// Add the `const` type qualifier to this QualType.
846 void addConst() {
847 addFastQualifiers(Qualifiers::Const);
848 }
849 QualType withConst() const {
850 return withFastQualifiers(Qualifiers::Const);
851 }
852
853 /// Add the `volatile` type qualifier to this QualType.
854 void addVolatile() {
855 addFastQualifiers(Qualifiers::Volatile);
856 }
857 QualType withVolatile() const {
858 return withFastQualifiers(Qualifiers::Volatile);
859 }
860
861 /// Add the `restrict` qualifier to this QualType.
862 void addRestrict() {
863 addFastQualifiers(Qualifiers::Restrict);
864 }
865 QualType withRestrict() const {
866 return withFastQualifiers(Qualifiers::Restrict);
867 }
868
869 QualType withCVRQualifiers(unsigned CVR) const {
870 return withFastQualifiers(CVR);
871 }
872
873 void addFastQualifiers(unsigned TQs) {
874 assert(!(TQs & ~Qualifiers::FastMask)(static_cast <bool> (!(TQs & ~Qualifiers::FastMask)
&& "non-fast qualifier bits set in mask!") ? void (0
) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "clang/include/clang/AST/Type.h", 875, __extension__ __PRETTY_FUNCTION__
))
875 && "non-fast qualifier bits set in mask!")(static_cast <bool> (!(TQs & ~Qualifiers::FastMask)
&& "non-fast qualifier bits set in mask!") ? void (0
) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "clang/include/clang/AST/Type.h", 875, __extension__ __PRETTY_FUNCTION__
))
;
876 Value.setInt(Value.getInt() | TQs);
877 }
878
879 void removeLocalConst();
880 void removeLocalVolatile();
881 void removeLocalRestrict();
882 void removeLocalCVRQualifiers(unsigned Mask);
883
884 void removeLocalFastQualifiers() { Value.setInt(0); }
885 void removeLocalFastQualifiers(unsigned Mask) {
886 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")(static_cast <bool> (!(Mask & ~Qualifiers::FastMask
) && "mask has non-fast qualifiers") ? void (0) : __assert_fail
("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "clang/include/clang/AST/Type.h", 886, __extension__ __PRETTY_FUNCTION__
))
;
887 Value.setInt(Value.getInt() & ~Mask);
888 }
889
890 // Creates a type with the given qualifiers in addition to any
891 // qualifiers already on this type.
892 QualType withFastQualifiers(unsigned TQs) const {
893 QualType T = *this;
894 T.addFastQualifiers(TQs);
895 return T;
896 }
897
898 // Creates a type with exactly the given fast qualifiers, removing
899 // any existing fast qualifiers.
900 QualType withExactLocalFastQualifiers(unsigned TQs) const {
901 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
902 }
903
904 // Removes fast qualifiers, but leaves any extended qualifiers in place.
905 QualType withoutLocalFastQualifiers() const {
906 QualType T = *this;
907 T.removeLocalFastQualifiers();
908 return T;
909 }
910
911 QualType getCanonicalType() const;
912
913 /// Return this type with all of the instance-specific qualifiers
914 /// removed, but without removing any qualifiers that may have been applied
915 /// through typedefs.
916 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
917
918 /// Retrieve the unqualified variant of the given type,
919 /// removing as little sugar as possible.
920 ///
921 /// This routine looks through various kinds of sugar to find the
922 /// least-desugared type that is unqualified. For example, given:
923 ///
924 /// \code
925 /// typedef int Integer;
926 /// typedef const Integer CInteger;
927 /// typedef CInteger DifferenceType;
928 /// \endcode
929 ///
930 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
931 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
932 ///
933 /// The resulting type might still be qualified if it's sugar for an array
934 /// type. To strip qualifiers even from within a sugared array type, use
935 /// ASTContext::getUnqualifiedArrayType.
936 inline QualType getUnqualifiedType() const;
937
938 /// Retrieve the unqualified variant of the given type, removing as little
939 /// sugar as possible.
940 ///
941 /// Like getUnqualifiedType(), but also returns the set of
942 /// qualifiers that were built up.
943 ///
944 /// The resulting type might still be qualified if it's sugar for an array
945 /// type. To strip qualifiers even from within a sugared array type, use
946 /// ASTContext::getUnqualifiedArrayType.
947 inline SplitQualType getSplitUnqualifiedType() const;
948
949 /// Determine whether this type is more qualified than the other
950 /// given type, requiring exact equality for non-CVR qualifiers.
951 bool isMoreQualifiedThan(QualType Other) const;
952
953 /// Determine whether this type is at least as qualified as the other
954 /// given type, requiring exact equality for non-CVR qualifiers.
955 bool isAtLeastAsQualifiedAs(QualType Other) const;
956
957 QualType getNonReferenceType() const;
958
959 /// Determine the type of a (typically non-lvalue) expression with the
960 /// specified result type.
961 ///
962 /// This routine should be used for expressions for which the return type is
963 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
964 /// an lvalue. It removes a top-level reference (since there are no
965 /// expressions of reference type) and deletes top-level cvr-qualifiers
966 /// from non-class types (in C++) or all types (in C).
967 QualType getNonLValueExprType(const ASTContext &Context) const;
968
969 /// Remove an outer pack expansion type (if any) from this type. Used as part
970 /// of converting the type of a declaration to the type of an expression that
971 /// references that expression. It's meaningless for an expression to have a
972 /// pack expansion type.
973 QualType getNonPackExpansionType() const;
974
975 /// Return the specified type with any "sugar" removed from
976 /// the type. This takes off typedefs, typeof's etc. If the outer level of
977 /// the type is already concrete, it returns it unmodified. This is similar
978 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
979 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
980 /// concrete.
981 ///
982 /// Qualifiers are left in place.
983 QualType getDesugaredType(const ASTContext &Context) const {
984 return getDesugaredType(*this, Context);
985 }
986
987 SplitQualType getSplitDesugaredType() const {
988 return getSplitDesugaredType(*this);
989 }
990
991 /// Return the specified type with one level of "sugar" removed from
992 /// the type.
993 ///
994 /// This routine takes off the first typedef, typeof, etc. If the outer level
995 /// of the type is already concrete, it returns it unmodified.
996 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
997 return getSingleStepDesugaredTypeImpl(*this, Context);
998 }
999
1000 /// Returns the specified type after dropping any
1001 /// outer-level parentheses.
1002 QualType IgnoreParens() const {
1003 if (isa<ParenType>(*this))
1004 return QualType::IgnoreParens(*this);
1005 return *this;
1006 }
1007
1008 /// Indicate whether the specified types and qualifiers are identical.
1009 friend bool operator==(const QualType &LHS, const QualType &RHS) {
1010 return LHS.Value == RHS.Value;
2
Calling 'PointerIntPair::operator=='
5
Returning from 'PointerIntPair::operator=='
6
Returning zero, which participates in a condition later
1011 }
1012 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
1013 return LHS.Value != RHS.Value;
1014 }
1015 friend bool operator<(const QualType &LHS, const QualType &RHS) {
1016 return LHS.Value < RHS.Value;
1017 }
1018
1019 static std::string getAsString(SplitQualType split,
1020 const PrintingPolicy &Policy) {
1021 return getAsString(split.Ty, split.Quals, Policy);
1022 }
1023 static std::string getAsString(const Type *ty, Qualifiers qs,
1024 const PrintingPolicy &Policy);
1025
1026 std::string getAsString() const;
1027 std::string getAsString(const PrintingPolicy &Policy) const;
1028
1029 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1030 const Twine &PlaceHolder = Twine(),
1031 unsigned Indentation = 0) const;
1032
1033 static void print(SplitQualType split, raw_ostream &OS,
1034 const PrintingPolicy &policy, const Twine &PlaceHolder,
1035 unsigned Indentation = 0) {
1036 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1037 }
1038
1039 static void print(const Type *ty, Qualifiers qs,
1040 raw_ostream &OS, const PrintingPolicy &policy,
1041 const Twine &PlaceHolder,
1042 unsigned Indentation = 0);
1043
1044 void getAsStringInternal(std::string &Str,
1045 const PrintingPolicy &Policy) const;
1046
1047 static void getAsStringInternal(SplitQualType split, std::string &out,
1048 const PrintingPolicy &policy) {
1049 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1050 }
1051
1052 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1053 std::string &out,
1054 const PrintingPolicy &policy);
1055
1056 class StreamedQualTypeHelper {
1057 const QualType &T;
1058 const PrintingPolicy &Policy;
1059 const Twine &PlaceHolder;
1060 unsigned Indentation;
1061
1062 public:
1063 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1064 const Twine &PlaceHolder, unsigned Indentation)
1065 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1066 Indentation(Indentation) {}
1067
1068 friend raw_ostream &operator<<(raw_ostream &OS,
1069 const StreamedQualTypeHelper &SQT) {
1070 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1071 return OS;
1072 }
1073 };
1074
1075 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1076 const Twine &PlaceHolder = Twine(),
1077 unsigned Indentation = 0) const {
1078 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1079 }
1080
1081 void dump(const char *s) const;
1082 void dump() const;
1083 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1084
1085 void Profile(llvm::FoldingSetNodeID &ID) const {
1086 ID.AddPointer(getAsOpaquePtr());
1087 }
1088
1089 /// Check if this type has any address space qualifier.
1090 inline bool hasAddressSpace() const;
1091
1092 /// Return the address space of this type.
1093 inline LangAS getAddressSpace() const;
1094
1095 /// Returns true if address space qualifiers overlap with T address space
1096 /// qualifiers.
1097 /// OpenCL C defines conversion rules for pointers to different address spaces
1098 /// and notion of overlapping address spaces.
1099 /// CL1.1 or CL1.2:
1100 /// address spaces overlap iff they are they same.
1101 /// OpenCL C v2.0 s6.5.5 adds:
1102 /// __generic overlaps with any address space except for __constant.
1103 bool isAddressSpaceOverlapping(QualType T) const {
1104 Qualifiers Q = getQualifiers();
1105 Qualifiers TQ = T.getQualifiers();
1106 // Address spaces overlap if at least one of them is a superset of another
1107 return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q);
1108 }
1109
1110 /// Returns gc attribute of this type.
1111 inline Qualifiers::GC getObjCGCAttr() const;
1112
1113 /// true when Type is objc's weak.
1114 bool isObjCGCWeak() const {
1115 return getObjCGCAttr() == Qualifiers::Weak;
1116 }
1117
1118 /// true when Type is objc's strong.
1119 bool isObjCGCStrong() const {
1120 return getObjCGCAttr() == Qualifiers::Strong;
1121 }
1122
1123 /// Returns lifetime attribute of this type.
1124 Qualifiers::ObjCLifetime getObjCLifetime() const {
1125 return getQualifiers().getObjCLifetime();
1126 }
1127
1128 bool hasNonTrivialObjCLifetime() const {
1129 return getQualifiers().hasNonTrivialObjCLifetime();
1130 }
1131
1132 bool hasStrongOrWeakObjCLifetime() const {
1133 return getQualifiers().hasStrongOrWeakObjCLifetime();
1134 }
1135
1136 // true when Type is objc's weak and weak is enabled but ARC isn't.
1137 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1138
1139 enum PrimitiveDefaultInitializeKind {
1140 /// The type does not fall into any of the following categories. Note that
1141 /// this case is zero-valued so that values of this enum can be used as a
1142 /// boolean condition for non-triviality.
1143 PDIK_Trivial,
1144
1145 /// The type is an Objective-C retainable pointer type that is qualified
1146 /// with the ARC __strong qualifier.
1147 PDIK_ARCStrong,
1148
1149 /// The type is an Objective-C retainable pointer type that is qualified
1150 /// with the ARC __weak qualifier.
1151 PDIK_ARCWeak,
1152
1153 /// The type is a struct containing a field whose type is not PCK_Trivial.
1154 PDIK_Struct
1155 };
1156
1157 /// Functions to query basic properties of non-trivial C struct types.
1158
1159 /// Check if this is a non-trivial type that would cause a C struct
1160 /// transitively containing this type to be non-trivial to default initialize
1161 /// and return the kind.
1162 PrimitiveDefaultInitializeKind
1163 isNonTrivialToPrimitiveDefaultInitialize() const;
1164
1165 enum PrimitiveCopyKind {
1166 /// The type does not fall into any of the following categories. Note that
1167 /// this case is zero-valued so that values of this enum can be used as a
1168 /// boolean condition for non-triviality.
1169 PCK_Trivial,
1170
1171 /// The type would be trivial except that it is volatile-qualified. Types
1172 /// that fall into one of the other non-trivial cases may additionally be
1173 /// volatile-qualified.
1174 PCK_VolatileTrivial,
1175
1176 /// The type is an Objective-C retainable pointer type that is qualified
1177 /// with the ARC __strong qualifier.
1178 PCK_ARCStrong,
1179
1180 /// The type is an Objective-C retainable pointer type that is qualified
1181 /// with the ARC __weak qualifier.
1182 PCK_ARCWeak,
1183
1184 /// The type is a struct containing a field whose type is neither
1185 /// PCK_Trivial nor PCK_VolatileTrivial.
1186 /// Note that a C++ struct type does not necessarily match this; C++ copying
1187 /// semantics are too complex to express here, in part because they depend
1188 /// on the exact constructor or assignment operator that is chosen by
1189 /// overload resolution to do the copy.
1190 PCK_Struct
1191 };
1192
1193 /// Check if this is a non-trivial type that would cause a C struct
1194 /// transitively containing this type to be non-trivial to copy and return the
1195 /// kind.
1196 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1197
1198 /// Check if this is a non-trivial type that would cause a C struct
1199 /// transitively containing this type to be non-trivial to destructively
1200 /// move and return the kind. Destructive move in this context is a C++-style
1201 /// move in which the source object is placed in a valid but unspecified state
1202 /// after it is moved, as opposed to a truly destructive move in which the
1203 /// source object is placed in an uninitialized state.
1204 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1205
1206 enum DestructionKind {
1207 DK_none,
1208 DK_cxx_destructor,
1209 DK_objc_strong_lifetime,
1210 DK_objc_weak_lifetime,
1211 DK_nontrivial_c_struct
1212 };
1213
1214 /// Returns a nonzero value if objects of this type require
1215 /// non-trivial work to clean up after. Non-zero because it's
1216 /// conceivable that qualifiers (objc_gc(weak)?) could make
1217 /// something require destruction.
1218 DestructionKind isDestructedType() const {
1219 return isDestructedTypeImpl(*this);
1220 }
1221
1222 /// Check if this is or contains a C union that is non-trivial to
1223 /// default-initialize, which is a union that has a member that is non-trivial
1224 /// to default-initialize. If this returns true,
1225 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1226 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1227
1228 /// Check if this is or contains a C union that is non-trivial to destruct,
1229 /// which is a union that has a member that is non-trivial to destruct. If
1230 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1231 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1232
1233 /// Check if this is or contains a C union that is non-trivial to copy, which
1234 /// is a union that has a member that is non-trivial to copy. If this returns
1235 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1236 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1237
1238 /// Determine whether expressions of the given type are forbidden
1239 /// from being lvalues in C.
1240 ///
1241 /// The expression types that are forbidden to be lvalues are:
1242 /// - 'void', but not qualified void
1243 /// - function types
1244 ///
1245 /// The exact rule here is C99 6.3.2.1:
1246 /// An lvalue is an expression with an object type or an incomplete
1247 /// type other than void.
1248 bool isCForbiddenLValueType() const;
1249
1250 /// Substitute type arguments for the Objective-C type parameters used in the
1251 /// subject type.
1252 ///
1253 /// \param ctx ASTContext in which the type exists.
1254 ///
1255 /// \param typeArgs The type arguments that will be substituted for the
1256 /// Objective-C type parameters in the subject type, which are generally
1257 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1258 /// parameters will be replaced with their bounds or id/Class, as appropriate
1259 /// for the context.
1260 ///
1261 /// \param context The context in which the subject type was written.
1262 ///
1263 /// \returns the resulting type.
1264 QualType substObjCTypeArgs(ASTContext &ctx,
1265 ArrayRef<QualType> typeArgs,
1266 ObjCSubstitutionContext context) const;
1267
1268 /// Substitute type arguments from an object type for the Objective-C type
1269 /// parameters used in the subject type.
1270 ///
1271 /// This operation combines the computation of type arguments for
1272 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1273 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1274 /// callers that need to perform a single substitution in isolation.
1275 ///
1276 /// \param objectType The type of the object whose member type we're
1277 /// substituting into. For example, this might be the receiver of a message
1278 /// or the base of a property access.
1279 ///
1280 /// \param dc The declaration context from which the subject type was
1281 /// retrieved, which indicates (for example) which type parameters should
1282 /// be substituted.
1283 ///
1284 /// \param context The context in which the subject type was written.
1285 ///
1286 /// \returns the subject type after replacing all of the Objective-C type
1287 /// parameters with their corresponding arguments.
1288 QualType substObjCMemberType(QualType objectType,
1289 const DeclContext *dc,
1290 ObjCSubstitutionContext context) const;
1291
1292 /// Strip Objective-C "__kindof" types from the given type.
1293 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1294
1295 /// Remove all qualifiers including _Atomic.
1296 QualType getAtomicUnqualifiedType() const;
1297
1298private:
1299 // These methods are implemented in a separate translation unit;
1300 // "static"-ize them to avoid creating temporary QualTypes in the
1301 // caller.
1302 static bool isConstant(QualType T, const ASTContext& Ctx);
1303 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1304 static SplitQualType getSplitDesugaredType(QualType T);
1305 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1306 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1307 const ASTContext &C);
1308 static QualType IgnoreParens(QualType T);
1309 static DestructionKind isDestructedTypeImpl(QualType type);
1310
1311 /// Check if \param RD is or contains a non-trivial C union.
1312 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1313 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1314 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1315};
1316
1317} // namespace clang
1318
1319namespace llvm {
1320
1321/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1322/// to a specific Type class.
1323template<> struct simplify_type< ::clang::QualType> {
1324 using SimpleType = const ::clang::Type *;
1325
1326 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1327 return Val.getTypePtr();
1328 }
1329};
1330
1331// Teach SmallPtrSet that QualType is "basically a pointer".
1332template<>
1333struct PointerLikeTypeTraits<clang::QualType> {
1334 static inline void *getAsVoidPointer(clang::QualType P) {
1335 return P.getAsOpaquePtr();
1336 }
1337
1338 static inline clang::QualType getFromVoidPointer(void *P) {
1339 return clang::QualType::getFromOpaquePtr(P);
1340 }
1341
1342 // Various qualifiers go in low bits.
1343 static constexpr int NumLowBitsAvailable = 0;
1344};
1345
1346} // namespace llvm
1347
1348namespace clang {
1349
1350/// Base class that is common to both the \c ExtQuals and \c Type
1351/// classes, which allows \c QualType to access the common fields between the
1352/// two.
1353class ExtQualsTypeCommonBase {
1354 friend class ExtQuals;
1355 friend class QualType;
1356 friend class Type;
1357
1358 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1359 /// a self-referential pointer (for \c Type).
1360 ///
1361 /// This pointer allows an efficient mapping from a QualType to its
1362 /// underlying type pointer.
1363 const Type *const BaseType;
1364
1365 /// The canonical type of this type. A QualType.
1366 QualType CanonicalType;
1367
1368 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1369 : BaseType(baseType), CanonicalType(canon) {}
1370};
1371
1372/// We can encode up to four bits in the low bits of a
1373/// type pointer, but there are many more type qualifiers that we want
1374/// to be able to apply to an arbitrary type. Therefore we have this
1375/// struct, intended to be heap-allocated and used by QualType to
1376/// store qualifiers.
1377///
1378/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1379/// in three low bits on the QualType pointer; a fourth bit records whether
1380/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1381/// Objective-C GC attributes) are much more rare.
1382class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1383 // NOTE: changing the fast qualifiers should be straightforward as
1384 // long as you don't make 'const' non-fast.
1385 // 1. Qualifiers:
1386 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1387 // Fast qualifiers must occupy the low-order bits.
1388 // b) Update Qualifiers::FastWidth and FastMask.
1389 // 2. QualType:
1390 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1391 // b) Update remove{Volatile,Restrict}, defined near the end of
1392 // this header.
1393 // 3. ASTContext:
1394 // a) Update get{Volatile,Restrict}Type.
1395
1396 /// The immutable set of qualifiers applied by this node. Always contains
1397 /// extended qualifiers.
1398 Qualifiers Quals;
1399
1400 ExtQuals *this_() { return this; }
1401
1402public:
1403 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1404 : ExtQualsTypeCommonBase(baseType,
1405 canon.isNull() ? QualType(this_(), 0) : canon),
1406 Quals(quals) {
1407 assert(Quals.hasNonFastQualifiers()(static_cast <bool> (Quals.hasNonFastQualifiers() &&
"ExtQuals created with no fast qualifiers") ? void (0) : __assert_fail
("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "clang/include/clang/AST/Type.h", 1408, __extension__ __PRETTY_FUNCTION__
))
1408 && "ExtQuals created with no fast qualifiers")(static_cast <bool> (Quals.hasNonFastQualifiers() &&
"ExtQuals created with no fast qualifiers") ? void (0) : __assert_fail
("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "clang/include/clang/AST/Type.h", 1408, __extension__ __PRETTY_FUNCTION__
))
;
1409 assert(!Quals.hasFastQualifiers()(static_cast <bool> (!Quals.hasFastQualifiers() &&
"ExtQuals created with fast qualifiers") ? void (0) : __assert_fail
("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "clang/include/clang/AST/Type.h", 1410, __extension__ __PRETTY_FUNCTION__
))
1410 && "ExtQuals created with fast qualifiers")(static_cast <bool> (!Quals.hasFastQualifiers() &&
"ExtQuals created with fast qualifiers") ? void (0) : __assert_fail
("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "clang/include/clang/AST/Type.h", 1410, __extension__ __PRETTY_FUNCTION__
))
;
1411 }
1412
1413 Qualifiers getQualifiers() const { return Quals; }
1414
1415 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1416 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1417
1418 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1419 Qualifiers::ObjCLifetime getObjCLifetime() const {
1420 return Quals.getObjCLifetime();
1421 }
1422
1423 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1424 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1425
1426 const Type *getBaseType() const { return BaseType; }
1427
1428public:
1429 void Profile(llvm::FoldingSetNodeID &ID) const {
1430 Profile(ID, getBaseType(), Quals);
1431 }
1432
1433 static void Profile(llvm::FoldingSetNodeID &ID,
1434 const Type *BaseType,
1435 Qualifiers Quals) {
1436 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")(static_cast <bool> (!Quals.hasFastQualifiers() &&
"fast qualifiers in ExtQuals hash!") ? void (0) : __assert_fail
("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "clang/include/clang/AST/Type.h", 1436, __extension__ __PRETTY_FUNCTION__
))
;
1437 ID.AddPointer(BaseType);
1438 Quals.Profile(ID);
1439 }
1440};
1441
1442/// The kind of C++11 ref-qualifier associated with a function type.
1443/// This determines whether a member function's "this" object can be an
1444/// lvalue, rvalue, or neither.
1445enum RefQualifierKind {
1446 /// No ref-qualifier was provided.
1447 RQ_None = 0,
1448
1449 /// An lvalue ref-qualifier was provided (\c &).
1450 RQ_LValue,
1451
1452 /// An rvalue ref-qualifier was provided (\c &&).
1453 RQ_RValue
1454};
1455
1456/// Which keyword(s) were used to create an AutoType.
1457enum class AutoTypeKeyword {
1458 /// auto
1459 Auto,
1460
1461 /// decltype(auto)
1462 DecltypeAuto,
1463
1464 /// __auto_type (GNU extension)
1465 GNUAutoType
1466};
1467
1468/// The base class of the type hierarchy.
1469///
1470/// A central concept with types is that each type always has a canonical
1471/// type. A canonical type is the type with any typedef names stripped out
1472/// of it or the types it references. For example, consider:
1473///
1474/// typedef int foo;
1475/// typedef foo* bar;
1476/// 'int *' 'foo *' 'bar'
1477///
1478/// There will be a Type object created for 'int'. Since int is canonical, its
1479/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1480/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1481/// there is a PointerType that represents 'int*', which, like 'int', is
1482/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1483/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1484/// is also 'int*'.
1485///
1486/// Non-canonical types are useful for emitting diagnostics, without losing
1487/// information about typedefs being used. Canonical types are useful for type
1488/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1489/// about whether something has a particular form (e.g. is a function type),
1490/// because they implicitly, recursively, strip all typedefs out of a type.
1491///
1492/// Types, once created, are immutable.
1493///
1494class alignas(8) Type : public ExtQualsTypeCommonBase {
1495public:
1496 enum TypeClass {
1497#define TYPE(Class, Base) Class,
1498#define LAST_TYPE(Class) TypeLast = Class
1499#define ABSTRACT_TYPE(Class, Base)
1500#include "clang/AST/TypeNodes.inc"
1501 };
1502
1503private:
1504 /// Bitfields required by the Type class.
1505 class TypeBitfields {
1506 friend class Type;
1507 template <class T> friend class TypePropertyCache;
1508
1509 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1510 unsigned TC : 8;
1511
1512 /// Store information on the type dependency.
1513 unsigned Dependence : llvm::BitWidth<TypeDependence>;
1514
1515 /// True if the cache (i.e. the bitfields here starting with
1516 /// 'Cache') is valid.
1517 mutable unsigned CacheValid : 1;
1518
1519 /// Linkage of this type.
1520 mutable unsigned CachedLinkage : 3;
1521
1522 /// Whether this type involves and local or unnamed types.
1523 mutable unsigned CachedLocalOrUnnamed : 1;
1524
1525 /// Whether this type comes from an AST file.
1526 mutable unsigned FromAST : 1;
1527
1528 bool isCacheValid() const {
1529 return CacheValid;
1530 }
1531
1532 Linkage getLinkage() const {
1533 assert(isCacheValid() && "getting linkage from invalid cache")(static_cast <bool> (isCacheValid() && "getting linkage from invalid cache"
) ? void (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "clang/include/clang/AST/Type.h", 1533, __extension__ __PRETTY_FUNCTION__
))
;
1534 return static_cast<Linkage>(CachedLinkage);
1535 }
1536
1537 bool hasLocalOrUnnamedType() const {
1538 assert(isCacheValid() && "getting linkage from invalid cache")(static_cast <bool> (isCacheValid() && "getting linkage from invalid cache"
) ? void (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "clang/include/clang/AST/Type.h", 1538, __extension__ __PRETTY_FUNCTION__
))
;
1539 return CachedLocalOrUnnamed;
1540 }
1541 };
1542 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1543
1544protected:
1545 // These classes allow subclasses to somewhat cleanly pack bitfields
1546 // into Type.
1547
1548 class ArrayTypeBitfields {
1549 friend class ArrayType;
1550
1551 unsigned : NumTypeBits;
1552
1553 /// CVR qualifiers from declarations like
1554 /// 'int X[static restrict 4]'. For function parameters only.
1555 unsigned IndexTypeQuals : 3;
1556
1557 /// Storage class qualifiers from declarations like
1558 /// 'int X[static restrict 4]'. For function parameters only.
1559 /// Actually an ArrayType::ArraySizeModifier.
1560 unsigned SizeModifier : 3;
1561 };
1562
1563 class ConstantArrayTypeBitfields {
1564 friend class ConstantArrayType;
1565
1566 unsigned : NumTypeBits + 3 + 3;
1567
1568 /// Whether we have a stored size expression.
1569 unsigned HasStoredSizeExpr : 1;
1570 };
1571
1572 class BuiltinTypeBitfields {
1573 friend class BuiltinType;
1574
1575 unsigned : NumTypeBits;
1576
1577 /// The kind (BuiltinType::Kind) of builtin type this is.
1578 unsigned Kind : 8;
1579 };
1580
1581 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1582 /// Only common bits are stored here. Additional uncommon bits are stored
1583 /// in a trailing object after FunctionProtoType.
1584 class FunctionTypeBitfields {
1585 friend class FunctionProtoType;
1586 friend class FunctionType;
1587
1588 unsigned : NumTypeBits;
1589
1590 /// Extra information which affects how the function is called, like
1591 /// regparm and the calling convention.
1592 unsigned ExtInfo : 13;
1593
1594 /// The ref-qualifier associated with a \c FunctionProtoType.
1595 ///
1596 /// This is a value of type \c RefQualifierKind.
1597 unsigned RefQualifier : 2;
1598
1599 /// Used only by FunctionProtoType, put here to pack with the
1600 /// other bitfields.
1601 /// The qualifiers are part of FunctionProtoType because...
1602 ///
1603 /// C++ 8.3.5p4: The return type, the parameter type list and the
1604 /// cv-qualifier-seq, [...], are part of the function type.
1605 unsigned FastTypeQuals : Qualifiers::FastWidth;
1606 /// Whether this function has extended Qualifiers.
1607 unsigned HasExtQuals : 1;
1608
1609 /// The number of parameters this function has, not counting '...'.
1610 /// According to [implimits] 8 bits should be enough here but this is
1611 /// somewhat easy to exceed with metaprogramming and so we would like to
1612 /// keep NumParams as wide as reasonably possible.
1613 unsigned NumParams : 16;
1614
1615 /// The type of exception specification this function has.
1616 unsigned ExceptionSpecType : 4;
1617
1618 /// Whether this function has extended parameter information.
1619 unsigned HasExtParameterInfos : 1;
1620
1621 /// Whether the function is variadic.
1622 unsigned Variadic : 1;
1623
1624 /// Whether this function has a trailing return type.
1625 unsigned HasTrailingReturn : 1;
1626 };
1627
1628 class ObjCObjectTypeBitfields {
1629 friend class ObjCObjectType;
1630
1631 unsigned : NumTypeBits;
1632
1633 /// The number of type arguments stored directly on this object type.
1634 unsigned NumTypeArgs : 7;
1635
1636 /// The number of protocols stored directly on this object type.
1637 unsigned NumProtocols : 6;
1638
1639 /// Whether this is a "kindof" type.
1640 unsigned IsKindOf : 1;
1641 };
1642
1643 class ReferenceTypeBitfields {
1644 friend class ReferenceType;
1645
1646 unsigned : NumTypeBits;
1647
1648 /// True if the type was originally spelled with an lvalue sigil.
1649 /// This is never true of rvalue references but can also be false
1650 /// on lvalue references because of C++0x [dcl.typedef]p9,
1651 /// as follows:
1652 ///
1653 /// typedef int &ref; // lvalue, spelled lvalue
1654 /// typedef int &&rvref; // rvalue
1655 /// ref &a; // lvalue, inner ref, spelled lvalue
1656 /// ref &&a; // lvalue, inner ref
1657 /// rvref &a; // lvalue, inner ref, spelled lvalue
1658 /// rvref &&a; // rvalue, inner ref
1659 unsigned SpelledAsLValue : 1;
1660
1661 /// True if the inner type is a reference type. This only happens
1662 /// in non-canonical forms.
1663 unsigned InnerRef : 1;
1664 };
1665
1666 class TypeWithKeywordBitfields {
1667 friend class TypeWithKeyword;
1668
1669 unsigned : NumTypeBits;
1670
1671 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1672 unsigned Keyword : 8;
1673 };
1674
1675 enum { NumTypeWithKeywordBits = 8 };
1676
1677 class ElaboratedTypeBitfields {
1678 friend class ElaboratedType;
1679
1680 unsigned : NumTypeBits;
1681 unsigned : NumTypeWithKeywordBits;
1682
1683 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1684 unsigned HasOwnedTagDecl : 1;
1685 };
1686
1687 class VectorTypeBitfields {
1688 friend class VectorType;
1689 friend class DependentVectorType;
1690
1691 unsigned : NumTypeBits;
1692
1693 /// The kind of vector, either a generic vector type or some
1694 /// target-specific vector type such as for AltiVec or Neon.
1695 unsigned VecKind : 3;
1696 /// The number of elements in the vector.
1697 uint32_t NumElements;
1698 };
1699
1700 class AttributedTypeBitfields {
1701 friend class AttributedType;
1702
1703 unsigned : NumTypeBits;
1704
1705 /// An AttributedType::Kind
1706 unsigned AttrKind : 32 - NumTypeBits;
1707 };
1708
1709 class AutoTypeBitfields {
1710 friend class AutoType;
1711
1712 unsigned : NumTypeBits;
1713
1714 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1715 /// or '__auto_type'? AutoTypeKeyword value.
1716 unsigned Keyword : 2;
1717
1718 /// The number of template arguments in the type-constraints, which is
1719 /// expected to be able to hold at least 1024 according to [implimits].
1720 /// However as this limit is somewhat easy to hit with template
1721 /// metaprogramming we'd prefer to keep it as large as possible.
1722 /// At the moment it has been left as a non-bitfield since this type
1723 /// safely fits in 64 bits as an unsigned, so there is no reason to
1724 /// introduce the performance impact of a bitfield.
1725 unsigned NumArgs;
1726 };
1727
1728 class SubstTemplateTypeParmPackTypeBitfields {
1729 friend class SubstTemplateTypeParmPackType;
1730
1731 unsigned : NumTypeBits;
1732
1733 /// The number of template arguments in \c Arguments, which is
1734 /// expected to be able to hold at least 1024 according to [implimits].
1735 /// However as this limit is somewhat easy to hit with template
1736 /// metaprogramming we'd prefer to keep it as large as possible.
1737 /// At the moment it has been left as a non-bitfield since this type
1738 /// safely fits in 64 bits as an unsigned, so there is no reason to
1739 /// introduce the performance impact of a bitfield.
1740 unsigned NumArgs;
1741 };
1742
1743 class TemplateSpecializationTypeBitfields {
1744 friend class TemplateSpecializationType;
1745
1746 unsigned : NumTypeBits;
1747
1748 /// Whether this template specialization type is a substituted type alias.
1749 unsigned TypeAlias : 1;
1750
1751 /// The number of template arguments named in this class template
1752 /// specialization, which is expected to be able to hold at least 1024
1753 /// according to [implimits]. However, as this limit is somewhat easy to
1754 /// hit with template metaprogramming we'd prefer to keep it as large
1755 /// as possible. At the moment it has been left as a non-bitfield since
1756 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1757 /// to introduce the performance impact of a bitfield.
1758 unsigned NumArgs;
1759 };
1760
1761 class DependentTemplateSpecializationTypeBitfields {
1762 friend class DependentTemplateSpecializationType;
1763
1764 unsigned : NumTypeBits;
1765 unsigned : NumTypeWithKeywordBits;
1766
1767 /// The number of template arguments named in this class template
1768 /// specialization, which is expected to be able to hold at least 1024
1769 /// according to [implimits]. However, as this limit is somewhat easy to
1770 /// hit with template metaprogramming we'd prefer to keep it as large
1771 /// as possible. At the moment it has been left as a non-bitfield since
1772 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1773 /// to introduce the performance impact of a bitfield.
1774 unsigned NumArgs;
1775 };
1776
1777 class PackExpansionTypeBitfields {
1778 friend class PackExpansionType;
1779
1780 unsigned : NumTypeBits;
1781
1782 /// The number of expansions that this pack expansion will
1783 /// generate when substituted (+1), which is expected to be able to
1784 /// hold at least 1024 according to [implimits]. However, as this limit
1785 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1786 /// keep it as large as possible. At the moment it has been left as a
1787 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1788 /// there is no reason to introduce the performance impact of a bitfield.
1789 ///
1790 /// This field will only have a non-zero value when some of the parameter
1791 /// packs that occur within the pattern have been substituted but others
1792 /// have not.
1793 unsigned NumExpansions;
1794 };
1795
1796 union {
1797 TypeBitfields TypeBits;
1798 ArrayTypeBitfields ArrayTypeBits;
1799 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1800 AttributedTypeBitfields AttributedTypeBits;
1801 AutoTypeBitfields AutoTypeBits;
1802 BuiltinTypeBitfields BuiltinTypeBits;
1803 FunctionTypeBitfields FunctionTypeBits;
1804 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1805 ReferenceTypeBitfields ReferenceTypeBits;
1806 TypeWithKeywordBitfields TypeWithKeywordBits;
1807 ElaboratedTypeBitfields ElaboratedTypeBits;
1808 VectorTypeBitfields VectorTypeBits;
1809 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1810 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1811 DependentTemplateSpecializationTypeBitfields
1812 DependentTemplateSpecializationTypeBits;
1813 PackExpansionTypeBitfields PackExpansionTypeBits;
1814 };
1815
1816private:
1817 template <class T> friend class TypePropertyCache;
1818
1819 /// Set whether this type comes from an AST file.
1820 void setFromAST(bool V = true) const {
1821 TypeBits.FromAST = V;
1822 }
1823
1824protected:
1825 friend class ASTContext;
1826
1827 Type(TypeClass tc, QualType canon, TypeDependence Dependence)
1828 : ExtQualsTypeCommonBase(this,
1829 canon.isNull() ? QualType(this_(), 0) : canon) {
1830 static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
1831 "changing bitfields changed sizeof(Type)!");
1832 static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
1833 "Insufficient alignment!");
1834 TypeBits.TC = tc;
1835 TypeBits.Dependence = static_cast<unsigned>(Dependence);
1836 TypeBits.CacheValid = false;
1837 TypeBits.CachedLocalOrUnnamed = false;
1838 TypeBits.CachedLinkage = NoLinkage;
1839 TypeBits.FromAST = false;
1840 }
1841
1842 // silence VC++ warning C4355: 'this' : used in base member initializer list
1843 Type *this_() { return this; }
1844
1845 void setDependence(TypeDependence D) {
1846 TypeBits.Dependence = static_cast<unsigned>(D);
1847 }
1848
1849 void addDependence(TypeDependence D) { setDependence(getDependence() | D); }
1850
1851public:
1852 friend class ASTReader;
1853 friend class ASTWriter;
1854 template <class T> friend class serialization::AbstractTypeReader;
1855 template <class T> friend class serialization::AbstractTypeWriter;
1856
1857 Type(const Type &) = delete;
1858 Type(Type &&) = delete;
1859 Type &operator=(const Type &) = delete;
1860 Type &operator=(Type &&) = delete;
1861
1862 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1863
1864 /// Whether this type comes from an AST file.
1865 bool isFromAST() const { return TypeBits.FromAST; }
1866
1867 /// Whether this type is or contains an unexpanded parameter
1868 /// pack, used to support C++0x variadic templates.
1869 ///
1870 /// A type that contains a parameter pack shall be expanded by the
1871 /// ellipsis operator at some point. For example, the typedef in the
1872 /// following example contains an unexpanded parameter pack 'T':
1873 ///
1874 /// \code
1875 /// template<typename ...T>
1876 /// struct X {
1877 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1878 /// };
1879 /// \endcode
1880 ///
1881 /// Note that this routine does not specify which
1882 bool containsUnexpandedParameterPack() const {
1883 return getDependence() & TypeDependence::UnexpandedPack;
1884 }
1885
1886 /// Determines if this type would be canonical if it had no further
1887 /// qualification.
1888 bool isCanonicalUnqualified() const {
1889 return CanonicalType == QualType(this, 0);
1890 }
1891
1892 /// Pull a single level of sugar off of this locally-unqualified type.
1893 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1894 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1895 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1896
1897 /// As an extension, we classify types as one of "sized" or "sizeless";
1898 /// every type is one or the other. Standard types are all sized;
1899 /// sizeless types are purely an extension.
1900 ///
1901 /// Sizeless types contain data with no specified size, alignment,
1902 /// or layout.
1903 bool isSizelessType() const;
1904 bool isSizelessBuiltinType() const;
1905
1906 /// Determines if this is a sizeless type supported by the
1907 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
1908 /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
1909 bool isVLSTBuiltinType() const;
1910
1911 /// Returns the representative type for the element of an SVE builtin type.
1912 /// This is used to represent fixed-length SVE vectors created with the
1913 /// 'arm_sve_vector_bits' type attribute as VectorType.
1914 QualType getSveEltType(const ASTContext &Ctx) const;
1915
1916 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1917 /// object types, function types, and incomplete types.
1918
1919 /// Return true if this is an incomplete type.
1920 /// A type that can describe objects, but which lacks information needed to
1921 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1922 /// routine will need to determine if the size is actually required.
1923 ///
1924 /// Def If non-null, and the type refers to some kind of declaration
1925 /// that can be completed (such as a C struct, C++ class, or Objective-C
1926 /// class), will be set to the declaration.
1927 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1928
1929 /// Return true if this is an incomplete or object
1930 /// type, in other words, not a function type.
1931 bool isIncompleteOrObjectType() const {
1932 return !isFunctionType();
1933 }
1934
1935 /// Determine whether this type is an object type.
1936 bool isObjectType() const {
1937 // C++ [basic.types]p8:
1938 // An object type is a (possibly cv-qualified) type that is not a
1939 // function type, not a reference type, and not a void type.
1940 return !isReferenceType() && !isFunctionType() && !isVoidType();
1941 }
1942
1943 /// Return true if this is a literal type
1944 /// (C++11 [basic.types]p10)
1945 bool isLiteralType(const ASTContext &Ctx) const;
1946
1947 /// Determine if this type is a structural type, per C++20 [temp.param]p7.
1948 bool isStructuralType() const;
1949
1950 /// Test if this type is a standard-layout type.
1951 /// (C++0x [basic.type]p9)
1952 bool isStandardLayoutType() const;
1953
1954 /// Helper methods to distinguish type categories. All type predicates
1955 /// operate on the canonical type, ignoring typedefs and qualifiers.
1956
1957 /// Returns true if the type is a builtin type.
1958 bool isBuiltinType() const;
1959
1960 /// Test for a particular builtin type.
1961 bool isSpecificBuiltinType(unsigned K) const;
1962
1963 /// Test for a type which does not represent an actual type-system type but
1964 /// is instead used as a placeholder for various convenient purposes within
1965 /// Clang. All such types are BuiltinTypes.
1966 bool isPlaceholderType() const;
1967 const BuiltinType *getAsPlaceholderType() const;
1968
1969 /// Test for a specific placeholder type.
1970 bool isSpecificPlaceholderType(unsigned K) const;
1971
1972 /// Test for a placeholder type other than Overload; see
1973 /// BuiltinType::isNonOverloadPlaceholderType.
1974 bool isNonOverloadPlaceholderType() const;
1975
1976 /// isIntegerType() does *not* include complex integers (a GCC extension).
1977 /// isComplexIntegerType() can be used to test for complex integers.
1978 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1979 bool isEnumeralType() const;
1980
1981 /// Determine whether this type is a scoped enumeration type.
1982 bool isScopedEnumeralType() const;
1983 bool isBooleanType() const;
1984 bool isCharType() const;
1985 bool isWideCharType() const;
1986 bool isChar8Type() const;
1987 bool isChar16Type() const;
1988 bool isChar32Type() const;
1989 bool isAnyCharacterType() const;
1990 bool isIntegralType(const ASTContext &Ctx) const;
1991
1992 /// Determine whether this type is an integral or enumeration type.
1993 bool isIntegralOrEnumerationType() const;
1994
1995 /// Determine whether this type is an integral or unscoped enumeration type.
1996 bool isIntegralOrUnscopedEnumerationType() const;
1997 bool isUnscopedEnumerationType() const;
1998
1999 /// Floating point categories.
2000 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
2001 /// isComplexType() does *not* include complex integers (a GCC extension).
2002 /// isComplexIntegerType() can be used to test for complex integers.
2003 bool isComplexType() const; // C99 6.2.5p11 (complex)
2004 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
2005 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
2006 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
2007 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
2008 bool isBFloat16Type() const;
2009 bool isFloat128Type() const;
2010 bool isIbm128Type() const;
2011 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
2012 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
2013 bool isVoidType() const; // C99 6.2.5p19
2014 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
2015 bool isAggregateType() const;
2016 bool isFundamentalType() const;
2017 bool isCompoundType() const;
2018
2019 // Type Predicates: Check to see if this type is structurally the specified
2020 // type, ignoring typedefs and qualifiers.
2021 bool isFunctionType() const;
2022 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2023 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2024 bool isPointerType() const;
2025 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2026 bool isBlockPointerType() const;
2027 bool isVoidPointerType() const;
2028 bool isReferenceType() const;
2029 bool isLValueReferenceType() const;
2030 bool isRValueReferenceType() const;
2031 bool isObjectPointerType() const;
2032 bool isFunctionPointerType() const;
2033 bool isFunctionReferenceType() const;
2034 bool isMemberPointerType() const;
2035 bool isMemberFunctionPointerType() const;
2036 bool isMemberDataPointerType() const;
2037 bool isArrayType() const;
2038 bool isConstantArrayType() const;
2039 bool isIncompleteArrayType() const;
2040 bool isVariableArrayType() const;
2041 bool isDependentSizedArrayType() const;
2042 bool isRecordType() const;
2043 bool isClassType() const;
2044 bool isStructureType() const;
2045 bool isObjCBoxableRecordType() const;
2046 bool isInterfaceType() const;
2047 bool isStructureOrClassType() const;
2048 bool isUnionType() const;
2049 bool isComplexIntegerType() const; // GCC _Complex integer type.
2050 bool isVectorType() const; // GCC vector type.
2051 bool isExtVectorType() const; // Extended vector type.
2052 bool isExtVectorBoolType() const; // Extended vector type with bool element.
2053 bool isMatrixType() const; // Matrix type.
2054 bool isConstantMatrixType() const; // Constant matrix type.
2055 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2056 bool isObjCObjectPointerType() const; // pointer to ObjC object
2057 bool isObjCRetainableType() const; // ObjC object or block pointer
2058 bool isObjCLifetimeType() const; // (array of)* retainable type
2059 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2060 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2061 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2062 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2063 // for the common case.
2064 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2065 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2066 bool isObjCQualifiedIdType() const; // id<foo>
2067 bool isObjCQualifiedClassType() const; // Class<foo>
2068 bool isObjCObjectOrInterfaceType() const;
2069 bool isObjCIdType() const; // id
2070 bool isDecltypeType() const;
2071 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2072 /// qualifier?
2073 ///
2074 /// This approximates the answer to the following question: if this
2075 /// translation unit were compiled in ARC, would this type be qualified
2076 /// with __unsafe_unretained?
2077 bool isObjCInertUnsafeUnretainedType() const {
2078 return hasAttr(attr::ObjCInertUnsafeUnretained);
2079 }
2080
2081 /// Whether the type is Objective-C 'id' or a __kindof type of an
2082 /// object type, e.g., __kindof NSView * or __kindof id
2083 /// <NSCopying>.
2084 ///
2085 /// \param bound Will be set to the bound on non-id subtype types,
2086 /// which will be (possibly specialized) Objective-C class type, or
2087 /// null for 'id.
2088 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2089 const ObjCObjectType *&bound) const;
2090
2091 bool isObjCClassType() const; // Class
2092
2093 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2094 /// Class type, e.g., __kindof Class <NSCopying>.
2095 ///
2096 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2097 /// here because Objective-C's type system cannot express "a class
2098 /// object for a subclass of NSFoo".
2099 bool isObjCClassOrClassKindOfType() const;
2100
2101 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2102 bool isObjCSelType() const; // Class
2103 bool isObjCBuiltinType() const; // 'id' or 'Class'
2104 bool isObjCARCBridgableType() const;
2105 bool isCARCBridgableType() const;
2106 bool isTemplateTypeParmType() const; // C++ template type parameter
2107 bool isNullPtrType() const; // C++11 std::nullptr_t
2108 bool isNothrowT() const; // C++ std::nothrow_t
2109 bool isAlignValT() const; // C++17 std::align_val_t
2110 bool isStdByteType() const; // C++17 std::byte
2111 bool isAtomicType() const; // C11 _Atomic()
2112 bool isUndeducedAutoType() const; // C++11 auto or
2113 // C++14 decltype(auto)
2114 bool isTypedefNameType() const; // typedef or alias template
2115
2116#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2117 bool is##Id##Type() const;
2118#include "clang/Basic/OpenCLImageTypes.def"
2119
2120 bool isImageType() const; // Any OpenCL image type
2121
2122 bool isSamplerT() const; // OpenCL sampler_t
2123 bool isEventT() const; // OpenCL event_t
2124 bool isClkEventT() const; // OpenCL clk_event_t
2125 bool isQueueT() const; // OpenCL queue_t
2126 bool isReserveIDT() const; // OpenCL reserve_id_t
2127
2128#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2129 bool is##Id##Type() const;
2130#include "clang/Basic/OpenCLExtensionTypes.def"
2131 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2132 bool isOCLIntelSubgroupAVCType() const;
2133 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2134
2135 bool isPipeType() const; // OpenCL pipe type
2136 bool isBitIntType() const; // Bit-precise integer type
2137 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2138
2139 /// Determines if this type, which must satisfy
2140 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2141 /// than implicitly __strong.
2142 bool isObjCARCImplicitlyUnretainedType() const;
2143
2144 /// Check if the type is the CUDA device builtin surface type.
2145 bool isCUDADeviceBuiltinSurfaceType() const;
2146 /// Check if the type is the CUDA device builtin texture type.
2147 bool isCUDADeviceBuiltinTextureType() const;
2148
2149 /// Return the implicit lifetime for this type, which must not be dependent.
2150 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2151
2152 enum ScalarTypeKind {
2153 STK_CPointer,
2154 STK_BlockPointer,
2155 STK_ObjCObjectPointer,
2156 STK_MemberPointer,
2157 STK_Bool,
2158 STK_Integral,
2159 STK_Floating,
2160 STK_IntegralComplex,
2161 STK_FloatingComplex,
2162 STK_FixedPoint
2163 };
2164
2165 /// Given that this is a scalar type, classify it.
2166 ScalarTypeKind getScalarTypeKind() const;
2167
2168 TypeDependence getDependence() const {
2169 return static_cast<TypeDependence>(TypeBits.Dependence);
2170 }
2171
2172 /// Whether this type is an error type.
2173 bool containsErrors() const {
2174 return getDependence() & TypeDependence::Error;
2175 }
2176
2177 /// Whether this type is a dependent type, meaning that its definition
2178 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2179 bool isDependentType() const {
2180 return getDependence() & TypeDependence::Dependent;
2181 }
2182
2183 /// Determine whether this type is an instantiation-dependent type,
2184 /// meaning that the type involves a template parameter (even if the
2185 /// definition does not actually depend on the type substituted for that
2186 /// template parameter).
2187 bool isInstantiationDependentType() const {
2188 return getDependence() & TypeDependence::Instantiation;
2189 }
2190
2191 /// Determine whether this type is an undeduced type, meaning that
2192 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2193 /// deduced.
2194 bool isUndeducedType() const;
2195
2196 /// Whether this type is a variably-modified type (C99 6.7.5).
2197 bool isVariablyModifiedType() const {
2198 return getDependence() & TypeDependence::VariablyModified;
2199 }
2200
2201 /// Whether this type involves a variable-length array type
2202 /// with a definite size.
2203 bool hasSizedVLAType() const;
2204
2205 /// Whether this type is or contains a local or unnamed type.
2206 bool hasUnnamedOrLocalType() const;
2207
2208 bool isOverloadableType() const;
2209
2210 /// Determine wither this type is a C++ elaborated-type-specifier.
2211 bool isElaboratedTypeSpecifier() const;
2212
2213 bool canDecayToPointerType() const;
2214
2215 /// Whether this type is represented natively as a pointer. This includes
2216 /// pointers, references, block pointers, and Objective-C interface,
2217 /// qualified id, and qualified interface types, as well as nullptr_t.
2218 bool hasPointerRepresentation() const;
2219
2220 /// Whether this type can represent an objective pointer type for the
2221 /// purpose of GC'ability
2222 bool hasObjCPointerRepresentation() const;
2223
2224 /// Determine whether this type has an integer representation
2225 /// of some sort, e.g., it is an integer type or a vector.
2226 bool hasIntegerRepresentation() const;
2227
2228 /// Determine whether this type has an signed integer representation
2229 /// of some sort, e.g., it is an signed integer type or a vector.
2230 bool hasSignedIntegerRepresentation() const;
2231
2232 /// Determine whether this type has an unsigned integer representation
2233 /// of some sort, e.g., it is an unsigned integer type or a vector.
2234 bool hasUnsignedIntegerRepresentation() const;
2235
2236 /// Determine whether this type has a floating-point representation
2237 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2238 bool hasFloatingRepresentation() const;
2239
2240 // Type Checking Functions: Check to see if this type is structurally the
2241 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2242 // the best type we can.
2243 const RecordType *getAsStructureType() const;
2244 /// NOTE: getAs*ArrayType are methods on ASTContext.
2245 const RecordType *getAsUnionType() const;
2246 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2247 const ObjCObjectType *getAsObjCInterfaceType() const;
2248
2249 // The following is a convenience method that returns an ObjCObjectPointerType
2250 // for object declared using an interface.
2251 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2252 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2253 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2254 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2255
2256 /// Retrieves the CXXRecordDecl that this type refers to, either
2257 /// because the type is a RecordType or because it is the injected-class-name
2258 /// type of a class template or class template partial specialization.
2259 CXXRecordDecl *getAsCXXRecordDecl() const;
2260
2261 /// Retrieves the RecordDecl this type refers to.
2262 RecordDecl *getAsRecordDecl() const;
2263
2264 /// Retrieves the TagDecl that this type refers to, either
2265 /// because the type is a TagType or because it is the injected-class-name
2266 /// type of a class template or class template partial specialization.
2267 TagDecl *getAsTagDecl() const;
2268
2269 /// If this is a pointer or reference to a RecordType, return the
2270 /// CXXRecordDecl that the type refers to.
2271 ///
2272 /// If this is not a pointer or reference, or the type being pointed to does
2273 /// not refer to a CXXRecordDecl, returns NULL.
2274 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2275
2276 /// Get the DeducedType whose type will be deduced for a variable with
2277 /// an initializer of this type. This looks through declarators like pointer
2278 /// types, but not through decltype or typedefs.
2279 DeducedType *getContainedDeducedType() const;
2280
2281 /// Get the AutoType whose type will be deduced for a variable with
2282 /// an initializer of this type. This looks through declarators like pointer
2283 /// types, but not through decltype or typedefs.
2284 AutoType *getContainedAutoType() const {
2285 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2286 }
2287
2288 /// Determine whether this type was written with a leading 'auto'
2289 /// corresponding to a trailing return type (possibly for a nested
2290 /// function type within a pointer to function type or similar).
2291 bool hasAutoForTrailingReturnType() const;
2292
2293 /// Member-template getAs<specific type>'. Look through sugar for
2294 /// an instance of \<specific type>. This scheme will eventually
2295 /// replace the specific getAsXXXX methods above.
2296 ///
2297 /// There are some specializations of this member template listed
2298 /// immediately following this class.
2299 template <typename T> const T *getAs() const;
2300
2301 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2302 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2303 /// This is used when you need to walk over sugar nodes that represent some
2304 /// kind of type adjustment from a type that was written as a \<specific type>
2305 /// to another type that is still canonically a \<specific type>.
2306 template <typename T> const T *getAsAdjusted() const;
2307
2308 /// A variant of getAs<> for array types which silently discards
2309 /// qualifiers from the outermost type.
2310 const ArrayType *getAsArrayTypeUnsafe() const;
2311
2312 /// Member-template castAs<specific type>. Look through sugar for
2313 /// the underlying instance of \<specific type>.
2314 ///
2315 /// This method has the same relationship to getAs<T> as cast<T> has
2316 /// to dyn_cast<T>; which is to say, the underlying type *must*
2317 /// have the intended type, and this method will never return null.
2318 template <typename T> const T *castAs() const;
2319
2320 /// A variant of castAs<> for array type which silently discards
2321 /// qualifiers from the outermost type.
2322 const ArrayType *castAsArrayTypeUnsafe() const;
2323
2324 /// Determine whether this type had the specified attribute applied to it
2325 /// (looking through top-level type sugar).
2326 bool hasAttr(attr::Kind AK) const;
2327
2328 /// Get the base element type of this type, potentially discarding type
2329 /// qualifiers. This should never be used when type qualifiers
2330 /// are meaningful.
2331 const Type *getBaseElementTypeUnsafe() const;
2332
2333 /// If this is an array type, return the element type of the array,
2334 /// potentially with type qualifiers missing.
2335 /// This should never be used when type qualifiers are meaningful.
2336 const Type *getArrayElementTypeNoTypeQual() const;
2337
2338 /// If this is a pointer type, return the pointee type.
2339 /// If this is an array type, return the array element type.
2340 /// This should never be used when type qualifiers are meaningful.
2341 const Type *getPointeeOrArrayElementType() const;
2342
2343 /// If this is a pointer, ObjC object pointer, or block
2344 /// pointer, this returns the respective pointee.
2345 QualType getPointeeType() const;
2346
2347 /// Return the specified type with any "sugar" removed from the type,
2348 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2349 const Type *getUnqualifiedDesugaredType() const;
2350
2351 /// More type predicates useful for type checking/promotion
2352 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2353
2354 /// Return true if this is an integer type that is
2355 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2356 /// or an enum decl which has a signed representation.
2357 bool isSignedIntegerType() const;
2358
2359 /// Return true if this is an integer type that is
2360 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2361 /// or an enum decl which has an unsigned representation.
2362 bool isUnsignedIntegerType() const;
2363
2364 /// Determines whether this is an integer type that is signed or an
2365 /// enumeration types whose underlying type is a signed integer type.
2366 bool isSignedIntegerOrEnumerationType() const;
2367
2368 /// Determines whether this is an integer type that is unsigned or an
2369 /// enumeration types whose underlying type is a unsigned integer type.
2370 bool isUnsignedIntegerOrEnumerationType() const;
2371
2372 /// Return true if this is a fixed point type according to
2373 /// ISO/IEC JTC1 SC22 WG14 N1169.
2374 bool isFixedPointType() const;
2375
2376 /// Return true if this is a fixed point or integer type.
2377 bool isFixedPointOrIntegerType() const;
2378
2379 /// Return true if this is a saturated fixed point type according to
2380 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2381 bool isSaturatedFixedPointType() const;
2382
2383 /// Return true if this is a saturated fixed point type according to
2384 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2385 bool isUnsaturatedFixedPointType() const;
2386
2387 /// Return true if this is a fixed point type that is signed according
2388 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2389 bool isSignedFixedPointType() const;
2390
2391 /// Return true if this is a fixed point type that is unsigned according
2392 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2393 bool isUnsignedFixedPointType() const;
2394
2395 /// Return true if this is not a variable sized type,
2396 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2397 /// incomplete types.
2398 bool isConstantSizeType() const;
2399
2400 /// Returns true if this type can be represented by some
2401 /// set of type specifiers.
2402 bool isSpecifierType() const;
2403
2404 /// Determine the linkage of this type.
2405 Linkage getLinkage() const;
2406
2407 /// Determine the visibility of this type.
2408 Visibility getVisibility() const {
2409 return getLinkageAndVisibility().getVisibility();
2410 }
2411
2412 /// Return true if the visibility was explicitly set is the code.
2413 bool isVisibilityExplicit() const {
2414 return getLinkageAndVisibility().isVisibilityExplicit();
2415 }
2416
2417 /// Determine the linkage and visibility of this type.
2418 LinkageInfo getLinkageAndVisibility() const;
2419
2420 /// True if the computed linkage is valid. Used for consistency
2421 /// checking. Should always return true.
2422 bool isLinkageValid() const;
2423
2424 /// Determine the nullability of the given type.
2425 ///
2426 /// Note that nullability is only captured as sugar within the type
2427 /// system, not as part of the canonical type, so nullability will
2428 /// be lost by canonicalization and desugaring.
2429 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2430
2431 /// Determine whether the given type can have a nullability
2432 /// specifier applied to it, i.e., if it is any kind of pointer type.
2433 ///
2434 /// \param ResultIfUnknown The value to return if we don't yet know whether
2435 /// this type can have nullability because it is dependent.
2436 bool canHaveNullability(bool ResultIfUnknown = true) const;
2437
2438 /// Retrieve the set of substitutions required when accessing a member
2439 /// of the Objective-C receiver type that is declared in the given context.
2440 ///
2441 /// \c *this is the type of the object we're operating on, e.g., the
2442 /// receiver for a message send or the base of a property access, and is
2443 /// expected to be of some object or object pointer type.
2444 ///
2445 /// \param dc The declaration context for which we are building up a
2446 /// substitution mapping, which should be an Objective-C class, extension,
2447 /// category, or method within.
2448 ///
2449 /// \returns an array of type arguments that can be substituted for
2450 /// the type parameters of the given declaration context in any type described
2451 /// within that context, or an empty optional to indicate that no
2452 /// substitution is required.
2453 Optional<ArrayRef<QualType>>
2454 getObjCSubstitutions(const DeclContext *dc) const;
2455
2456 /// Determines if this is an ObjC interface type that may accept type
2457 /// parameters.
2458 bool acceptsObjCTypeParams() const;
2459
2460 const char *getTypeClassName() const;
2461
2462 QualType getCanonicalTypeInternal() const {
2463 return CanonicalType;
2464 }
2465
2466 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2467 void dump() const;
2468 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2469};
2470
2471/// This will check for a TypedefType by removing any existing sugar
2472/// until it reaches a TypedefType or a non-sugared type.
2473template <> const TypedefType *Type::getAs() const;
2474
2475/// This will check for a TemplateSpecializationType by removing any
2476/// existing sugar until it reaches a TemplateSpecializationType or a
2477/// non-sugared type.
2478template <> const TemplateSpecializationType *Type::getAs() const;
2479
2480/// This will check for an AttributedType by removing any existing sugar
2481/// until it reaches an AttributedType or a non-sugared type.
2482template <> const AttributedType *Type::getAs() const;
2483
2484// We can do canonical leaf types faster, because we don't have to
2485// worry about preserving child type decoration.
2486#define TYPE(Class, Base)
2487#define LEAF_TYPE(Class) \
2488template <> inline const Class##Type *Type::getAs() const { \
2489 return dyn_cast<Class##Type>(CanonicalType); \
2490} \
2491template <> inline const Class##Type *Type::castAs() const { \
2492 return cast<Class##Type>(CanonicalType); \
2493}
2494#include "clang/AST/TypeNodes.inc"
2495
2496/// This class is used for builtin types like 'int'. Builtin
2497/// types are always canonical and have a literal name field.
2498class BuiltinType : public Type {
2499public:
2500 enum Kind {
2501// OpenCL image types
2502#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2503#include "clang/Basic/OpenCLImageTypes.def"
2504// OpenCL extension types
2505#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2506#include "clang/Basic/OpenCLExtensionTypes.def"
2507// SVE Types
2508#define SVE_TYPE(Name, Id, SingletonId) Id,
2509#include "clang/Basic/AArch64SVEACLETypes.def"
2510// PPC MMA Types
2511#define PPC_VECTOR_TYPE(Name, Id, Size) Id,
2512#include "clang/Basic/PPCTypes.def"
2513// RVV Types
2514#define RVV_TYPE(Name, Id, SingletonId) Id,
2515#include "clang/Basic/RISCVVTypes.def"
2516// All other builtin types
2517#define BUILTIN_TYPE(Id, SingletonId) Id,
2518#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2519#include "clang/AST/BuiltinTypes.def"
2520 };
2521
2522private:
2523 friend class ASTContext; // ASTContext creates these.
2524
2525 BuiltinType(Kind K)
2526 : Type(Builtin, QualType(),
2527 K == Dependent ? TypeDependence::DependentInstantiation
2528 : TypeDependence::None) {
2529 BuiltinTypeBits.Kind = K;
2530 }
2531
2532public:
2533 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2534 StringRef getName(const PrintingPolicy &Policy) const;
2535
2536 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2537 // The StringRef is null-terminated.
2538 StringRef str = getName(Policy);
2539 assert(!str.empty() && str.data()[str.size()] == '\0')(static_cast <bool> (!str.empty() && str.data()
[str.size()] == '\0') ? void (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "clang/include/clang/AST/Type.h", 2539, __extension__ __PRETTY_FUNCTION__
))
;
2540 return str.data();
2541 }
2542
2543 bool isSugared() const { return false; }
2544 QualType desugar() const { return QualType(this, 0); }
2545
2546 bool isInteger() const {
2547 return getKind() >= Bool && getKind() <= Int128;
2548 }
2549
2550 bool isSignedInteger() const {
2551 return getKind() >= Char_S && getKind() <= Int128;
2552 }
2553
2554 bool isUnsignedInteger() const {
2555 return getKind() >= Bool && getKind() <= UInt128;
2556 }
2557
2558 bool isFloatingPoint() const {
2559 return getKind() >= Half && getKind() <= Ibm128;
2560 }
2561
2562 bool isSVEBool() const { return getKind() == Kind::SveBool; }
2563
2564 /// Determines whether the given kind corresponds to a placeholder type.
2565 static bool isPlaceholderTypeKind(Kind K) {
2566 return K >= Overload;
2567 }
2568
2569 /// Determines whether this type is a placeholder type, i.e. a type
2570 /// which cannot appear in arbitrary positions in a fully-formed
2571 /// expression.
2572 bool isPlaceholderType() const {
2573 return isPlaceholderTypeKind(getKind());
2574 }
2575
2576 /// Determines whether this type is a placeholder type other than
2577 /// Overload. Most placeholder types require only syntactic
2578 /// information about their context in order to be resolved (e.g.
2579 /// whether it is a call expression), which means they can (and
2580 /// should) be resolved in an earlier "phase" of analysis.
2581 /// Overload expressions sometimes pick up further information
2582 /// from their context, like whether the context expects a
2583 /// specific function-pointer type, and so frequently need
2584 /// special treatment.
2585 bool isNonOverloadPlaceholderType() const {
2586 return getKind() > Overload;
2587 }
2588
2589 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2590};
2591
2592/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2593/// types (_Complex float etc) as well as the GCC integer complex extensions.
2594class ComplexType : public Type, public llvm::FoldingSetNode {
2595 friend class ASTContext; // ASTContext creates these.
2596
2597 QualType ElementType;
2598
2599 ComplexType(QualType Element, QualType CanonicalPtr)
2600 : Type(Complex, CanonicalPtr, Element->getDependence()),
2601 ElementType(Element) {}
2602
2603public:
2604 QualType getElementType() const { return ElementType; }
2605
2606 bool isSugared() const { return false; }
2607 QualType desugar() const { return QualType(this, 0); }
2608
2609 void Profile(llvm::FoldingSetNodeID &ID) {
2610 Profile(ID, getElementType());
2611 }
2612
2613 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2614 ID.AddPointer(Element.getAsOpaquePtr());
2615 }
2616
2617 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2618};
2619
2620/// Sugar for parentheses used when specifying types.
2621class ParenType : public Type, public llvm::FoldingSetNode {
2622 friend class ASTContext; // ASTContext creates these.
2623
2624 QualType Inner;
2625
2626 ParenType(QualType InnerType, QualType CanonType)
2627 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
2628
2629public:
2630 QualType getInnerType() const { return Inner; }
2631
2632 bool isSugared() const { return true; }
2633 QualType desugar() const { return getInnerType(); }
2634
2635 void Profile(llvm::FoldingSetNodeID &ID) {
2636 Profile(ID, getInnerType());
2637 }
2638
2639 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2640 Inner.Profile(ID);
2641 }
2642
2643 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2644};
2645
2646/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2647class PointerType : public Type, public llvm::FoldingSetNode {
2648 friend class ASTContext; // ASTContext creates these.
2649
2650 QualType PointeeType;
2651
2652 PointerType(QualType Pointee, QualType CanonicalPtr)
2653 : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
2654 PointeeType(Pointee) {}
2655
2656public:
2657 QualType getPointeeType() const { return PointeeType; }
2658
2659 bool isSugared() const { return false; }
2660 QualType desugar() const { return QualType(this, 0); }
2661
2662 void Profile(llvm::FoldingSetNodeID &ID) {
2663 Profile(ID, getPointeeType());
2664 }
2665
2666 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2667 ID.AddPointer(Pointee.getAsOpaquePtr());
2668 }
2669
2670 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2671};
2672
2673/// Represents a type which was implicitly adjusted by the semantic
2674/// engine for arbitrary reasons. For example, array and function types can
2675/// decay, and function types can have their calling conventions adjusted.
2676class AdjustedType : public Type, public llvm::FoldingSetNode {
2677 QualType OriginalTy;
2678 QualType AdjustedTy;
2679
2680protected:
2681 friend class ASTContext; // ASTContext creates these.
2682
2683 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2684 QualType CanonicalPtr)
2685 : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
2686 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2687
2688public:
2689 QualType getOriginalType() const { return OriginalTy; }
2690 QualType getAdjustedType() const { return AdjustedTy; }
2691
2692 bool isSugared() const { return true; }
2693 QualType desugar() const { return AdjustedTy; }
2694
2695 void Profile(llvm::FoldingSetNodeID &ID) {
2696 Profile(ID, OriginalTy, AdjustedTy);
2697 }
2698
2699 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2700 ID.AddPointer(Orig.getAsOpaquePtr());
2701 ID.AddPointer(New.getAsOpaquePtr());
2702 }
2703
2704 static bool classof(const Type *T) {
2705 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2706 }
2707};
2708
2709/// Represents a pointer type decayed from an array or function type.
2710class DecayedType : public AdjustedType {
2711 friend class ASTContext; // ASTContext creates these.
2712
2713 inline
2714 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2715
2716public:
2717 QualType getDecayedType() const { return getAdjustedType(); }
2718
2719 inline QualType getPointeeType() const;
2720
2721 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2722};
2723
2724/// Pointer to a block type.
2725/// This type is to represent types syntactically represented as
2726/// "void (^)(int)", etc. Pointee is required to always be a function type.
2727class BlockPointerType : public Type, public llvm::FoldingSetNode {
2728 friend class ASTContext; // ASTContext creates these.
2729
2730 // Block is some kind of pointer type
2731 QualType PointeeType;
2732
2733 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2734 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
2735 PointeeType(Pointee) {}
2736
2737public:
2738 // Get the pointee type. Pointee is required to always be a function type.
2739 QualType getPointeeType() const { return PointeeType; }
2740
2741 bool isSugared() const { return false; }
2742 QualType desugar() const { return QualType(this, 0); }
2743
2744 void Profile(llvm::FoldingSetNodeID &ID) {
2745 Profile(ID, getPointeeType());
2746 }
2747
2748 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2749 ID.AddPointer(Pointee.getAsOpaquePtr());
2750 }
2751
2752 static bool classof(const Type *T) {
2753 return T->getTypeClass() == BlockPointer;
2754 }
2755};
2756
2757/// Base for LValueReferenceType and RValueReferenceType
2758class ReferenceType : public Type, public llvm::FoldingSetNode {
2759 QualType PointeeType;
2760
2761protected:
2762 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2763 bool SpelledAsLValue)
2764 : Type(tc, CanonicalRef, Referencee->getDependence()),
2765 PointeeType(Referencee) {
2766 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2767 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2768 }
2769
2770public:
2771 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2772 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2773
2774 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2775
2776 QualType getPointeeType() const {
2777 // FIXME: this might strip inner qualifiers; okay?
2778 const ReferenceType *T = this;
2779 while (T->isInnerRef())
2780 T = T->PointeeType->castAs<ReferenceType>();
2781 return T->PointeeType;
2782 }
2783
2784 void Profile(llvm::FoldingSetNodeID &ID) {
2785 Profile(ID, PointeeType, isSpelledAsLValue());
2786 }
2787
2788 static void Profile(llvm::FoldingSetNodeID &ID,
2789 QualType Referencee,
2790 bool SpelledAsLValue) {
2791 ID.AddPointer(Referencee.getAsOpaquePtr());
2792 ID.AddBoolean(SpelledAsLValue);
2793 }
2794
2795 static bool classof(const Type *T) {
2796 return T->getTypeClass() == LValueReference ||
2797 T->getTypeClass() == RValueReference;
2798 }
2799};
2800
2801/// An lvalue reference type, per C++11 [dcl.ref].
2802class LValueReferenceType : public ReferenceType {
2803 friend class ASTContext; // ASTContext creates these
2804
2805 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2806 bool SpelledAsLValue)
2807 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2808 SpelledAsLValue) {}
2809
2810public:
2811 bool isSugared() const { return false; }
2812 QualType desugar() const { return QualType(this, 0); }
2813
2814 static bool classof(const Type *T) {
2815 return T->getTypeClass() == LValueReference;
2816 }
2817};
2818
2819/// An rvalue reference type, per C++11 [dcl.ref].
2820class RValueReferenceType : public ReferenceType {
2821 friend class ASTContext; // ASTContext creates these
2822
2823 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2824 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2825
2826public:
2827 bool isSugared() const { return false; }
2828 QualType desugar() const { return QualType(this, 0); }
2829
2830 static bool classof(const Type *T) {
2831 return T->getTypeClass() == RValueReference;
2832 }
2833};
2834
2835/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2836///
2837/// This includes both pointers to data members and pointer to member functions.
2838class MemberPointerType : public Type, public llvm::FoldingSetNode {
2839 friend class ASTContext; // ASTContext creates these.
2840
2841 QualType PointeeType;
2842
2843 /// The class of which the pointee is a member. Must ultimately be a
2844 /// RecordType, but could be a typedef or a template parameter too.
2845 const Type *Class;
2846
2847 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2848 : Type(MemberPointer, CanonicalPtr,
2849 (Cls->getDependence() & ~TypeDependence::VariablyModified) |
2850 Pointee->getDependence()),
2851 PointeeType(Pointee), Class(Cls) {}
2852
2853public:
2854 QualType getPointeeType() const { return PointeeType; }
2855
2856 /// Returns true if the member type (i.e. the pointee type) is a
2857 /// function type rather than a data-member type.
2858 bool isMemberFunctionPointer() const {
2859 return PointeeType->isFunctionProtoType();
2860 }
2861
2862 /// Returns true if the member type (i.e. the pointee type) is a
2863 /// data type rather than a function type.
2864 bool isMemberDataPointer() const {
2865 return !PointeeType->isFunctionProtoType();
2866 }
2867
2868 const Type *getClass() const { return Class; }
2869 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2870
2871 bool isSugared() const { return false; }
2872 QualType desugar() const { return QualType(this, 0); }
2873
2874 void Profile(llvm::FoldingSetNodeID &ID) {
2875 Profile(ID, getPointeeType(), getClass());
2876 }
2877
2878 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2879 const Type *Class) {
2880 ID.AddPointer(Pointee.getAsOpaquePtr());
2881 ID.AddPointer(Class);
2882 }
2883
2884 static bool classof(const Type *T) {
2885 return T->getTypeClass() == MemberPointer;
2886 }
2887};
2888
2889/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2890class ArrayType : public Type, public llvm::FoldingSetNode {
2891public:
2892 /// Capture whether this is a normal array (e.g. int X[4])
2893 /// an array with a static size (e.g. int X[static 4]), or an array
2894 /// with a star size (e.g. int X[*]).
2895 /// 'static' is only allowed on function parameters.
2896 enum ArraySizeModifier {
2897 Normal, Static, Star
2898 };
2899
2900private:
2901 /// The element type of the array.
2902 QualType ElementType;
2903
2904protected:
2905 friend class ASTContext; // ASTContext creates these.
2906
2907 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2908 unsigned tq, const Expr *sz = nullptr);
2909
2910public:
2911 QualType getElementType() const { return ElementType; }
2912
2913 ArraySizeModifier getSizeModifier() const {
2914 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2915 }
2916
2917 Qualifiers getIndexTypeQualifiers() const {
2918 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2919 }
2920
2921 unsigned getIndexTypeCVRQualifiers() const {
2922 return ArrayTypeBits.IndexTypeQuals;
2923 }
2924
2925 static bool classof(const Type *T) {
2926 return T->getTypeClass() == ConstantArray ||
2927 T->getTypeClass() == VariableArray ||
2928 T->getTypeClass() == IncompleteArray ||
2929 T->getTypeClass() == DependentSizedArray;
2930 }
2931};
2932
2933/// Represents the canonical version of C arrays with a specified constant size.
2934/// For example, the canonical type for 'int A[4 + 4*100]' is a
2935/// ConstantArrayType where the element type is 'int' and the size is 404.
2936class ConstantArrayType final
2937 : public ArrayType,
2938 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2939 friend class ASTContext; // ASTContext creates these.
2940 friend TrailingObjects;
2941
2942 llvm::APInt Size; // Allows us to unique the type.
2943
2944 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2945 const Expr *sz, ArraySizeModifier sm, unsigned tq)
2946 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2947 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2948 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2949 assert(!can.isNull() && "canonical constant array should not have size")(static_cast <bool> (!can.isNull() && "canonical constant array should not have size"
) ? void (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\""
, "clang/include/clang/AST/Type.h", 2949, __extension__ __PRETTY_FUNCTION__
))
;
2950 *getTrailingObjects<const Expr*>() = sz;
2951 }
2952 }
2953
2954 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2955 return ConstantArrayTypeBits.HasStoredSizeExpr;
2956 }
2957
2958public:
2959 const llvm::APInt &getSize() const { return Size; }
2960 const Expr *getSizeExpr() const {
2961 return ConstantArrayTypeBits.HasStoredSizeExpr
2962 ? *getTrailingObjects<const Expr *>()
2963 : nullptr;
2964 }
2965 bool isSugared() const { return false; }
2966 QualType desugar() const { return QualType(this, 0); }
2967
2968 /// Determine the number of bits required to address a member of
2969 // an array with the given element type and number of elements.
2970 static unsigned getNumAddressingBits(const ASTContext &Context,
2971 QualType ElementType,
2972 const llvm::APInt &NumElements);
2973
2974 /// Determine the maximum number of active bits that an array's size
2975 /// can require, which limits the maximum size of the array.
2976 static unsigned getMaxSizeBits(const ASTContext &Context);
2977
2978 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
2979 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
2980 getSizeModifier(), getIndexTypeCVRQualifiers());
2981 }
2982
2983 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
2984 QualType ET, const llvm::APInt &ArraySize,
2985 const Expr *SizeExpr, ArraySizeModifier SizeMod,
2986 unsigned TypeQuals);
2987
2988 static bool classof(const Type *T) {
2989 return T->getTypeClass() == ConstantArray;
2990 }
2991};
2992
2993/// Represents a C array with an unspecified size. For example 'int A[]' has
2994/// an IncompleteArrayType where the element type is 'int' and the size is
2995/// unspecified.
2996class IncompleteArrayType : public ArrayType {
2997 friend class ASTContext; // ASTContext creates these.
2998
2999 IncompleteArrayType(QualType et, QualType can,
3000 ArraySizeModifier sm, unsigned tq)
3001 : ArrayType(IncompleteArray, et, can, sm, tq) {}
3002
3003public:
3004 friend class StmtIteratorBase;
3005
3006 bool isSugared() const { return false; }
3007 QualType desugar() const { return QualType(this, 0); }
3008
3009 static bool classof(const Type *T) {
3010 return T->getTypeClass() == IncompleteArray;
3011 }
3012
3013 void Profile(llvm::FoldingSetNodeID &ID) {
3014 Profile(ID, getElementType(), getSizeModifier(),
3015 getIndexTypeCVRQualifiers());
3016 }
3017
3018 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
3019 ArraySizeModifier SizeMod, unsigned TypeQuals) {
3020 ID.AddPointer(ET.getAsOpaquePtr());
3021 ID.AddInteger(SizeMod);
3022 ID.AddInteger(TypeQuals);
3023 }
3024};
3025
3026/// Represents a C array with a specified size that is not an
3027/// integer-constant-expression. For example, 'int s[x+foo()]'.
3028/// Since the size expression is an arbitrary expression, we store it as such.
3029///
3030/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3031/// should not be: two lexically equivalent variable array types could mean
3032/// different things, for example, these variables do not have the same type
3033/// dynamically:
3034///
3035/// void foo(int x) {
3036/// int Y[x];
3037/// ++x;
3038/// int Z[x];
3039/// }
3040class VariableArrayType : public ArrayType {
3041 friend class ASTContext; // ASTContext creates these.
3042
3043 /// An assignment-expression. VLA's are only permitted within
3044 /// a function block.
3045 Stmt *SizeExpr;
3046
3047 /// The range spanned by the left and right array brackets.
3048 SourceRange Brackets;
3049
3050 VariableArrayType(QualType et, QualType can, Expr *e,
3051 ArraySizeModifier sm, unsigned tq,
3052 SourceRange brackets)
3053 : ArrayType(VariableArray, et, can, sm, tq, e),
3054 SizeExpr((Stmt*) e), Brackets(brackets) {}
3055
3056public:
3057 friend class StmtIteratorBase;
3058
3059 Expr *getSizeExpr() const {
3060 // We use C-style casts instead of cast<> here because we do not wish
3061 // to have a dependency of Type.h on Stmt.h/Expr.h.
3062 return (Expr*) SizeExpr;
3063 }
3064
3065 SourceRange getBracketsRange() const { return Brackets; }
3066 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3067 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3068
3069 bool isSugared() const { return false; }
3070 QualType desugar() const { return QualType(this, 0); }
3071
3072 static bool classof(const Type *T) {
3073 return T->getTypeClass() == VariableArray;
3074 }
3075
3076 void Profile(llvm::FoldingSetNodeID &ID) {
3077 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "clang/include/clang/AST/Type.h", 3077)
;
3078 }
3079};
3080
3081/// Represents an array type in C++ whose size is a value-dependent expression.
3082///
3083/// For example:
3084/// \code
3085/// template<typename T, int Size>
3086/// class array {
3087/// T data[Size];
3088/// };
3089/// \endcode
3090///
3091/// For these types, we won't actually know what the array bound is
3092/// until template instantiation occurs, at which point this will
3093/// become either a ConstantArrayType or a VariableArrayType.
3094class DependentSizedArrayType : public ArrayType {
3095 friend class ASTContext; // ASTContext creates these.
3096
3097 const ASTContext &Context;
3098
3099 /// An assignment expression that will instantiate to the
3100 /// size of the array.
3101 ///
3102 /// The expression itself might be null, in which case the array
3103 /// type will have its size deduced from an initializer.
3104 Stmt *SizeExpr;
3105
3106 /// The range spanned by the left and right array brackets.
3107 SourceRange Brackets;
3108
3109 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3110 Expr *e, ArraySizeModifier sm, unsigned tq,
3111 SourceRange brackets);
3112
3113public:
3114 friend class StmtIteratorBase;
3115
3116 Expr *getSizeExpr() const {
3117 // We use C-style casts instead of cast<> here because we do not wish
3118 // to have a dependency of Type.h on Stmt.h/Expr.h.
3119 return (Expr*) SizeExpr;
3120 }
3121
3122 SourceRange getBracketsRange() const { return Brackets; }
3123 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3124 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3125
3126 bool isSugared() const { return false; }
3127 QualType desugar() const { return QualType(this, 0); }
3128
3129 static bool classof(const Type *T) {
3130 return T->getTypeClass() == DependentSizedArray;
3131 }
3132
3133 void Profile(llvm::FoldingSetNodeID &ID) {
3134 Profile(ID, Context, getElementType(),
3135 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3136 }
3137
3138 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3139 QualType ET, ArraySizeModifier SizeMod,
3140 unsigned TypeQuals, Expr *E);
3141};
3142
3143/// Represents an extended address space qualifier where the input address space
3144/// value is dependent. Non-dependent address spaces are not represented with a
3145/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3146///
3147/// For example:
3148/// \code
3149/// template<typename T, int AddrSpace>
3150/// class AddressSpace {
3151/// typedef T __attribute__((address_space(AddrSpace))) type;
3152/// }
3153/// \endcode
3154class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3155 friend class ASTContext;
3156
3157 const ASTContext &Context;
3158 Expr *AddrSpaceExpr;
3159 QualType PointeeType;
3160 SourceLocation loc;
3161
3162 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3163 QualType can, Expr *AddrSpaceExpr,
3164 SourceLocation loc);
3165
3166public:
3167 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3168 QualType getPointeeType() const { return PointeeType; }
3169 SourceLocation getAttributeLoc() const { return loc; }
3170
3171 bool isSugared() const { return false; }
3172 QualType desugar() const { return QualType(this, 0); }
3173
3174 static bool classof(const Type *T) {
3175 return T->getTypeClass() == DependentAddressSpace;
3176 }
3177
3178 void Profile(llvm::FoldingSetNodeID &ID) {
3179 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3180 }
3181
3182 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3183 QualType PointeeType, Expr *AddrSpaceExpr);
3184};
3185
3186/// Represents an extended vector type where either the type or size is
3187/// dependent.
3188///
3189/// For example:
3190/// \code
3191/// template<typename T, int Size>
3192/// class vector {
3193/// typedef T __attribute__((ext_vector_type(Size))) type;
3194/// }
3195/// \endcode
3196class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3197 friend class ASTContext;
3198
3199 const ASTContext &Context;
3200 Expr *SizeExpr;
3201
3202 /// The element type of the array.
3203 QualType ElementType;
3204
3205 SourceLocation loc;
3206
3207 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3208 QualType can, Expr *SizeExpr, SourceLocation loc);
3209
3210public:
3211 Expr *getSizeExpr() const { return SizeExpr; }
3212 QualType getElementType() const { return ElementType; }
3213 SourceLocation getAttributeLoc() const { return loc; }
3214
3215 bool isSugared() const { return false; }
3216 QualType desugar() const { return QualType(this, 0); }
3217
3218 static bool classof(const Type *T) {
3219 return T->getTypeClass() == DependentSizedExtVector;
3220 }
3221
3222 void Profile(llvm::FoldingSetNodeID &ID) {
3223 Profile(ID, Context, getElementType(), getSizeExpr());
3224 }
3225
3226 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3227 QualType ElementType, Expr *SizeExpr);
3228};
3229
3230
3231/// Represents a GCC generic vector type. This type is created using
3232/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3233/// bytes; or from an Altivec __vector or vector declaration.
3234/// Since the constructor takes the number of vector elements, the
3235/// client is responsible for converting the size into the number of elements.
3236class VectorType : public Type, public llvm::FoldingSetNode {
3237public:
3238 enum VectorKind {
3239 /// not a target-specific vector type
3240 GenericVector,
3241
3242 /// is AltiVec vector
3243 AltiVecVector,
3244
3245 /// is AltiVec 'vector Pixel'
3246 AltiVecPixel,
3247
3248 /// is AltiVec 'vector bool ...'
3249 AltiVecBool,
3250
3251 /// is ARM Neon vector
3252 NeonVector,
3253
3254 /// is ARM Neon polynomial vector
3255 NeonPolyVector,
3256
3257 /// is AArch64 SVE fixed-length data vector
3258 SveFixedLengthDataVector,
3259
3260 /// is AArch64 SVE fixed-length predicate vector
3261 SveFixedLengthPredicateVector
3262 };
3263
3264protected:
3265 friend class ASTContext; // ASTContext creates these.
3266
3267 /// The element type of the vector.
3268 QualType ElementType;
3269
3270 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3271 VectorKind vecKind);
3272
3273 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3274 QualType canonType, VectorKind vecKind);
3275
3276public:
3277 QualType getElementType() const { return ElementType; }
3278 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3279
3280 bool isSugared() const { return false; }
3281 QualType desugar() const { return QualType(this, 0); }
3282
3283 VectorKind getVectorKind() const {
3284 return VectorKind(VectorTypeBits.VecKind);
3285 }
3286
3287 void Profile(llvm::FoldingSetNodeID &ID) {
3288 Profile(ID, getElementType(), getNumElements(),
3289 getTypeClass(), getVectorKind());
3290 }
3291
3292 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3293 unsigned NumElements, TypeClass TypeClass,
3294 VectorKind VecKind) {
3295 ID.AddPointer(ElementType.getAsOpaquePtr());
3296 ID.AddInteger(NumElements);
3297 ID.AddInteger(TypeClass);
3298 ID.AddInteger(VecKind);
3299 }
3300
3301 static bool classof(const Type *T) {
3302 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3303 }
3304};
3305
3306/// Represents a vector type where either the type or size is dependent.
3307////
3308/// For example:
3309/// \code
3310/// template<typename T, int Size>
3311/// class vector {
3312/// typedef T __attribute__((vector_size(Size))) type;
3313/// }
3314/// \endcode
3315class DependentVectorType : public Type, public llvm::FoldingSetNode {
3316 friend class ASTContext;
3317
3318 const ASTContext &Context;
3319 QualType ElementType;
3320 Expr *SizeExpr;
3321 SourceLocation Loc;
3322
3323 DependentVectorType(const ASTContext &Context, QualType ElementType,
3324 QualType CanonType, Expr *SizeExpr,
3325 SourceLocation Loc, VectorType::VectorKind vecKind);
3326
3327public:
3328 Expr *getSizeExpr() const { return SizeExpr; }
3329 QualType getElementType() const { return ElementType; }
3330 SourceLocation getAttributeLoc() const { return Loc; }
3331 VectorType::VectorKind getVectorKind() const {
3332 return VectorType::VectorKind(VectorTypeBits.VecKind);
3333 }
3334
3335 bool isSugared() const { return false; }
3336 QualType desugar() const { return QualType(this, 0); }
3337
3338 static bool classof(const Type *T) {
3339 return T->getTypeClass() == DependentVector;
3340 }
3341
3342 void Profile(llvm::FoldingSetNodeID &ID) {
3343 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3344 }
3345
3346 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3347 QualType ElementType, const Expr *SizeExpr,
3348 VectorType::VectorKind VecKind);
3349};
3350
3351/// ExtVectorType - Extended vector type. This type is created using
3352/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3353/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3354/// class enables syntactic extensions, like Vector Components for accessing
3355/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3356/// Shading Language).
3357class ExtVectorType : public VectorType {
3358 friend class ASTContext; // ASTContext creates these.
3359
3360 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3361 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3362
3363public:
3364 static int getPointAccessorIdx(char c) {
3365 switch (c) {
3366 default: return -1;
3367 case 'x': case 'r': return 0;
3368 case 'y': case 'g': return 1;
3369 case 'z': case 'b': return 2;
3370 case 'w': case 'a': return 3;
3371 }
3372 }
3373
3374 static int getNumericAccessorIdx(char c) {
3375 switch (c) {
3376 default: return -1;
3377 case '0': return 0;
3378 case '1': return 1;
3379 case '2': return 2;
3380 case '3': return 3;
3381 case '4': return 4;
3382 case '5': return 5;
3383 case '6': return 6;
3384 case '7': return 7;
3385 case '8': return 8;
3386 case '9': return 9;
3387 case 'A':
3388 case 'a': return 10;
3389 case 'B':
3390 case 'b': return 11;
3391 case 'C':
3392 case 'c': return 12;
3393 case 'D':
3394 case 'd': return 13;
3395 case 'E':
3396 case 'e': return 14;
3397 case 'F':
3398 case 'f': return 15;
3399 }
3400 }
3401
3402 static int getAccessorIdx(char c, bool isNumericAccessor) {
3403 if (isNumericAccessor)
3404 return getNumericAccessorIdx(c);
3405 else
3406 return getPointAccessorIdx(c);
3407 }
3408
3409 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3410 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3411 return unsigned(idx-1) < getNumElements();
3412 return false;
3413 }
3414
3415 bool isSugared() const { return false; }
3416 QualType desugar() const { return QualType(this, 0); }
3417
3418 static bool classof(const Type *T) {
3419 return T->getTypeClass() == ExtVector;
3420 }
3421};
3422
3423/// Represents a matrix type, as defined in the Matrix Types clang extensions.
3424/// __attribute__((matrix_type(rows, columns))), where "rows" specifies
3425/// number of rows and "columns" specifies the number of columns.
3426class MatrixType : public Type, public llvm::FoldingSetNode {
3427protected:
3428 friend class ASTContext;
3429
3430 /// The element type of the matrix.
3431 QualType ElementType;
3432
3433 MatrixType(QualType ElementTy, QualType CanonElementTy);
3434
3435 MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy,
3436 const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr);
3437
3438public:
3439 /// Returns type of the elements being stored in the matrix
3440 QualType getElementType() const { return ElementType; }
3441
3442 /// Valid elements types are the following:
3443 /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types
3444 /// and _Bool
3445 /// * the standard floating types float or double
3446 /// * a half-precision floating point type, if one is supported on the target
3447 static bool isValidElementType(QualType T) {
3448 return T->isDependentType() ||
3449 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
3450 }
3451
3452 bool isSugared() const { return false; }
3453 QualType desugar() const { return QualType(this, 0); }
3454
3455 static bool classof(const Type *T) {
3456 return T->getTypeClass() == ConstantMatrix ||
3457 T->getTypeClass() == DependentSizedMatrix;
3458 }
3459};
3460
3461/// Represents a concrete matrix type with constant number of rows and columns
3462class ConstantMatrixType final : public MatrixType {
3463protected:
3464 friend class ASTContext;
3465
3466 /// Number of rows and columns.
3467 unsigned NumRows;
3468 unsigned NumColumns;
3469
3470 static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
3471
3472 ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
3473 unsigned NColumns, QualType CanonElementType);
3474
3475 ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows,
3476 unsigned NColumns, QualType CanonElementType);
3477
3478public:
3479 /// Returns the number of rows in the matrix.
3480 unsigned getNumRows() const { return NumRows; }
3481
3482 /// Returns the number of columns in the matrix.
3483 unsigned getNumColumns() const { return NumColumns; }
3484
3485 /// Returns the number of elements required to embed the matrix into a vector.
3486 unsigned getNumElementsFlattened() const {
3487 return getNumRows() * getNumColumns();
3488 }
3489
3490 /// Returns true if \p NumElements is a valid matrix dimension.
3491 static constexpr bool isDimensionValid(size_t NumElements) {
3492 return NumElements > 0 && NumElements <= MaxElementsPerDimension;
3493 }
3494
3495 /// Returns the maximum number of elements per dimension.
3496 static constexpr unsigned getMaxElementsPerDimension() {
3497 return MaxElementsPerDimension;
3498 }
3499
3500 void Profile(llvm::FoldingSetNodeID &ID) {
3501 Profile(ID, getElementType(), getNumRows(), getNumColumns(),
3502 getTypeClass());
3503 }
3504
3505 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3506 unsigned NumRows, unsigned NumColumns,
3507 TypeClass TypeClass) {
3508 ID.AddPointer(ElementType.getAsOpaquePtr());
3509 ID.AddInteger(NumRows);
3510 ID.AddInteger(NumColumns);
3511 ID.AddInteger(TypeClass);
3512 }
3513
3514 static bool classof(const Type *T) {
3515 return T->getTypeClass() == ConstantMatrix;
3516 }
3517};
3518
3519/// Represents a matrix type where the type and the number of rows and columns
3520/// is dependent on a template.
3521class DependentSizedMatrixType final : public MatrixType {
3522 friend class ASTContext;
3523
3524 const ASTContext &Context;
3525 Expr *RowExpr;
3526 Expr *ColumnExpr;
3527
3528 SourceLocation loc;
3529
3530 DependentSizedMatrixType(const ASTContext &Context, QualType ElementType,
3531 QualType CanonicalType, Expr *RowExpr,
3532 Expr *ColumnExpr, SourceLocation loc);
3533
3534public:
3535 Expr *getRowExpr() const { return RowExpr; }
3536 Expr *getColumnExpr() const { return ColumnExpr; }
3537 SourceLocation getAttributeLoc() const { return loc; }
3538
3539 static bool classof(const Type *T) {
3540 return T->getTypeClass() == DependentSizedMatrix;
3541 }
3542
3543 void Profile(llvm::FoldingSetNodeID &ID) {
3544 Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr());
3545 }
3546
3547 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3548 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr);
3549};
3550
3551/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3552/// class of FunctionNoProtoType and FunctionProtoType.
3553class FunctionType : public Type {
3554 // The type returned by the function.
3555 QualType ResultType;
3556
3557public:
3558 /// Interesting information about a specific parameter that can't simply
3559 /// be reflected in parameter's type. This is only used by FunctionProtoType
3560 /// but is in FunctionType to make this class available during the
3561 /// specification of the bases of FunctionProtoType.
3562 ///
3563 /// It makes sense to model language features this way when there's some
3564 /// sort of parameter-specific override (such as an attribute) that
3565 /// affects how the function is called. For example, the ARC ns_consumed
3566 /// attribute changes whether a parameter is passed at +0 (the default)
3567 /// or +1 (ns_consumed). This must be reflected in the function type,
3568 /// but isn't really a change to the parameter type.
3569 ///
3570 /// One serious disadvantage of modelling language features this way is
3571 /// that they generally do not work with language features that attempt
3572 /// to destructure types. For example, template argument deduction will
3573 /// not be able to match a parameter declared as
3574 /// T (*)(U)
3575 /// against an argument of type
3576 /// void (*)(__attribute__((ns_consumed)) id)
3577 /// because the substitution of T=void, U=id into the former will
3578 /// not produce the latter.
3579 class ExtParameterInfo {
3580 enum {
3581 ABIMask = 0x0F,
3582 IsConsumed = 0x10,
3583 HasPassObjSize = 0x20,
3584 IsNoEscape = 0x40,
3585 };
3586 unsigned char Data = 0;
3587
3588 public:
3589 ExtParameterInfo() = default;
3590
3591 /// Return the ABI treatment of this parameter.
3592 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3593 ExtParameterInfo withABI(ParameterABI kind) const {
3594 ExtParameterInfo copy = *this;
3595 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3596 return copy;
3597 }
3598
3599 /// Is this parameter considered "consumed" by Objective-C ARC?
3600 /// Consumed parameters must have retainable object type.
3601 bool isConsumed() const { return (Data & IsConsumed); }
3602 ExtParameterInfo withIsConsumed(bool consumed) const {
3603 ExtParameterInfo copy = *this;
3604 if (consumed)
3605 copy.Data |= IsConsumed;
3606 else
3607 copy.Data &= ~IsConsumed;
3608 return copy;
3609 }
3610
3611 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3612 ExtParameterInfo withHasPassObjectSize() const {
3613 ExtParameterInfo Copy = *this;
3614 Copy.Data |= HasPassObjSize;
3615 return Copy;
3616 }
3617
3618 bool isNoEscape() const { return Data & IsNoEscape; }
3619 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3620 ExtParameterInfo Copy = *this;
3621 if (NoEscape)
3622 Copy.Data |= IsNoEscape;
3623 else
3624 Copy.Data &= ~IsNoEscape;
3625 return Copy;
3626 }
3627
3628 unsigned char getOpaqueValue() const { return Data; }
3629 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3630 ExtParameterInfo result;
3631 result.Data = data;
3632 return result;
3633 }
3634
3635 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3636 return lhs.Data == rhs.Data;
3637 }
3638
3639 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3640 return lhs.Data != rhs.Data;
3641 }
3642 };
3643
3644 /// A class which abstracts out some details necessary for
3645 /// making a call.
3646 ///
3647 /// It is not actually used directly for storing this information in
3648 /// a FunctionType, although FunctionType does currently use the
3649 /// same bit-pattern.
3650 ///
3651 // If you add a field (say Foo), other than the obvious places (both,
3652 // constructors, compile failures), what you need to update is
3653 // * Operator==
3654 // * getFoo
3655 // * withFoo
3656 // * functionType. Add Foo, getFoo.
3657 // * ASTContext::getFooType
3658 // * ASTContext::mergeFunctionTypes
3659 // * FunctionNoProtoType::Profile
3660 // * FunctionProtoType::Profile
3661 // * TypePrinter::PrintFunctionProto
3662 // * AST read and write
3663 // * Codegen
3664 class ExtInfo {
3665 friend class FunctionType;
3666
3667 // Feel free to rearrange or add bits, but if you go over 16, you'll need to
3668 // adjust the Bits field below, and if you add bits, you'll need to adjust
3669 // Type::FunctionTypeBitfields::ExtInfo as well.
3670
3671 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall|
3672 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 |
3673 //
3674 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3675 enum { CallConvMask = 0x1F };
3676 enum { NoReturnMask = 0x20 };
3677 enum { ProducesResultMask = 0x40 };
3678 enum { NoCallerSavedRegsMask = 0x80 };
3679 enum {
3680 RegParmMask = 0x700,
3681 RegParmOffset = 8
3682 };
3683 enum { NoCfCheckMask = 0x800 };
3684 enum { CmseNSCallMask = 0x1000 };
3685 uint16_t Bits = CC_C;
3686
3687 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3688
3689 public:
3690 // Constructor with no defaults. Use this when you know that you
3691 // have all the elements (when reading an AST file for example).
3692 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3693 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck,
3694 bool cmseNSCall) {
3695 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(static_cast <bool> ((!hasRegParm || regParm < 7) &&
"Invalid regparm value") ? void (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "clang/include/clang/AST/Type.h", 3695, __extension__ __PRETTY_FUNCTION__
))
;
3696 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3697 (producesResult ? ProducesResultMask : 0) |
3698 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3699 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3700 (NoCfCheck ? NoCfCheckMask : 0) |
3701 (cmseNSCall ? CmseNSCallMask : 0);
3702 }
3703
3704 // Constructor with all defaults. Use when for example creating a
3705 // function known to use defaults.
3706 ExtInfo() = default;
3707
3708 // Constructor with just the calling convention, which is an important part
3709 // of the canonical type.
3710 ExtInfo(CallingConv CC) : Bits(CC) {}
3711
3712 bool getNoReturn() const { return Bits & NoReturnMask; }
3713 bool getProducesResult() const { return Bits & ProducesResultMask; }
3714 bool getCmseNSCall() const { return Bits & CmseNSCallMask; }
3715 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3716 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3717 bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; }
3718
3719 unsigned getRegParm() const {
3720 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3721 if (RegParm > 0)
3722 --RegParm;
3723 return RegParm;
3724 }
3725
3726 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3727
3728 bool operator==(ExtInfo Other) const {
3729 return Bits == Other.Bits;
3730 }
3731 bool operator!=(ExtInfo Other) const {
3732 return Bits != Other.Bits;
3733 }
3734
3735 // Note that we don't have setters. That is by design, use
3736 // the following with methods instead of mutating these objects.
3737
3738 ExtInfo withNoReturn(bool noReturn) const {
3739 if (noReturn)
3740 return ExtInfo(Bits | NoReturnMask);
3741 else
3742 return ExtInfo(Bits & ~NoReturnMask);
3743 }
3744
3745 ExtInfo withProducesResult(bool producesResult) const {
3746 if (producesResult)
3747 return ExtInfo(Bits | ProducesResultMask);
3748 else
3749 return ExtInfo(Bits & ~ProducesResultMask);
3750 }
3751
3752 ExtInfo withCmseNSCall(bool cmseNSCall) const {
3753 if (cmseNSCall)
3754 return ExtInfo(Bits | CmseNSCallMask);
3755 else
3756 return ExtInfo(Bits & ~CmseNSCallMask);
3757 }
3758
3759 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3760 if (noCallerSavedRegs)
3761 return ExtInfo(Bits | NoCallerSavedRegsMask);
3762 else
3763 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3764 }
3765
3766 ExtInfo withNoCfCheck(bool noCfCheck) const {
3767 if (noCfCheck)
3768 return ExtInfo(Bits | NoCfCheckMask);
3769 else
3770 return ExtInfo(Bits & ~NoCfCheckMask);
3771 }
3772
3773 ExtInfo withRegParm(unsigned RegParm) const {
3774 assert(RegParm < 7 && "Invalid regparm value")(static_cast <bool> (RegParm < 7 && "Invalid regparm value"
) ? void (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "clang/include/clang/AST/Type.h", 3774, __extension__ __PRETTY_FUNCTION__
))
;
3775 return ExtInfo((Bits & ~RegParmMask) |
3776 ((RegParm + 1) << RegParmOffset));
3777 }
3778
3779 ExtInfo withCallingConv(CallingConv cc) const {
3780 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3781 }
3782
3783 void Profile(llvm::FoldingSetNodeID &ID) const {
3784 ID.AddInteger(Bits);
3785 }
3786 };
3787
3788 /// A simple holder for a QualType representing a type in an
3789 /// exception specification. Unfortunately needed by FunctionProtoType
3790 /// because TrailingObjects cannot handle repeated types.
3791 struct ExceptionType { QualType Type; };
3792
3793 /// A simple holder for various uncommon bits which do not fit in
3794 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3795 /// alignment of subsequent objects in TrailingObjects. You must update
3796 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3797 struct alignas(void *) FunctionTypeExtraBitfields {
3798 /// The number of types in the exception specification.
3799 /// A whole unsigned is not needed here and according to
3800 /// [implimits] 8 bits would be enough here.
3801 unsigned NumExceptionType;
3802 };
3803
3804protected:
3805 FunctionType(TypeClass tc, QualType res, QualType Canonical,
3806 TypeDependence Dependence, ExtInfo Info)
3807 : Type(tc, Canonical, Dependence), ResultType(res) {
3808 FunctionTypeBits.ExtInfo = Info.Bits;
3809 }
3810
3811 Qualifiers getFastTypeQuals() const {
3812 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3813 }
3814
3815public:
3816 QualType getReturnType() const { return ResultType; }
3817
3818 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3819 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3820
3821 /// Determine whether this function type includes the GNU noreturn
3822 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3823 /// type.
3824 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3825
3826 bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); }
3827 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3828 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3829
3830 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3831 "Const, volatile and restrict are assumed to be a subset of "
3832 "the fast qualifiers.");
3833
3834 bool isConst() const { return getFastTypeQuals().hasConst(); }
3835 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3836 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3837
3838 /// Determine the type of an expression that calls a function of
3839 /// this type.
3840 QualType getCallResultType(const ASTContext &Context) const {
3841 return getReturnType().getNonLValueExprType(Context);
3842 }
3843
3844 static StringRef getNameForCallConv(CallingConv CC);
3845
3846 static bool classof(const Type *T) {
3847 return T->getTypeClass() == FunctionNoProto ||
3848 T->getTypeClass() == FunctionProto;
3849 }
3850};
3851
3852/// Represents a K&R-style 'int foo()' function, which has
3853/// no information available about its arguments.
3854class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3855 friend class ASTContext; // ASTContext creates these.
3856
3857 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3858 : FunctionType(FunctionNoProto, Result, Canonical,
3859 Result->getDependence() &
3860 ~(TypeDependence::DependentInstantiation |
3861 TypeDependence::UnexpandedPack),
3862 Info) {}
3863
3864public:
3865 // No additional state past what FunctionType provides.
3866
3867 bool isSugared() const { return false; }
3868 QualType desugar() const { return QualType(this, 0); }
3869
3870 void Profile(llvm::FoldingSetNodeID &ID) {
3871 Profile(ID, getReturnType(), getExtInfo());
3872 }
3873
3874 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3875 ExtInfo Info) {
3876 Info.Profile(ID);
3877 ID.AddPointer(ResultType.getAsOpaquePtr());
3878 }
3879
3880 static bool classof(const Type *T) {
3881 return T->getTypeClass() == FunctionNoProto;
3882 }
3883};
3884
3885/// Represents a prototype with parameter type info, e.g.
3886/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3887/// parameters, not as having a single void parameter. Such a type can have
3888/// an exception specification, but this specification is not part of the
3889/// canonical type. FunctionProtoType has several trailing objects, some of
3890/// which optional. For more information about the trailing objects see
3891/// the first comment inside FunctionProtoType.
3892class FunctionProtoType final
3893 : public FunctionType,
3894 public llvm::FoldingSetNode,
3895 private llvm::TrailingObjects<
3896 FunctionProtoType, QualType, SourceLocation,
3897 FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType,
3898 Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> {
3899 friend class ASTContext; // ASTContext creates these.
3900 friend TrailingObjects;
3901
3902 // FunctionProtoType is followed by several trailing objects, some of
3903 // which optional. They are in order:
3904 //
3905 // * An array of getNumParams() QualType holding the parameter types.
3906 // Always present. Note that for the vast majority of FunctionProtoType,
3907 // these will be the only trailing objects.
3908 //
3909 // * Optionally if the function is variadic, the SourceLocation of the
3910 // ellipsis.
3911 //
3912 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3913 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3914 // a single FunctionTypeExtraBitfields. Present if and only if
3915 // hasExtraBitfields() is true.
3916 //
3917 // * Optionally exactly one of:
3918 // * an array of getNumExceptions() ExceptionType,
3919 // * a single Expr *,
3920 // * a pair of FunctionDecl *,
3921 // * a single FunctionDecl *
3922 // used to store information about the various types of exception
3923 // specification. See getExceptionSpecSize for the details.
3924 //
3925 // * Optionally an array of getNumParams() ExtParameterInfo holding
3926 // an ExtParameterInfo for each of the parameters. Present if and
3927 // only if hasExtParameterInfos() is true.
3928 //
3929 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3930 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3931 // if hasExtQualifiers() is true.
3932 //
3933 // The optional FunctionTypeExtraBitfields has to be before the data
3934 // related to the exception specification since it contains the number
3935 // of exception types.
3936 //
3937 // We put the ExtParameterInfos last. If all were equal, it would make
3938 // more sense to put these before the exception specification, because
3939 // it's much easier to skip past them compared to the elaborate switch
3940 // required to skip the exception specification. However, all is not
3941 // equal; ExtParameterInfos are used to model very uncommon features,
3942 // and it's better not to burden the more common paths.
3943
3944public:
3945 /// Holds information about the various types of exception specification.
3946 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3947 /// used to group together the various bits of information about the
3948 /// exception specification.
3949 struct ExceptionSpecInfo {
3950 /// The kind of exception specification this is.
3951 ExceptionSpecificationType Type = EST_None;
3952
3953 /// Explicitly-specified list of exception types.
3954 ArrayRef<QualType> Exceptions;
3955
3956 /// Noexcept expression, if this is a computed noexcept specification.
3957 Expr *NoexceptExpr = nullptr;
3958
3959 /// The function whose exception specification this is, for
3960 /// EST_Unevaluated and EST_Uninstantiated.
3961 FunctionDecl *SourceDecl = nullptr;
3962
3963 /// The function template whose exception specification this is instantiated
3964 /// from, for EST_Uninstantiated.
3965 FunctionDecl *SourceTemplate = nullptr;
3966
3967 ExceptionSpecInfo() = default;
3968
3969 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3970 };
3971
3972 /// Extra information about a function prototype. ExtProtoInfo is not
3973 /// stored as such in FunctionProtoType but is used to group together
3974 /// the various bits of extra information about a function prototype.
3975 struct ExtProtoInfo {
3976 FunctionType::ExtInfo ExtInfo;
3977 bool Variadic : 1;
3978 bool HasTrailingReturn : 1;
3979 Qualifiers TypeQuals;
3980 RefQualifierKind RefQualifier = RQ_None;
3981 ExceptionSpecInfo ExceptionSpec;
3982 const ExtParameterInfo *ExtParameterInfos = nullptr;
3983 SourceLocation EllipsisLoc;
3984
3985 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3986
3987 ExtProtoInfo(CallingConv CC)
3988 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3989
3990 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3991 ExtProtoInfo Result(*this);
3992 Result.ExceptionSpec = ESI;
3993 return Result;
3994 }
3995 };
3996
3997private:
3998 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3999 return getNumParams();
4000 }
4001
4002 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
4003 return isVariadic();
4004 }
4005
4006 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
4007 return hasExtraBitfields();
4008 }
4009
4010 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
4011 return getExceptionSpecSize().NumExceptionType;
4012 }
4013
4014 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
4015 return getExceptionSpecSize().NumExprPtr;
4016 }
4017
4018 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
4019 return getExceptionSpecSize().NumFunctionDeclPtr;
4020 }
4021
4022 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
4023 return hasExtParameterInfos() ? getNumParams() : 0;
4024 }
4025
4026 /// Determine whether there are any argument types that
4027 /// contain an unexpanded parameter pack.
4028 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
4029 unsigned numArgs) {
4030 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
4031 if (ArgArray[Idx]->containsUnexpandedParameterPack())
4032 return true;
4033
4034 return false;
4035 }
4036
4037 FunctionProtoType(QualType result, ArrayRef<QualType> params,
4038 QualType canonical, const ExtProtoInfo &epi);
4039
4040 /// This struct is returned by getExceptionSpecSize and is used to
4041 /// translate an ExceptionSpecificationType to the number and kind
4042 /// of trailing objects related to the exception specification.
4043 struct ExceptionSpecSizeHolder {
4044 unsigned NumExceptionType;
4045 unsigned NumExprPtr;
4046 unsigned NumFunctionDeclPtr;
4047 };
4048
4049 /// Return the number and kind of trailing objects
4050 /// related to the exception specification.
4051 static ExceptionSpecSizeHolder
4052 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
4053 switch (EST) {
4054 case EST_None:
4055 case EST_DynamicNone:
4056 case EST_MSAny:
4057 case EST_BasicNoexcept:
4058 case EST_Unparsed:
4059 case EST_NoThrow:
4060 return {0, 0, 0};
4061
4062 case EST_Dynamic:
4063 return {NumExceptions, 0, 0};
4064
4065 case EST_DependentNoexcept:
4066 case EST_NoexceptFalse:
4067 case EST_NoexceptTrue:
4068 return {0, 1, 0};
4069
4070 case EST_Uninstantiated:
4071 return {0, 0, 2};
4072
4073 case EST_Unevaluated:
4074 return {0, 0, 1};
4075 }
4076 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "clang/include/clang/AST/Type.h", 4076)
;
4077 }
4078
4079 /// Return the number and kind of trailing objects
4080 /// related to the exception specification.
4081 ExceptionSpecSizeHolder getExceptionSpecSize() const {
4082 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
4083 }
4084
4085 /// Whether the trailing FunctionTypeExtraBitfields is present.
4086 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
4087 // If the exception spec type is EST_Dynamic then we have > 0 exception
4088 // types and the exact number is stored in FunctionTypeExtraBitfields.
4089 return EST == EST_Dynamic;
4090 }
4091
4092 /// Whether the trailing FunctionTypeExtraBitfields is present.
4093 bool hasExtraBitfields() const {
4094 return hasExtraBitfields(getExceptionSpecType());
4095 }
4096
4097 bool hasExtQualifiers() const {
4098 return FunctionTypeBits.HasExtQuals;
4099 }
4100
4101public:
4102 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
4103
4104 QualType getParamType(unsigned i) const {
4105 assert(i < getNumParams() && "invalid parameter index")(static_cast <bool> (i < getNumParams() && "invalid parameter index"
) ? void (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "clang/include/clang/AST/Type.h", 4105, __extension__ __PRETTY_FUNCTION__
))
;
4106 return param_type_begin()[i];
4107 }
4108
4109 ArrayRef<QualType> getParamTypes() const {
4110 return llvm::makeArrayRef(param_type_begin(), param_type_end());
4111 }
4112
4113 ExtProtoInfo getExtProtoInfo() const {
4114 ExtProtoInfo EPI;
4115 EPI.ExtInfo = getExtInfo();
4116 EPI.Variadic = isVariadic();
4117 EPI.EllipsisLoc = getEllipsisLoc();
4118 EPI.HasTrailingReturn = hasTrailingReturn();
4119 EPI.ExceptionSpec = getExceptionSpecInfo();
4120 EPI.TypeQuals = getMethodQuals();
4121 EPI.RefQualifier = getRefQualifier();
4122 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
4123 return EPI;
4124 }
4125
4126 /// Get the kind of exception specification on this function.
4127 ExceptionSpecificationType getExceptionSpecType() const {
4128 return static_cast<ExceptionSpecificationType>(
4129 FunctionTypeBits.ExceptionSpecType);
4130 }
4131
4132 /// Return whether this function has any kind of exception spec.
4133 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
4134
4135 /// Return whether this function has a dynamic (throw) exception spec.
4136 bool hasDynamicExceptionSpec() const {
4137 return isDynamicExceptionSpec(getExceptionSpecType());
4138 }
4139
4140 /// Return whether this function has a noexcept exception spec.
4141 bool hasNoexceptExceptionSpec() const {
4142 return isNoexceptExceptionSpec(getExceptionSpecType());
4143 }
4144
4145 /// Return whether this function has a dependent exception spec.
4146 bool hasDependentExceptionSpec() const;
4147
4148 /// Return whether this function has an instantiation-dependent exception
4149 /// spec.
4150 bool hasInstantiationDependentExceptionSpec() const;
4151
4152 /// Return all the available information about this type's exception spec.
4153 ExceptionSpecInfo getExceptionSpecInfo() const {
4154 ExceptionSpecInfo Result;
4155 Result.Type = getExceptionSpecType();
4156 if (Result.Type == EST_Dynamic) {
4157 Result.Exceptions = exceptions();
4158 } else if (isComputedNoexcept(Result.Type)) {
4159 Result.NoexceptExpr = getNoexceptExpr();
4160 } else if (Result.Type == EST_Uninstantiated) {
4161 Result.SourceDecl = getExceptionSpecDecl();
4162 Result.SourceTemplate = getExceptionSpecTemplate();
4163 } else if (Result.Type == EST_Unevaluated) {
4164 Result.SourceDecl = getExceptionSpecDecl();
4165 }
4166 return Result;
4167 }
4168
4169 /// Return the number of types in the exception specification.
4170 unsigned getNumExceptions() const {
4171 return getExceptionSpecType() == EST_Dynamic
4172 ? getTrailingObjects<FunctionTypeExtraBitfields>()
4173 ->NumExceptionType
4174 : 0;
4175 }
4176
4177 /// Return the ith exception type, where 0 <= i < getNumExceptions().
4178 QualType getExceptionType(unsigned i) const {
4179 assert(i < getNumExceptions() && "Invalid exception number!")(static_cast <bool> (i < getNumExceptions() &&
"Invalid exception number!") ? void (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "clang/include/clang/AST/Type.h", 4179, __extension__ __PRETTY_FUNCTION__
))
;
4180 return exception_begin()[i];
4181 }
4182
4183 /// Return the expression inside noexcept(expression), or a null pointer
4184 /// if there is none (because the exception spec is not of this form).
4185 Expr *getNoexceptExpr() const {
4186 if (!isComputedNoexcept(getExceptionSpecType()))
4187 return nullptr;
4188 return *getTrailingObjects<Expr *>();
4189 }
4190
4191 /// If this function type has an exception specification which hasn't
4192 /// been determined yet (either because it has not been evaluated or because
4193 /// it has not been instantiated), this is the function whose exception
4194 /// specification is represented by this type.
4195 FunctionDecl *getExceptionSpecDecl() const {
4196 if (getExceptionSpecType() != EST_Uninstantiated &&
4197 getExceptionSpecType() != EST_Unevaluated)
4198 return nullptr;
4199 return getTrailingObjects<FunctionDecl *>()[0];
4200 }
4201
4202 /// If this function type has an uninstantiated exception
4203 /// specification, this is the function whose exception specification
4204 /// should be instantiated to find the exception specification for
4205 /// this type.
4206 FunctionDecl *getExceptionSpecTemplate() const {
4207 if (getExceptionSpecType() != EST_Uninstantiated)
4208 return nullptr;
4209 return getTrailingObjects<FunctionDecl *>()[1];
4210 }
4211
4212 /// Determine whether this function type has a non-throwing exception
4213 /// specification.
4214 CanThrowResult canThrow() const;
4215
4216 /// Determine whether this function type has a non-throwing exception
4217 /// specification. If this depends on template arguments, returns
4218 /// \c ResultIfDependent.
4219 bool isNothrow(bool ResultIfDependent = false) const {
4220 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4221 }
4222
4223 /// Whether this function prototype is variadic.
4224 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4225
4226 SourceLocation getEllipsisLoc() const {
4227 return isVariadic() ? *getTrailingObjects<SourceLocation>()
4228 : SourceLocation();
4229 }
4230
4231 /// Determines whether this function prototype contains a
4232 /// parameter pack at the end.
4233 ///
4234 /// A function template whose last parameter is a parameter pack can be
4235 /// called with an arbitrary number of arguments, much like a variadic
4236 /// function.
4237 bool isTemplateVariadic() const;
4238
4239 /// Whether this function prototype has a trailing return type.
4240 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4241
4242 Qualifiers getMethodQuals() const {
4243 if (hasExtQualifiers())
4244 return *getTrailingObjects<Qualifiers>();
4245 else
4246 return getFastTypeQuals();
4247 }
4248
4249 /// Retrieve the ref-qualifier associated with this function type.
4250 RefQualifierKind getRefQualifier() const {
4251 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4252 }
4253
4254 using param_type_iterator = const QualType *;
4255 using param_type_range = llvm::iterator_range<param_type_iterator>;
4256
4257 param_type_range param_types() const {
4258 return param_type_range(param_type_begin(), param_type_end());
4259 }
4260
4261 param_type_iterator param_type_begin() const {
4262 return getTrailingObjects<QualType>();
4263 }
4264
4265 param_type_iterator param_type_end() const {
4266 return param_type_begin() + getNumParams();
4267 }
4268
4269 using exception_iterator = const QualType *;
4270
4271 ArrayRef<QualType> exceptions() const {
4272 return llvm::makeArrayRef(exception_begin(), exception_end());
4273 }
4274
4275 exception_iterator exception_begin() const {
4276 return reinterpret_cast<exception_iterator>(
4277 getTrailingObjects<ExceptionType>());
4278 }
4279
4280 exception_iterator exception_end() const {
4281 return exception_begin() + getNumExceptions();
4282 }
4283
4284 /// Is there any interesting extra information for any of the parameters
4285 /// of this function type?
4286 bool hasExtParameterInfos() const {
4287 return FunctionTypeBits.HasExtParameterInfos;
4288 }
4289
4290 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4291 assert(hasExtParameterInfos())(static_cast <bool> (hasExtParameterInfos()) ? void (0)
: __assert_fail ("hasExtParameterInfos()", "clang/include/clang/AST/Type.h"
, 4291, __extension__ __PRETTY_FUNCTION__))
;
4292 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4293 getNumParams());
4294 }
4295
4296 /// Return a pointer to the beginning of the array of extra parameter
4297 /// information, if present, or else null if none of the parameters
4298 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4299 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4300 if (!hasExtParameterInfos())
4301 return nullptr;
4302 return getTrailingObjects<ExtParameterInfo>();
4303 }
4304
4305 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4306 assert(I < getNumParams() && "parameter index out of range")(static_cast <bool> (I < getNumParams() && "parameter index out of range"
) ? void (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "clang/include/clang/AST/Type.h", 4306, __extension__ __PRETTY_FUNCTION__
))
;
4307 if (hasExtParameterInfos())
4308 return getTrailingObjects<ExtParameterInfo>()[I];
4309 return ExtParameterInfo();
4310 }
4311
4312 ParameterABI getParameterABI(unsigned I) const {
4313 assert(I < getNumParams() && "parameter index out of range")(static_cast <bool> (I < getNumParams() && "parameter index out of range"
) ? void (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "clang/include/clang/AST/Type.h", 4313, __extension__ __PRETTY_FUNCTION__
))
;
4314 if (hasExtParameterInfos())
4315 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4316 return ParameterABI::Ordinary;
4317 }
4318
4319 bool isParamConsumed(unsigned I) const {
4320 assert(I < getNumParams() && "parameter index out of range")(static_cast <bool> (I < getNumParams() && "parameter index out of range"
) ? void (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "clang/include/clang/AST/Type.h", 4320, __extension__ __PRETTY_FUNCTION__
))
;
4321 if (hasExtParameterInfos())
4322 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4323 return false;
4324 }
4325
4326 bool isSugared() const { return false; }
4327 QualType desugar() const { return QualType(this, 0); }
4328
4329 void printExceptionSpecification(raw_ostream &OS,
4330 const PrintingPolicy &Policy) const;
4331
4332 static bool classof(const Type *T) {
4333 return T->getTypeClass() == FunctionProto;
4334 }
4335
4336 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4337 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4338 param_type_iterator ArgTys, unsigned NumArgs,
4339 const ExtProtoInfo &EPI, const ASTContext &Context,
4340 bool Canonical);
4341};
4342
4343/// Represents the dependent type named by a dependently-scoped
4344/// typename using declaration, e.g.
4345/// using typename Base<T>::foo;
4346///
4347/// Template instantiation turns these into the underlying type.
4348class UnresolvedUsingType : public Type {
4349 friend class ASTContext; // ASTContext creates these.
4350
4351 UnresolvedUsingTypenameDecl *Decl;
4352
4353 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4354 : Type(UnresolvedUsing, QualType(),
4355 TypeDependence::DependentInstantiation),
4356 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {}
4357
4358public:
4359 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4360
4361 bool isSugared() const { return false; }
4362 QualType desugar() const { return QualType(this, 0); }
4363
4364 static bool classof(const Type *T) {
4365 return T->getTypeClass() == UnresolvedUsing;
4366 }
4367
4368 void Profile(llvm::FoldingSetNodeID &ID) {
4369 return Profile(ID, Decl);
4370 }
4371
4372 static void Profile(llvm::FoldingSetNodeID &ID,
4373 UnresolvedUsingTypenameDecl *D) {
4374 ID.AddPointer(D);
4375 }
4376};
4377
4378class UsingType : public Type, public llvm::FoldingSetNode {
4379 UsingShadowDecl *Found;
4380 friend class ASTContext; // ASTContext creates these.
4381
4382 UsingType(const UsingShadowDecl *Found, QualType Underlying, QualType Canon);
4383
4384public:
4385 UsingShadowDecl *getFoundDecl() const { return Found; }
4386 QualType getUnderlyingType() const;
4387
4388 bool isSugared() const { return true; }
4389 QualType desugar() const { return getUnderlyingType(); }
4390
4391 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Found); }
4392 static void Profile(llvm::FoldingSetNodeID &ID,
4393 const UsingShadowDecl *Found) {
4394 ID.AddPointer(Found);
4395 }
4396 static bool classof(const Type *T) { return T->getTypeClass() == Using; }
4397};
4398
4399class TypedefType : public Type {
4400 TypedefNameDecl *Decl;
4401
4402private:
4403 friend class ASTContext; // ASTContext creates these.
4404
4405 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType underlying,
4406 QualType can);
4407
4408public:
4409 TypedefNameDecl *getDecl() const { return Decl; }
4410
4411 bool isSugared() const { return true; }
4412 QualType desugar() const;
4413
4414 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4415};
4416
4417/// Sugar type that represents a type that was qualified by a qualifier written
4418/// as a macro invocation.
4419class MacroQualifiedType : public Type {
4420 friend class ASTContext; // ASTContext creates these.
4421
4422 QualType UnderlyingTy;
4423 const IdentifierInfo *MacroII;
4424
4425 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4426 const IdentifierInfo *MacroII)
4427 : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()),
4428 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4429 assert(isa<AttributedType>(UnderlyingTy) &&(static_cast <bool> (isa<AttributedType>(UnderlyingTy
) && "Expected a macro qualified type to only wrap attributed types."
) ? void (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "clang/include/clang/AST/Type.h", 4430, __extension__ __PRETTY_FUNCTION__
))
4430 "Expected a macro qualified type to only wrap attributed types.")(static_cast <bool> (isa<AttributedType>(UnderlyingTy
) && "Expected a macro qualified type to only wrap attributed types."
) ? void (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "clang/include/clang/AST/Type.h", 4430, __extension__ __PRETTY_FUNCTION__
))
;
4431 }
4432
4433public:
4434 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4435 QualType getUnderlyingType() const { return UnderlyingTy; }
4436
4437 /// Return this attributed type's modified type with no qualifiers attached to
4438 /// it.
4439 QualType getModifiedType() const;
4440
4441 bool isSugared() const { return true; }
4442 QualType desugar() const;
4443
4444 static bool classof(const Type *T) {
4445 return T->getTypeClass() == MacroQualified;
4446 }
4447};
4448
4449/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4450class TypeOfExprType : public Type {
4451 Expr *TOExpr;
4452
4453protected:
4454 friend class ASTContext; // ASTContext creates these.
4455
4456 TypeOfExprType(Expr *E, QualType can = QualType());
4457
4458public:
4459 Expr *getUnderlyingExpr() const { return TOExpr; }
4460
4461 /// Remove a single level of sugar.
4462 QualType desugar() const;
4463
4464 /// Returns whether this type directly provides sugar.
4465 bool isSugared() const;
4466
4467 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4468};
4469
4470/// Internal representation of canonical, dependent
4471/// `typeof(expr)` types.
4472///
4473/// This class is used internally by the ASTContext to manage
4474/// canonical, dependent types, only. Clients will only see instances
4475/// of this class via TypeOfExprType nodes.
4476class DependentTypeOfExprType
4477 : public TypeOfExprType, public llvm::FoldingSetNode {
4478 const ASTContext &Context;
4479
4480public:
4481 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4482 : TypeOfExprType(E), Context(Context) {}
4483
4484 void Profile(llvm::FoldingSetNodeID &ID) {
4485 Profile(ID, Context, getUnderlyingExpr());
4486 }
4487
4488 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4489 Expr *E);
4490};
4491
4492/// Represents `typeof(type)`, a GCC extension.
4493class TypeOfType : public Type {
4494 friend class ASTContext; // ASTContext creates these.
4495
4496 QualType TOType;
4497
4498 TypeOfType(QualType T, QualType can)
4499 : Type(TypeOf, can, T->getDependence()), TOType(T) {
4500 assert(!isa<TypedefType>(can) && "Invalid canonical type")(static_cast <bool> (!isa<TypedefType>(can) &&
"Invalid canonical type") ? void (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "clang/include/clang/AST/Type.h", 4500, __extension__ __PRETTY_FUNCTION__
))
;
4501 }
4502
4503public:
4504 QualType getUnderlyingType() const { return TOType; }
4505
4506 /// Remove a single level of sugar.
4507 QualType desugar() const { return getUnderlyingType(); }
4508
4509 /// Returns whether this type directly provides sugar.
4510 bool isSugared() const { return true; }
4511
4512 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4513};
4514
4515/// Represents the type `decltype(expr)` (C++11).
4516class DecltypeType : public Type {
4517 Expr *E;
4518 QualType UnderlyingType;
4519
4520protected:
4521 friend class ASTContext; // ASTContext creates these.
4522
4523 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4524
4525public:
4526 Expr *getUnderlyingExpr() const { return E; }
4527 QualType getUnderlyingType() const { return UnderlyingType; }
4528
4529 /// Remove a single level of sugar.
4530 QualType desugar() const;
4531
4532 /// Returns whether this type directly provides sugar.
4533 bool isSugared() const;
4534
4535 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4536};
4537
4538/// Internal representation of canonical, dependent
4539/// decltype(expr) types.
4540///
4541/// This class is used internally by the ASTContext to manage
4542/// canonical, dependent types, only. Clients will only see instances
4543/// of this class via DecltypeType nodes.
4544class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4545 const ASTContext &Context;
4546
4547public:
4548 DependentDecltypeType(const ASTContext &Context, Expr *E);
4549
4550 void Profile(llvm::FoldingSetNodeID &ID) {
4551 Profile(ID, Context, getUnderlyingExpr());
4552 }
4553
4554 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4555 Expr *E);
4556};
4557
4558/// A unary type transform, which is a type constructed from another.
4559class UnaryTransformType : public Type {
4560public:
4561 enum UTTKind {
4562 EnumUnderlyingType
4563 };
4564
4565private:
4566 /// The untransformed type.
4567 QualType BaseType;
4568
4569 /// The transformed type if not dependent, otherwise the same as BaseType.
4570 QualType UnderlyingType;
4571
4572 UTTKind UKind;
4573
4574protected:
4575 friend class ASTContext;
4576
4577 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4578 QualType CanonicalTy);
4579
4580public:
4581 bool isSugared() const { return !isDependentType(); }
4582 QualType desugar() const { return UnderlyingType; }
4583
4584 QualType getUnderlyingType() const { return UnderlyingType; }
4585 QualType getBaseType() const { return BaseType; }
4586
4587 UTTKind getUTTKind() const { return UKind; }
4588
4589 static bool classof(const Type *T) {
4590 return T->getTypeClass() == UnaryTransform;
4591 }
4592};
4593
4594/// Internal representation of canonical, dependent
4595/// __underlying_type(type) types.
4596///
4597/// This class is used internally by the ASTContext to manage
4598/// canonical, dependent types, only. Clients will only see instances
4599/// of this class via UnaryTransformType nodes.
4600class DependentUnaryTransformType : public UnaryTransformType,
4601 public llvm::FoldingSetNode {
4602public:
4603 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4604 UTTKind UKind);
4605
4606 void Profile(llvm::FoldingSetNodeID &ID) {
4607 Profile(ID, getBaseType(), getUTTKind());
4608 }
4609
4610 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4611 UTTKind UKind) {
4612 ID.AddPointer(BaseType.getAsOpaquePtr());
4613 ID.AddInteger((unsigned)UKind);
4614 }
4615};
4616
4617class TagType : public Type {
4618 friend class ASTReader;
4619 template <class T> friend class serialization::AbstractTypeReader;
4620
4621 /// Stores the TagDecl associated with this type. The decl may point to any
4622 /// TagDecl that declares the entity.
4623 TagDecl *decl;
4624
4625protected:
4626 TagType(TypeClass TC, const TagDecl *D, QualType can);
4627
4628public:
4629 TagDecl *getDecl() const;
4630
4631 /// Determines whether this type is in the process of being defined.
4632 bool isBeingDefined() const;
4633
4634 static bool classof(const Type *T) {
4635 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4636 }
4637};
4638
4639/// A helper class that allows the use of isa/cast/dyncast
4640/// to detect TagType objects of structs/unions/classes.
4641class RecordType : public TagType {
4642protected:
4643 friend class ASTContext; // ASTContext creates these.
4644
4645 explicit RecordType(const RecordDecl *D)
4646 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4647 explicit RecordType(TypeClass TC, RecordDecl *D)
4648 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4649
4650public:
4651 RecordDecl *getDecl() const {
4652 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4653 }
4654
4655 /// Recursively check all fields in the record for const-ness. If any field
4656 /// is declared const, return true. Otherwise, return false.
4657 bool hasConstFields() const;
4658
4659 bool isSugared() const { return false; }
4660 QualType desugar() const { return QualType(this, 0); }
4661
4662 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4663};
4664
4665/// A helper class that allows the use of isa/cast/dyncast
4666/// to detect TagType objects of enums.
4667class EnumType : public TagType {
4668 friend class ASTContext; // ASTContext creates these.
4669
4670 explicit EnumType(const EnumDecl *D)
4671 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4672
4673public:
4674 EnumDecl *getDecl() const {
4675 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4676 }
4677
4678 bool isSugared() const { return false; }
4679 QualType desugar() const { return QualType(this, 0); }
4680
4681 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4682};
4683
4684/// An attributed type is a type to which a type attribute has been applied.
4685///
4686/// The "modified type" is the fully-sugared type to which the attributed
4687/// type was applied; generally it is not canonically equivalent to the
4688/// attributed type. The "equivalent type" is the minimally-desugared type
4689/// which the type is canonically equivalent to.
4690///
4691/// For example, in the following attributed type:
4692/// int32_t __attribute__((vector_size(16)))
4693/// - the modified type is the TypedefType for int32_t
4694/// - the equivalent type is VectorType(16, int32_t)
4695/// - the canonical type is VectorType(16, int)
4696class AttributedType : public Type, public llvm::FoldingSetNode {
4697public:
4698 using Kind = attr::Kind;
4699
4700private:
4701 friend class ASTContext; // ASTContext creates these
4702
4703 QualType ModifiedType;
4704 QualType EquivalentType;
4705
4706 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4707 QualType equivalent)
4708 : Type(Attributed, canon, equivalent->getDependence()),
4709 ModifiedType(modified), EquivalentType(equivalent) {
4710 AttributedTypeBits.AttrKind = attrKind;
4711 }
4712
4713public:
4714 Kind getAttrKind() const {
4715 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4716 }
4717
4718 QualType getModifiedType() const { return ModifiedType; }
4719 QualType getEquivalentType() const { return EquivalentType; }
4720
4721 bool isSugared() const { return true; }
4722 QualType desugar() const { return getEquivalentType(); }
4723
4724 /// Does this attribute behave like a type qualifier?
4725 ///
4726 /// A type qualifier adjusts a type to provide specialized rules for
4727 /// a specific object, like the standard const and volatile qualifiers.
4728 /// This includes attributes controlling things like nullability,
4729 /// address spaces, and ARC ownership. The value of the object is still
4730 /// largely described by the modified type.
4731 ///
4732 /// In contrast, many type attributes "rewrite" their modified type to
4733 /// produce a fundamentally different type, not necessarily related in any
4734 /// formalizable way to the original type. For example, calling convention
4735 /// and vector attributes are not simple type qualifiers.
4736 ///
4737 /// Type qualifiers are often, but not always, reflected in the canonical
4738 /// type.
4739 bool isQualifier() const;
4740
4741 bool isMSTypeSpec() const;
4742
4743 bool isCallingConv() const;
4744
4745 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4746
4747 /// Retrieve the attribute kind corresponding to the given
4748 /// nullability kind.
4749 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4750 switch (kind) {
4751 case NullabilityKind::NonNull:
4752 return attr::TypeNonNull;
4753
4754 case NullabilityKind::Nullable:
4755 return attr::TypeNullable;
4756
4757 case NullabilityKind::NullableResult:
4758 return attr::TypeNullableResult;
4759
4760 case NullabilityKind::Unspecified:
4761 return attr::TypeNullUnspecified;
4762 }
4763 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "clang/include/clang/AST/Type.h", 4763)
;
4764 }
4765
4766 /// Strip off the top-level nullability annotation on the given
4767 /// type, if it's there.
4768 ///
4769 /// \param T The type to strip. If the type is exactly an
4770 /// AttributedType specifying nullability (without looking through
4771 /// type sugar), the nullability is returned and this type changed
4772 /// to the underlying modified type.
4773 ///
4774 /// \returns the top-level nullability, if present.
4775 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4776
4777 void Profile(llvm::FoldingSetNodeID &ID) {
4778 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4779 }
4780
4781 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4782 QualType modified, QualType equivalent) {
4783 ID.AddInteger(attrKind);
4784 ID.AddPointer(modified.getAsOpaquePtr());
4785 ID.AddPointer(equivalent.getAsOpaquePtr());
4786 }
4787
4788 static bool classof(const Type *T) {
4789 return T->getTypeClass() == Attributed;
4790 }
4791};
4792
4793class BTFTagAttributedType : public Type, public llvm::FoldingSetNode {
4794private:
4795 friend class ASTContext; // ASTContext creates these
4796
4797 QualType WrappedType;
4798 const BTFTypeTagAttr *BTFAttr;
4799
4800 BTFTagAttributedType(QualType Canon, QualType Wrapped,
4801 const BTFTypeTagAttr *BTFAttr)
4802 : Type(BTFTagAttributed, Canon, Wrapped->getDependence()),
4803 WrappedType(Wrapped), BTFAttr(BTFAttr) {}
4804
4805public:
4806 QualType getWrappedType() const { return WrappedType; }
4807 const BTFTypeTagAttr *getAttr() const { return BTFAttr; }
4808
4809 bool isSugared() const { return true; }
4810 QualType desugar() const { return getWrappedType(); }
4811
4812 void Profile(llvm::FoldingSetNodeID &ID) {
4813 Profile(ID, WrappedType, BTFAttr);
4814 }
4815
4816 static void Profile(llvm::FoldingSetNodeID &ID, QualType Wrapped,
4817 const BTFTypeTagAttr *BTFAttr) {
4818 ID.AddPointer(Wrapped.getAsOpaquePtr());
4819 ID.AddPointer(BTFAttr);
4820 }
4821
4822 static bool classof(const Type *T) {
4823 return T->getTypeClass() == BTFTagAttributed;
4824 }
4825};
4826
4827class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4828 friend class ASTContext; // ASTContext creates these
4829
4830 // Helper data collector for canonical types.
4831 struct CanonicalTTPTInfo {
4832 unsigned Depth : 15;
4833 unsigned ParameterPack : 1;
4834 unsigned Index : 16;
4835 };
4836
4837 union {
4838 // Info for the canonical type.
4839 CanonicalTTPTInfo CanTTPTInfo;
4840
4841 // Info for the non-canonical type.
4842 TemplateTypeParmDecl *TTPDecl;
4843 };
4844
4845 /// Build a non-canonical type.
4846 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4847 : Type(TemplateTypeParm, Canon,
4848 TypeDependence::DependentInstantiation |
4849 (Canon->getDependence() & TypeDependence::UnexpandedPack)),
4850 TTPDecl(TTPDecl) {}
4851
4852 /// Build the canonical type.
4853 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4854 : Type(TemplateTypeParm, QualType(this, 0),
4855 TypeDependence::DependentInstantiation |
4856 (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) {
4857 CanTTPTInfo.Depth = D;
4858 CanTTPTInfo.Index = I;
4859 CanTTPTInfo.ParameterPack = PP;
4860 }
4861
4862 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4863 QualType Can = getCanonicalTypeInternal();
4864 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4865 }
4866
4867public:
4868 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4869 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4870 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4871
4872 TemplateTypeParmDecl *getDecl() const {
4873 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4874 }
4875
4876 IdentifierInfo *getIdentifier() const;
4877
4878 bool isSugared() const { return false; }
4879 QualType desugar() const { return QualType(this, 0); }
4880
4881 void Profile(llvm::FoldingSetNodeID &ID) {
4882 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4883 }
4884
4885 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4886 unsigned Index, bool ParameterPack,
4887 TemplateTypeParmDecl *TTPDecl) {
4888 ID.AddInteger(Depth);
4889 ID.AddInteger(Index);
4890 ID.AddBoolean(ParameterPack);
4891 ID.AddPointer(TTPDecl);
4892 }
4893
4894 static bool classof(const Type *T) {
4895 return T->getTypeClass() == TemplateTypeParm;
4896 }
4897};
4898
4899/// Represents the result of substituting a type for a template
4900/// type parameter.
4901///
4902/// Within an instantiated template, all template type parameters have
4903/// been replaced with these. They are used solely to record that a
4904/// type was originally written as a template type parameter;
4905/// therefore they are never canonical.
4906class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4907 friend class ASTContext;
4908
4909 // The original type parameter.
4910 const TemplateTypeParmType *Replaced;
4911
4912 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4913 : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()),
4914 Replaced(Param) {}
4915
4916public:
4917 /// Gets the template parameter that was substituted for.
4918 const TemplateTypeParmType *getReplacedParameter() const {
4919 return Replaced;
4920 }
4921
4922 /// Gets the type that was substituted for the template
4923 /// parameter.
4924 QualType getReplacementType() const {
4925 return getCanonicalTypeInternal();
4926 }
4927
4928 bool isSugared() const { return true; }
4929 QualType desugar() const { return getReplacementType(); }
4930
4931 void Profile(llvm::FoldingSetNodeID &ID) {
4932 Profile(ID, getReplacedParameter(), getReplacementType());
4933 }
4934
4935 static void Profile(llvm::FoldingSetNodeID &ID,
4936 const TemplateTypeParmType *Replaced,
4937 QualType Replacement) {
4938 ID.AddPointer(Replaced);
4939 ID.AddPointer(Replacement.getAsOpaquePtr());
4940 }
4941
4942 static bool classof(const Type *T) {
4943 return T->getTypeClass() == SubstTemplateTypeParm;
4944 }
4945};
4946
4947/// Represents the result of substituting a set of types for a template
4948/// type parameter pack.
4949///
4950/// When a pack expansion in the source code contains multiple parameter packs
4951/// and those parameter packs correspond to different levels of template
4952/// parameter lists, this type node is used to represent a template type
4953/// parameter pack from an outer level, which has already had its argument pack
4954/// substituted but that still lives within a pack expansion that itself
4955/// could not be instantiated. When actually performing a substitution into
4956/// that pack expansion (e.g., when all template parameters have corresponding
4957/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4958/// at the current pack substitution index.
4959class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4960 friend class ASTContext;
4961
4962 /// The original type parameter.
4963 const TemplateTypeParmType *Replaced;
4964
4965 /// A pointer to the set of template arguments that this
4966 /// parameter pack is instantiated with.
4967 const TemplateArgument *Arguments;
4968
4969 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4970 QualType Canon,
4971 const TemplateArgument &ArgPack);
4972
4973public:
4974 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4975
4976 /// Gets the template parameter that was substituted for.
4977 const TemplateTypeParmType *getReplacedParameter() const {
4978 return Replaced;
4979 }
4980
4981 unsigned getNumArgs() const {
4982 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4983 }
4984
4985 bool isSugared() const { return false; }
4986 QualType desugar() const { return QualType(this, 0); }
4987
4988 TemplateArgument getArgumentPack() const;
4989
4990 void Profile(llvm::FoldingSetNodeID &ID);
4991 static void Profile(llvm::FoldingSetNodeID &ID,
4992 const TemplateTypeParmType *Replaced,
4993 const TemplateArgument &ArgPack);
4994
4995 static bool classof(const Type *T) {
4996 return T->getTypeClass() == SubstTemplateTypeParmPack;
4997 }
4998};
4999
5000/// Common base class for placeholders for types that get replaced by
5001/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
5002/// class template types, and constrained type names.
5003///
5004/// These types are usually a placeholder for a deduced type. However, before
5005/// the initializer is attached, or (usually) if the initializer is
5006/// type-dependent, there is no deduced type and the type is canonical. In
5007/// the latter case, it is also a dependent type.
5008class DeducedType : public Type {
5009 QualType DeducedAsType;
5010
5011protected:
5012 DeducedType(TypeClass TC, QualType DeducedAsType,
5013 TypeDependence ExtraDependence, QualType Canon)
5014 : Type(TC, Canon,
5015 ExtraDependence | (DeducedAsType.isNull()
5016 ? TypeDependence::None
5017 : DeducedAsType->getDependence() &
5018 ~TypeDependence::VariablyModified)),
5019 DeducedAsType(DeducedAsType) {}
5020
5021public:
5022 bool isSugared() const { return !DeducedAsType.isNull(); }
5023 QualType desugar() const {
5024 return isSugared() ? DeducedAsType : QualType(this, 0);
5025 }
5026
5027 /// Get the type deduced for this placeholder type, or null if it
5028 /// has not been deduced.
5029 QualType getDeducedType() const { return DeducedAsType; }
5030 bool isDeduced() const {
5031 return !DeducedAsType.isNull() || isDependentType();
5032 }
5033
5034 static bool classof(const Type *T) {
5035 return T->getTypeClass() == Auto ||
5036 T->getTypeClass() == DeducedTemplateSpecialization;
5037 }
5038};
5039
5040/// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained
5041/// by a type-constraint.
5042class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode {
5043 friend class ASTContext; // ASTContext creates these
5044
5045 ConceptDecl *TypeConstraintConcept;
5046
5047 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
5048 TypeDependence ExtraDependence, QualType Canon, ConceptDecl *CD,
5049 ArrayRef<TemplateArgument> TypeConstraintArgs);
5050
5051 const TemplateArgument *getArgBuffer() const {
5052 return reinterpret_cast<const TemplateArgument*>(this+1);
5053 }
5054
5055 TemplateArgument *getArgBuffer() {
5056 return reinterpret_cast<TemplateArgument*>(this+1);
5057 }
5058
5059public:
5060 /// Retrieve the template arguments.
5061 const TemplateArgument *getArgs() const {
5062 return getArgBuffer();
5063 }
5064
5065 /// Retrieve the number of template arguments.
5066 unsigned getNumArgs() const {
5067 return AutoTypeBits.NumArgs;
5068 }
5069
5070 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5071
5072 ArrayRef<TemplateArgument> getTypeConstraintArguments() const {
5073 return {getArgs(), getNumArgs()};
5074 }
5075
5076 ConceptDecl *getTypeConstraintConcept() const {
5077 return TypeConstraintConcept;
5078 }
5079
5080 bool isConstrained() const {
5081 return TypeConstraintConcept != nullptr;
5082 }
5083
5084 bool isDecltypeAuto() const {
5085 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
5086 }
5087
5088 AutoTypeKeyword getKeyword() const {
5089 return (AutoTypeKeyword)AutoTypeBits.Keyword;
5090 }
5091
5092 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5093 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
5094 getTypeConstraintConcept(), getTypeConstraintArguments());
5095 }
5096
5097 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5098 QualType Deduced, AutoTypeKeyword Keyword,
5099 bool IsDependent, ConceptDecl *CD,
5100 ArrayRef<TemplateArgument> Arguments);
5101
5102 static bool classof(const Type *T) {
5103 return T->getTypeClass() == Auto;
5104 }
5105};
5106
5107/// Represents a C++17 deduced template specialization type.
5108class DeducedTemplateSpecializationType : public DeducedType,
5109 public llvm::FoldingSetNode {
5110 friend class ASTContext; // ASTContext creates these
5111
5112 /// The name of the template whose arguments will be deduced.
5113 TemplateName Template;
5114
5115 DeducedTemplateSpecializationType(TemplateName Template,
5116 QualType DeducedAsType,
5117 bool IsDeducedAsDependent)
5118 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
5119 toTypeDependence(Template.getDependence()) |
5120 (IsDeducedAsDependent
5121 ? TypeDependence::DependentInstantiation
5122 : TypeDependence::None),
5123 DeducedAsType.isNull() ? QualType(this, 0)
5124 : DeducedAsType.getCanonicalType()),
5125 Template(Template) {}
5126
5127public:
5128 /// Retrieve the name of the template that we are deducing.
5129 TemplateName getTemplateName() const { return Template;}
5130
5131 void Profile(llvm::FoldingSetNodeID &ID) {
5132 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
5133 }
5134
5135 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
5136 QualType Deduced, bool IsDependent) {
5137 Template.Profile(ID);
5138 QualType CanonicalType =
5139 Deduced.isNull() ? Deduced : Deduced.getCanonicalType();
5140 ID.AddPointer(CanonicalType.getAsOpaquePtr());
5141 ID.AddBoolean(IsDependent || Template.isDependent());
5142 }
5143
5144 static bool classof(const Type *T) {
5145 return T->getTypeClass() == DeducedTemplateSpecialization;
5146 }
5147};
5148
5149/// Represents a type template specialization; the template
5150/// must be a class template, a type alias template, or a template
5151/// template parameter. A template which cannot be resolved to one of
5152/// these, e.g. because it is written with a dependent scope
5153/// specifier, is instead represented as a
5154/// @c DependentTemplateSpecializationType.
5155///
5156/// A non-dependent template specialization type is always "sugar",
5157/// typically for a \c RecordType. For example, a class template
5158/// specialization type of \c vector<int> will refer to a tag type for
5159/// the instantiation \c std::vector<int, std::allocator<int>>
5160///
5161/// Template specializations are dependent if either the template or
5162/// any of the template arguments are dependent, in which case the
5163/// type may also be canonical.
5164///
5165/// Instances of this type are allocated with a trailing array of
5166/// TemplateArguments, followed by a QualType representing the
5167/// non-canonical aliased type when the template is a type alias
5168/// template.
5169class alignas(8) TemplateSpecializationType
5170 : public Type,
5171 public llvm::FoldingSetNode {
5172 friend class ASTContext; // ASTContext creates these
5173
5174 /// The name of the template being specialized. This is
5175 /// either a TemplateName::Template (in which case it is a
5176 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
5177 /// TypeAliasTemplateDecl*), a
5178 /// TemplateName::SubstTemplateTemplateParmPack, or a
5179 /// TemplateName::SubstTemplateTemplateParm (in which case the
5180 /// replacement must, recursively, be one of these).
5181 TemplateName Template;
5182
5183 TemplateSpecializationType(TemplateName T,
5184 ArrayRef<TemplateArgument> Args,
5185 QualType Canon,
5186 QualType Aliased);
5187
5188public:
5189 /// Determine whether any of the given template arguments are dependent.
5190 ///
5191 /// The converted arguments should be supplied when known; whether an
5192 /// argument is dependent can depend on the conversions performed on it
5193 /// (for example, a 'const int' passed as a template argument might be
5194 /// dependent if the parameter is a reference but non-dependent if the
5195 /// parameter is an int).
5196 ///
5197 /// Note that the \p Args parameter is unused: this is intentional, to remind
5198 /// the caller that they need to pass in the converted arguments, not the
5199 /// specified arguments.
5200 static bool
5201 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
5202 ArrayRef<TemplateArgument> Converted);
5203 static bool
5204 anyDependentTemplateArguments(const TemplateArgumentListInfo &,
5205 ArrayRef<TemplateArgument> Converted);
5206 static bool anyInstantiationDependentTemplateArguments(
5207 ArrayRef<TemplateArgumentLoc> Args);
5208
5209 /// True if this template specialization type matches a current
5210 /// instantiation in the context in which it is found.
5211 bool isCurrentInstantiation() const {
5212 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
5213 }
5214
5215 /// Determine if this template specialization type is for a type alias
5216 /// template that has been substituted.
5217 ///
5218 /// Nearly every template specialization type whose template is an alias
5219 /// template will be substituted. However, this is not the case when
5220 /// the specialization contains a pack expansion but the template alias
5221 /// does not have a corresponding parameter pack, e.g.,
5222 ///
5223 /// \code
5224 /// template<typename T, typename U, typename V> struct S;
5225 /// template<typename T, typename U> using A = S<T, int, U>;
5226 /// template<typename... Ts> struct X {
5227 /// typedef A<Ts...> type; // not a type alias
5228 /// };
5229 /// \endcode
5230 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
5231
5232 /// Get the aliased type, if this is a specialization of a type alias
5233 /// template.
5234 QualType getAliasedType() const {
5235 assert(isTypeAlias() && "not a type alias template specialization")(static_cast <bool> (isTypeAlias() && "not a type alias template specialization"
) ? void (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "clang/include/clang/AST/Type.h", 5235, __extension__ __PRETTY_FUNCTION__
))
;
5236 return *reinterpret_cast<const QualType*>(end());
5237 }
5238
5239 using iterator = const TemplateArgument *;
5240
5241 iterator begin() const { return getArgs(); }
5242 iterator end() const; // defined inline in TemplateBase.h
5243
5244 /// Retrieve the name of the template that we are specializing.
5245 TemplateName getTemplateName() const { return Template; }
5246
5247 /// Retrieve the template arguments.
5248 const TemplateArgument *getArgs() const {
5249 return reinterpret_cast<const TemplateArgument *>(this + 1);
5250 }
5251
5252 /// Retrieve the number of template arguments.
5253 unsigned getNumArgs() const {
5254 return TemplateSpecializationTypeBits.NumArgs;
5255 }
5256
5257 /// Retrieve a specific template argument as a type.
5258 /// \pre \c isArgType(Arg)
5259 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5260
5261 ArrayRef<TemplateArgument> template_arguments() const {
5262 return {getArgs(), getNumArgs()};
5263 }
5264
5265 bool isSugared() const {
5266 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5267 }
5268
5269 QualType desugar() const {
5270 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5271 }
5272
5273 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5274 Profile(ID, Template, template_arguments(), Ctx);
5275 if (isTypeAlias())
5276 getAliasedType().Profile(ID);
5277 }
5278
5279 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5280 ArrayRef<TemplateArgument> Args,
5281 const ASTContext &Context);
5282
5283 static bool classof(const Type *T) {
5284 return T->getTypeClass() == TemplateSpecialization;
5285 }
5286};
5287
5288/// Print a template argument list, including the '<' and '>'
5289/// enclosing the template arguments.
5290void printTemplateArgumentList(raw_ostream &OS,
5291 ArrayRef<TemplateArgument> Args,
5292 const PrintingPolicy &Policy,
5293 const TemplateParameterList *TPL = nullptr);
5294
5295void printTemplateArgumentList(raw_ostream &OS,
5296 ArrayRef<TemplateArgumentLoc> Args,
5297 const PrintingPolicy &Policy,
5298 const TemplateParameterList *TPL = nullptr);
5299
5300void printTemplateArgumentList(raw_ostream &OS,
5301 const TemplateArgumentListInfo &Args,
5302 const PrintingPolicy &Policy,
5303 const TemplateParameterList *TPL = nullptr);
5304
5305/// The injected class name of a C++ class template or class
5306/// template partial specialization. Used to record that a type was
5307/// spelled with a bare identifier rather than as a template-id; the
5308/// equivalent for non-templated classes is just RecordType.
5309///
5310/// Injected class name types are always dependent. Template
5311/// instantiation turns these into RecordTypes.
5312///
5313/// Injected class name types are always canonical. This works
5314/// because it is impossible to compare an injected class name type
5315/// with the corresponding non-injected template type, for the same
5316/// reason that it is impossible to directly compare template
5317/// parameters from different dependent contexts: injected class name
5318/// types can only occur within the scope of a particular templated
5319/// declaration, and within that scope every template specialization
5320/// will canonicalize to the injected class name (when appropriate
5321/// according to the rules of the language).
5322class InjectedClassNameType : public Type {
5323 friend class ASTContext; // ASTContext creates these.
5324 friend class ASTNodeImporter;
5325 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5326 // currently suitable for AST reading, too much
5327 // interdependencies.
5328 template <class T> friend class serialization::AbstractTypeReader;
5329
5330 CXXRecordDecl *Decl;
5331
5332 /// The template specialization which this type represents.
5333 /// For example, in
5334 /// template <class T> class A { ... };
5335 /// this is A<T>, whereas in
5336 /// template <class X, class Y> class A<B<X,Y> > { ... };
5337 /// this is A<B<X,Y> >.
5338 ///
5339 /// It is always unqualified, always a template specialization type,
5340 /// and always dependent.
5341 QualType InjectedType;
5342
5343 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5344 : Type(InjectedClassName, QualType(),
5345 TypeDependence::DependentInstantiation),
5346 Decl(D), InjectedType(TST) {
5347 assert(isa<TemplateSpecializationType>(TST))(static_cast <bool> (isa<TemplateSpecializationType>
(TST)) ? void (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "clang/include/clang/AST/Type.h", 5347, __extension__ __PRETTY_FUNCTION__
))
;
5348 assert(!TST.hasQualifiers())(static_cast <bool> (!TST.hasQualifiers()) ? void (0) :
__assert_fail ("!TST.hasQualifiers()", "clang/include/clang/AST/Type.h"
, 5348, __extension__ __PRETTY_FUNCTION__))
;
5349 assert(TST->isDependentType())(static_cast <bool> (TST->isDependentType()) ? void (
0) : __assert_fail ("TST->isDependentType()", "clang/include/clang/AST/Type.h"
, 5349, __extension__ __PRETTY_FUNCTION__))
;
5350 }
5351
5352public:
5353 QualType getInjectedSpecializationType() const { return InjectedType; }
5354
5355 const TemplateSpecializationType *getInjectedTST() const {
5356 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5357 }
5358
5359 TemplateName getTemplateName() const {
5360 return getInjectedTST()->getTemplateName();
5361 }
5362
5363 CXXRecordDecl *getDecl() const;
5364
5365 bool isSugared() const { return false; }
5366 QualType desugar() const { return QualType(this, 0); }
5367
5368 static bool classof(const Type *T) {
5369 return T->getTypeClass() == InjectedClassName;
5370 }
5371};
5372
5373/// The kind of a tag type.
5374enum TagTypeKind {
5375 /// The "struct" keyword.
5376 TTK_Struct,
5377
5378 /// The "__interface" keyword.
5379 TTK_Interface,
5380
5381 /// The "union" keyword.
5382 TTK_Union,
5383
5384 /// The "class" keyword.
5385 TTK_Class,
5386
5387 /// The "enum" keyword.
5388 TTK_Enum
5389};
5390
5391/// The elaboration keyword that precedes a qualified type name or
5392/// introduces an elaborated-type-specifier.
5393enum ElaboratedTypeKeyword {
5394 /// The "struct" keyword introduces the elaborated-type-specifier.
5395 ETK_Struct,
5396
5397 /// The "__interface" keyword introduces the elaborated-type-specifier.
5398 ETK_Interface,
5399
5400 /// The "union" keyword introduces the elaborated-type-specifier.
5401 ETK_Union,
5402
5403 /// The "class" keyword introduces the elaborated-type-specifier.
5404 ETK_Class,
5405
5406 /// The "enum" keyword introduces the elaborated-type-specifier.
5407 ETK_Enum,
5408
5409 /// The "typename" keyword precedes the qualified type name, e.g.,
5410 /// \c typename T::type.
5411 ETK_Typename,
5412
5413 /// No keyword precedes the qualified type name.
5414 ETK_None
5415};
5416
5417/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5418/// The keyword in stored in the free bits of the base class.
5419/// Also provides a few static helpers for converting and printing
5420/// elaborated type keyword and tag type kind enumerations.
5421class TypeWithKeyword : public Type {
5422protected:
5423 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5424 QualType Canonical, TypeDependence Dependence)
5425 : Type(tc, Canonical, Dependence) {
5426 TypeWithKeywordBits.Keyword = Keyword;
5427 }
5428
5429public:
5430 ElaboratedTypeKeyword getKeyword() const {
5431 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5432 }
5433
5434 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5435 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5436
5437 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5438 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5439 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5440
5441 /// Converts a TagTypeKind into an elaborated type keyword.
5442 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5443
5444 /// Converts an elaborated type keyword into a TagTypeKind.
5445 /// It is an error to provide an elaborated type keyword
5446 /// which *isn't* a tag kind here.
5447 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5448
5449 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5450
5451 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5452
5453 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5454 return getKeywordName(getKeywordForTagTypeKind(Kind));
5455 }
5456
5457 class CannotCastToThisType {};
5458 static CannotCastToThisType classof(const Type *);
5459};
5460
5461/// Represents a type that was referred to using an elaborated type
5462/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5463/// or both.
5464///
5465/// This type is used to keep track of a type name as written in the
5466/// source code, including tag keywords and any nested-name-specifiers.
5467/// The type itself is always "sugar", used to express what was written
5468/// in the source code but containing no additional semantic information.
5469class ElaboratedType final
5470 : public TypeWithKeyword,
5471 public llvm::FoldingSetNode,
5472 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5473 friend class ASTContext; // ASTContext creates these
5474 friend TrailingObjects;
5475
5476 /// The nested name specifier containing the qualifier.
5477 NestedNameSpecifier *NNS;
5478
5479 /// The type that this qualified name refers to.
5480 QualType NamedType;
5481
5482 /// The (re)declaration of this tag type owned by this occurrence is stored
5483 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5484 /// it, or obtain a null pointer if there is none.
5485
5486 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5487 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5488 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5489 // Any semantic dependence on the qualifier will have
5490 // been incorporated into NamedType. We still need to
5491 // track syntactic (instantiation / error / pack)
5492 // dependence on the qualifier.
5493 NamedType->getDependence() |
5494 (NNS ? toSyntacticDependence(
5495 toTypeDependence(NNS->getDependence()))
5496 : TypeDependence::None)),
5497 NNS(NNS), NamedType(NamedType) {
5498 ElaboratedTypeBits.HasOwnedTagDecl = false;
5499 if (OwnedTagDecl) {
5500 ElaboratedTypeBits.HasOwnedTagDecl = true;
5501 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5502 }
5503 assert(!(Keyword == ETK_None && NNS == nullptr) &&(static_cast <bool> (!(Keyword == ETK_None && NNS
== nullptr) && "ElaboratedType cannot have elaborated type keyword "
"and name qualifier both null.") ? void (0) : __assert_fail (
"!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "clang/include/clang/AST/Type.h", 5505, __extension__ __PRETTY_FUNCTION__
))
5504 "ElaboratedType cannot have elaborated type keyword "(static_cast <bool> (!(Keyword == ETK_None && NNS
== nullptr) && "ElaboratedType cannot have elaborated type keyword "
"and name qualifier both null.") ? void (0) : __assert_fail (
"!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "clang/include/clang/AST/Type.h", 5505, __extension__ __PRETTY_FUNCTION__
))
5505 "and name qualifier both null.")(static_cast <bool> (!(Keyword == ETK_None && NNS
== nullptr) && "ElaboratedType cannot have elaborated type keyword "
"and name qualifier both null.") ? void (0) : __assert_fail (
"!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "clang/include/clang/AST/Type.h", 5505, __extension__ __PRETTY_FUNCTION__
))
;
5506 }
5507
5508public:
5509 /// Retrieve the qualification on this type.
5510 NestedNameSpecifier *getQualifier() const { return NNS; }
5511
5512 /// Retrieve the type named by the qualified-id.
5513 QualType getNamedType() const { return NamedType; }
5514
5515 /// Remove a single level of sugar.
5516 QualType desugar() const { return getNamedType(); }
5517
5518 /// Returns whether this type directly provides sugar.
5519 bool isSugared() const { return true; }
5520
5521 /// Return the (re)declaration of this type owned by this occurrence of this
5522 /// type, or nullptr if there is none.
5523 TagDecl *getOwnedTagDecl() const {
5524 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5525 : nullptr;
5526 }
5527
5528 void Profile(llvm::FoldingSetNodeID &ID) {
5529 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5530 }
5531
5532 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5533 NestedNameSpecifier *NNS, QualType NamedType,
5534 TagDecl *OwnedTagDecl) {
5535 ID.AddInteger(Keyword);
5536 ID.AddPointer(NNS);
5537 NamedType.Profile(ID);
5538 ID.AddPointer(OwnedTagDecl);
5539 }
5540
5541 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5542};
5543
5544/// Represents a qualified type name for which the type name is
5545/// dependent.
5546///
5547/// DependentNameType represents a class of dependent types that involve a
5548/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5549/// name of a type. The DependentNameType may start with a "typename" (for a
5550/// typename-specifier), "class", "struct", "union", or "enum" (for a
5551/// dependent elaborated-type-specifier), or nothing (in contexts where we
5552/// know that we must be referring to a type, e.g., in a base class specifier).
5553/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5554/// mode, this type is used with non-dependent names to delay name lookup until
5555/// instantiation.
5556class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5557 friend class ASTContext; // ASTContext creates these
5558
5559 /// The nested name specifier containing the qualifier.
5560 NestedNameSpecifier *NNS;
5561
5562 /// The type that this typename specifier refers to.
5563 const IdentifierInfo *Name;
5564
5565 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5566 const IdentifierInfo *Name, QualType CanonType)
5567 : TypeWithKeyword(Keyword, DependentName, CanonType,
5568 TypeDependence::DependentInstantiation |
5569 toTypeDependence(NNS->getDependence())),
5570 NNS(NNS), Name(Name) {}
5571
5572public:
5573 /// Retrieve the qualification on this type.
5574 NestedNameSpecifier *getQualifier() const { return NNS; }
5575
5576 /// Retrieve the type named by the typename specifier as an identifier.
5577 ///
5578 /// This routine will return a non-NULL identifier pointer when the
5579 /// form of the original typename was terminated by an identifier,
5580 /// e.g., "typename T::type".
5581 const IdentifierInfo *getIdentifier() const {
5582 return Name;
5583 }
5584
5585 bool isSugared() const { return false; }
5586 QualType desugar() const { return QualType(this, 0); }
5587
5588 void Profile(llvm::FoldingSetNodeID &ID) {
5589 Profile(ID, getKeyword(), NNS, Name);
5590 }
5591
5592 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5593 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5594 ID.AddInteger(Keyword);
5595 ID.AddPointer(NNS);
5596 ID.AddPointer(Name);
5597 }
5598
5599 static bool classof(const Type *T) {
5600 return T->getTypeClass() == DependentName;
5601 }
5602};
5603
5604/// Represents a template specialization type whose template cannot be
5605/// resolved, e.g.
5606/// A<T>::template B<T>
5607class alignas(8) DependentTemplateSpecializationType
5608 : public TypeWithKeyword,
5609 public llvm::FoldingSetNode {
5610 friend class ASTContext; // ASTContext creates these
5611
5612 /// The nested name specifier containing the qualifier.
5613 NestedNameSpecifier *NNS;
5614
5615 /// The identifier of the template.
5616 const IdentifierInfo *Name;
5617
5618 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5619 NestedNameSpecifier *NNS,
5620 const IdentifierInfo *Name,
5621 ArrayRef<TemplateArgument> Args,
5622 QualType Canon);
5623
5624 const TemplateArgument *getArgBuffer() const {
5625 return reinterpret_cast<const TemplateArgument*>(this+1);
5626 }
5627
5628 TemplateArgument *getArgBuffer() {
5629 return reinterpret_cast<TemplateArgument*>(this+1);
5630 }
5631
5632public:
5633 NestedNameSpecifier *getQualifier() const { return NNS; }
5634 const IdentifierInfo *getIdentifier() const { return Name; }
5635
5636 /// Retrieve the template arguments.
5637 const TemplateArgument *getArgs() const {
5638 return getArgBuffer();
5639 }
5640
5641 /// Retrieve the number of template arguments.
5642 unsigned getNumArgs() const {
5643 return DependentTemplateSpecializationTypeBits.NumArgs;
5644 }
5645
5646 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5647
5648 ArrayRef<TemplateArgument> template_arguments() const {
5649 return {getArgs(), getNumArgs()};
5650 }
5651
5652 using iterator = const TemplateArgument *;
5653
5654 iterator begin() const { return getArgs(); }
5655 iterator end() const; // inline in TemplateBase.h
5656
5657 bool isSugared() const { return false; }
5658 QualType desugar() const { return QualType(this, 0); }
5659
5660 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5661 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5662 }
5663
5664 static void Profile(llvm::FoldingSetNodeID &ID,
5665 const ASTContext &Context,
5666 ElaboratedTypeKeyword Keyword,
5667 NestedNameSpecifier *Qualifier,
5668 const IdentifierInfo *Name,
5669 ArrayRef<TemplateArgument> Args);
5670
5671 static bool classof(const Type *T) {
5672 return T->getTypeClass() == DependentTemplateSpecialization;
5673 }
5674};
5675
5676/// Represents a pack expansion of types.
5677///
5678/// Pack expansions are part of C++11 variadic templates. A pack
5679/// expansion contains a pattern, which itself contains one or more
5680/// "unexpanded" parameter packs. When instantiated, a pack expansion
5681/// produces a series of types, each instantiated from the pattern of
5682/// the expansion, where the Ith instantiation of the pattern uses the
5683/// Ith arguments bound to each of the unexpanded parameter packs. The
5684/// pack expansion is considered to "expand" these unexpanded
5685/// parameter packs.
5686///
5687/// \code
5688/// template<typename ...Types> struct tuple;
5689///
5690/// template<typename ...Types>
5691/// struct tuple_of_references {
5692/// typedef tuple<Types&...> type;
5693/// };
5694/// \endcode
5695///
5696/// Here, the pack expansion \c Types&... is represented via a
5697/// PackExpansionType whose pattern is Types&.
5698class PackExpansionType : public Type, public llvm::FoldingSetNode {
5699 friend class ASTContext; // ASTContext creates these
5700
5701 /// The pattern of the pack expansion.
5702 QualType Pattern;
5703
5704 PackExpansionType(QualType Pattern, QualType Canon,
5705 Optional<unsigned> NumExpansions)
5706 : Type(PackExpansion, Canon,
5707 (Pattern->getDependence() | TypeDependence::Dependent |
5708 TypeDependence::Instantiation) &
5709 ~TypeDependence::UnexpandedPack),
5710 Pattern(Pattern) {
5711 PackExpansionTypeBits.NumExpansions =
5712 NumExpansions ? *NumExpansions + 1 : 0;
5713 }
5714
5715public:
5716 /// Retrieve the pattern of this pack expansion, which is the
5717 /// type that will be repeatedly instantiated when instantiating the
5718 /// pack expansion itself.
5719 QualType getPattern() const { return Pattern; }
5720
5721 /// Retrieve the number of expansions that this pack expansion will
5722 /// generate, if known.
5723 Optional<unsigned> getNumExpansions() const {
5724 if (PackExpansionTypeBits.NumExpansions)
5725 return PackExpansionTypeBits.NumExpansions - 1;
5726 return None;
5727 }
5728
5729 bool isSugared() const { return false; }
5730 QualType desugar() const { return QualType(this, 0); }
5731
5732 void Profile(llvm::FoldingSetNodeID &ID) {
5733 Profile(ID, getPattern(), getNumExpansions());
5734 }
5735
5736 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5737 Optional<unsigned> NumExpansions) {
5738 ID.AddPointer(Pattern.getAsOpaquePtr());
5739 ID.AddBoolean(NumExpansions.hasValue());
5740 if (NumExpansions)
5741 ID.AddInteger(*NumExpansions);
5742 }
5743
5744 static bool classof(const Type *T) {
5745 return T->getTypeClass() == PackExpansion;
5746 }
5747};
5748
5749/// This class wraps the list of protocol qualifiers. For types that can
5750/// take ObjC protocol qualifers, they can subclass this class.
5751template <class T>
5752class ObjCProtocolQualifiers {
5753protected:
5754 ObjCProtocolQualifiers() = default;
5755
5756 ObjCProtocolDecl * const *getProtocolStorage() const {
5757 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5758 }
5759
5760 ObjCProtocolDecl **getProtocolStorage() {
5761 return static_cast<T*>(this)->getProtocolStorageImpl();
5762 }
5763
5764 void setNumProtocols(unsigned N) {
5765 static_cast<T*>(this)->setNumProtocolsImpl(N);
5766 }
5767
5768 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5769 setNumProtocols(protocols.size());
5770 assert(getNumProtocols() == protocols.size() &&(static_cast <bool> (getNumProtocols() == protocols.size
() && "bitfield overflow in protocol count") ? void (
0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "clang/include/clang/AST/Type.h", 5771, __extension__ __PRETTY_FUNCTION__
))
5771 "bitfield overflow in protocol count")(static_cast <bool> (getNumProtocols() == protocols.size
() && "bitfield overflow in protocol count") ? void (
0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "clang/include/clang/AST/Type.h", 5771, __extension__ __PRETTY_FUNCTION__
))
;
5772 if (!protocols.empty())
5773 memcpy(getProtocolStorage(), protocols.data(),
5774 protocols.size() * sizeof(ObjCProtocolDecl*));
5775 }
5776
5777public:
5778 using qual_iterator = ObjCProtocolDecl * const *;
5779 using qual_range = llvm::iterator_range<qual_iterator>;
5780
5781 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5782 qual_iterator qual_begin() const { return getProtocolStorage(); }
5783 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5784
5785 bool qual_empty() const { return getNumProtocols() == 0; }
5786
5787 /// Return the number of qualifying protocols in this type, or 0 if
5788 /// there are none.
5789 unsigned getNumProtocols() const {
5790 return static_cast<const T*>(this)->getNumProtocolsImpl();
5791 }
5792
5793 /// Fetch a protocol by index.
5794 ObjCProtocolDecl *getProtocol(unsigned I) const {
5795 assert(I < getNumProtocols() && "Out-of-range protocol access")(static_cast <bool> (I < getNumProtocols() &&
"Out-of-range protocol access") ? void (0) : __assert_fail (
"I < getNumProtocols() && \"Out-of-range protocol access\""
, "clang/include/clang/AST/Type.h", 5795, __extension__ __PRETTY_FUNCTION__
))
;
5796 return qual_begin()[I];
5797 }
5798
5799 /// Retrieve all of the protocol qualifiers.
5800 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5801 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5802 }
5803};
5804
5805/// Represents a type parameter type in Objective C. It can take
5806/// a list of protocols.
5807class ObjCTypeParamType : public Type,
5808 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5809 public llvm::FoldingSetNode {
5810 friend class ASTContext;
5811 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5812
5813 /// The number of protocols stored on this type.
5814 unsigned NumProtocols : 6;
5815
5816 ObjCTypeParamDecl *OTPDecl;
5817
5818 /// The protocols are stored after the ObjCTypeParamType node. In the
5819 /// canonical type, the list of protocols are sorted alphabetically
5820 /// and uniqued.
5821 ObjCProtocolDecl **getProtocolStorageImpl();
5822
5823 /// Return the number of qualifying protocols in this interface type,
5824 /// or 0 if there are none.
5825 unsigned getNumProtocolsImpl() const {
5826 return NumProtocols;
5827 }
5828
5829 void setNumProtocolsImpl(unsigned N) {
5830 NumProtocols = N;
5831 }
5832
5833 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5834 QualType can,
5835 ArrayRef<ObjCProtocolDecl *> protocols);
5836
5837public:
5838 bool isSugared() const { return true; }
5839 QualType desugar() const { return getCanonicalTypeInternal(); }
5840
5841 static bool classof(const Type *T) {
5842 return T->getTypeClass() == ObjCTypeParam;
5843 }
5844
5845 void Profile(llvm::FoldingSetNodeID &ID);
5846 static void Profile(llvm::FoldingSetNodeID &ID,
5847 const ObjCTypeParamDecl *OTPDecl,
5848 QualType CanonicalType,
5849 ArrayRef<ObjCProtocolDecl *> protocols);
5850
5851 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5852};
5853
5854/// Represents a class type in Objective C.
5855///
5856/// Every Objective C type is a combination of a base type, a set of
5857/// type arguments (optional, for parameterized classes) and a list of
5858/// protocols.
5859///
5860/// Given the following declarations:
5861/// \code
5862/// \@class C<T>;
5863/// \@protocol P;
5864/// \endcode
5865///
5866/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5867/// with base C and no protocols.
5868///
5869/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5870/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5871/// protocol list.
5872/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5873/// and protocol list [P].
5874///
5875/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5876/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5877/// and no protocols.
5878///
5879/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5880/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5881/// this should get its own sugar class to better represent the source.
5882class ObjCObjectType : public Type,
5883 public ObjCProtocolQualifiers<ObjCObjectType> {
5884 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5885
5886 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5887 // after the ObjCObjectPointerType node.
5888 // ObjCObjectType.NumProtocols - the number of protocols stored
5889 // after the type arguments of ObjCObjectPointerType node.
5890 //
5891 // These protocols are those written directly on the type. If
5892 // protocol qualifiers ever become additive, the iterators will need
5893 // to get kindof complicated.
5894 //
5895 // In the canonical object type, these are sorted alphabetically
5896 // and uniqued.
5897
5898 /// Either a BuiltinType or an InterfaceType or sugar for either.
5899 QualType BaseType;
5900
5901 /// Cached superclass type.
5902 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5903 CachedSuperClassType;
5904
5905 QualType *getTypeArgStorage();
5906 const QualType *getTypeArgStorage() const {
5907 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5908 }
5909
5910 ObjCProtocolDecl **getProtocolStorageImpl();
5911 /// Return the number of qualifying protocols in this interface type,
5912 /// or 0 if there are none.
5913 unsigned getNumProtocolsImpl() const {
5914 return ObjCObjectTypeBits.NumProtocols;
5915 }
5916 void setNumProtocolsImpl(unsigned N) {
5917 ObjCObjectTypeBits.NumProtocols = N;
5918 }
5919
5920protected:
5921 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5922
5923 ObjCObjectType(QualType Canonical, QualType Base,
5924 ArrayRef<QualType> typeArgs,
5925 ArrayRef<ObjCProtocolDecl *> protocols,
5926 bool isKindOf);
5927
5928 ObjCObjectType(enum Nonce_ObjCInterface)
5929 : Type(ObjCInterface, QualType(), TypeDependence::None),
5930 BaseType(QualType(this_(), 0)) {
5931 ObjCObjectTypeBits.NumProtocols = 0;
5932 ObjCObjectTypeBits.NumTypeArgs = 0;
5933 ObjCObjectTypeBits.IsKindOf = 0;
5934 }
5935
5936 void computeSuperClassTypeSlow() const;
5937
5938public:
5939 /// Gets the base type of this object type. This is always (possibly
5940 /// sugar for) one of:
5941 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5942 /// user, which is a typedef for an ObjCObjectPointerType)
5943 /// - the 'Class' builtin type (same caveat)
5944 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5945 QualType getBaseType() const { return BaseType; }
5946
5947 bool isObjCId() const {
5948 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5949 }
5950
5951 bool isObjCClass() const {
5952 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5953 }
5954
5955 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5956 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5957 bool isObjCUnqualifiedIdOrClass() const {
5958 if (!qual_empty()) return false;
5959 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5960 return T->getKind() == BuiltinType::ObjCId ||
5961 T->getKind() == BuiltinType::ObjCClass;
5962 return false;
5963 }
5964 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5965 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5966
5967 /// Gets the interface declaration for this object type, if the base type
5968 /// really is an interface.
5969 ObjCInterfaceDecl *getInterface() const;
5970
5971 /// Determine whether this object type is "specialized", meaning
5972 /// that it has type arguments.
5973 bool isSpecialized() const;
5974
5975 /// Determine whether this object type was written with type arguments.
5976 bool isSpecializedAsWritten() const {
5977 return ObjCObjectTypeBits.NumTypeArgs > 0;
5978 }
5979
5980 /// Determine whether this object type is "unspecialized", meaning
5981 /// that it has no type arguments.
5982 bool isUnspecialized() const { return !isSpecialized(); }
5983
5984 /// Determine whether this object type is "unspecialized" as
5985 /// written, meaning that it has no type arguments.
5986 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5987
5988 /// Retrieve the type arguments of this object type (semantically).
5989 ArrayRef<QualType> getTypeArgs() const;
5990
5991 /// Retrieve the type arguments of this object type as they were
5992 /// written.
5993 ArrayRef<QualType> getTypeArgsAsWritten() const {
5994 return llvm::makeArrayRef(getTypeArgStorage(),
5995 ObjCObjectTypeBits.NumTypeArgs);
5996 }
5997
5998 /// Whether this is a "__kindof" type as written.
5999 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
6000
6001 /// Whether this ia a "__kindof" type (semantically).
6002 bool isKindOfType() const;
6003
6004 /// Retrieve the type of the superclass of this object type.
6005 ///
6006 /// This operation substitutes any type arguments into the
6007 /// superclass of the current class type, potentially producing a
6008 /// specialization of the superclass type. Produces a null type if
6009 /// there is no superclass.
6010 QualType getSuperClassType() const {
6011 if (!CachedSuperClassType.getInt())
6012 computeSuperClassTypeSlow();
6013
6014 assert(CachedSuperClassType.getInt() && "Superclass not set?")(static_cast <bool> (CachedSuperClassType.getInt() &&
"Superclass not set?") ? void (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "clang/include/clang/AST/Type.h", 6014, __extension__ __PRETTY_FUNCTION__
))
;
6015 return QualType(CachedSuperClassType.getPointer(), 0);
6016 }
6017
6018 /// Strip off the Objective-C "kindof" type and (with it) any
6019 /// protocol qualifiers.
6020 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
6021
6022 bool isSugared() const { return false; }
6023 QualType desugar() const { return QualType(this, 0); }
6024
6025 static bool classof(const Type *T) {
6026 return T->getTypeClass() == ObjCObject ||
6027 T->getTypeClass() == ObjCInterface;
6028 }
6029};
6030
6031/// A class providing a concrete implementation
6032/// of ObjCObjectType, so as to not increase the footprint of
6033/// ObjCInterfaceType. Code outside of ASTContext and the core type
6034/// system should not reference this type.
6035class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
6036 friend class ASTContext;
6037
6038 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
6039 // will need to be modified.
6040
6041 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
6042 ArrayRef<QualType> typeArgs,
6043 ArrayRef<ObjCProtocolDecl *> protocols,
6044 bool isKindOf)
6045 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
6046
6047public:
6048 void Profile(llvm::FoldingSetNodeID &ID);
6049 static void Profile(llvm::FoldingSetNodeID &ID,
6050 QualType Base,
6051 ArrayRef<QualType> typeArgs,
6052 ArrayRef<ObjCProtocolDecl *> protocols,
6053 bool isKindOf);
6054};
6055
6056inline QualType *ObjCObjectType::getTypeArgStorage() {
6057 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
6058}
6059
6060inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
6061 return reinterpret_cast<ObjCProtocolDecl**>(
6062 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
6063}
6064
6065inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
6066 return reinterpret_cast<ObjCProtocolDecl**>(
6067 static_cast<ObjCTypeParamType*>(this)+1);
6068}
6069
6070/// Interfaces are the core concept in Objective-C for object oriented design.
6071/// They basically correspond to C++ classes. There are two kinds of interface
6072/// types: normal interfaces like `NSString`, and qualified interfaces, which
6073/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
6074///
6075/// ObjCInterfaceType guarantees the following properties when considered
6076/// as a subtype of its superclass, ObjCObjectType:
6077/// - There are no protocol qualifiers. To reinforce this, code which
6078/// tries to invoke the protocol methods via an ObjCInterfaceType will
6079/// fail to compile.
6080/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
6081/// T->getBaseType() == QualType(T, 0).
6082class ObjCInterfaceType : public ObjCObjectType {
6083 friend class ASTContext; // ASTContext creates these.
6084 friend class ASTReader;
6085 template <class T> friend class serialization::AbstractTypeReader;
6086
6087 ObjCInterfaceDecl *Decl;
6088
6089 ObjCInterfaceType(const ObjCInterfaceDecl *D)
6090 : ObjCObjectType(Nonce_ObjCInterface),
6091 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
6092
6093public:
6094 /// Get the declaration of this interface.
6095 ObjCInterfaceDecl *getDecl() const;
6096
6097 bool isSugared() const { return false; }
6098 QualType desugar() const { return QualType(this, 0); }
6099
6100 static bool classof(const Type *T) {
6101 return T->getTypeClass() == ObjCInterface;
6102 }
6103
6104 // Nonsense to "hide" certain members of ObjCObjectType within this
6105 // class. People asking for protocols on an ObjCInterfaceType are
6106 // not going to get what they want: ObjCInterfaceTypes are
6107 // guaranteed to have no protocols.
6108 enum {
6109 qual_iterator,
6110 qual_begin,
6111 qual_end,
6112 getNumProtocols,
6113 getProtocol
6114 };
6115};
6116
6117inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
6118 QualType baseType = getBaseType();
6119 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
6120 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
6121 return T->getDecl();
6122
6123 baseType = ObjT->getBaseType();
6124 }
6125
6126 return nullptr;
6127}
6128
6129/// Represents a pointer to an Objective C object.
6130///
6131/// These are constructed from pointer declarators when the pointee type is
6132/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
6133/// types are typedefs for these, and the protocol-qualified types 'id<P>'
6134/// and 'Class<P>' are translated into these.
6135///
6136/// Pointers to pointers to Objective C objects are still PointerTypes;
6137/// only the first level of pointer gets it own type implementation.
6138class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
6139 friend class ASTContext; // ASTContext creates these.
6140
6141 QualType PointeeType;
6142
6143 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
6144 : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()),
6145 PointeeType(Pointee) {}
6146
6147public:
6148 /// Gets the type pointed to by this ObjC pointer.
6149 /// The result will always be an ObjCObjectType or sugar thereof.
6150 QualType getPointeeType() const { return PointeeType; }
6151
6152 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
6153 ///
6154 /// This method is equivalent to getPointeeType() except that
6155 /// it discards any typedefs (or other sugar) between this
6156 /// type and the "outermost" object type. So for:
6157 /// \code
6158 /// \@class A; \@protocol P; \@protocol Q;
6159 /// typedef A<P> AP;
6160 /// typedef A A1;
6161 /// typedef A1<P> A1P;
6162 /// typedef A1P<Q> A1PQ;
6163 /// \endcode
6164 /// For 'A*', getObjectType() will return 'A'.
6165 /// For 'A<P>*', getObjectType() will return 'A<P>'.
6166 /// For 'AP*', getObjectType() will return 'A<P>'.
6167 /// For 'A1*', getObjectType() will return 'A'.
6168 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
6169 /// For 'A1P*', getObjectType() will return 'A1<P>'.
6170 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
6171 /// adding protocols to a protocol-qualified base discards the
6172 /// old qualifiers (for now). But if it didn't, getObjectType()
6173 /// would return 'A1P<Q>' (and we'd have to make iterating over
6174 /// qualifiers more complicated).
6175 const ObjCObjectType *getObjectType() const {
6176 return PointeeType->castAs<ObjCObjectType>();
6177 }
6178
6179 /// If this pointer points to an Objective C
6180 /// \@interface type, gets the type for that interface. Any protocol
6181 /// qualifiers on the interface are ignored.
6182 ///
6183 /// \return null if the base type for this pointer is 'id' or 'Class'
6184 const ObjCInterfaceType *getInterfaceType() const;
6185
6186 /// If this pointer points to an Objective \@interface
6187 /// type, gets the declaration for that interface.
6188 ///
6189 /// \return null if the base type for this pointer is 'id' or 'Class'
6190 ObjCInterfaceDecl *getInterfaceDecl() const {
6191 return getObjectType()->getInterface();
6192 }
6193
6194 /// True if this is equivalent to the 'id' type, i.e. if
6195 /// its object type is the primitive 'id' type with no protocols.
6196 bool isObjCIdType() const {
6197 return getObjectType()->isObjCUnqualifiedId();
6198 }
6199
6200 /// True if this is equivalent to the 'Class' type,
6201 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
6202 bool isObjCClassType() const {
6203 return getObjectType()->isObjCUnqualifiedClass();
6204 }
6205
6206 /// True if this is equivalent to the 'id' or 'Class' type,
6207 bool isObjCIdOrClassType() const {
6208 return getObjectType()->isObjCUnqualifiedIdOrClass();
6209 }
6210
6211 /// True if this is equivalent to 'id<P>' for some non-empty set of
6212 /// protocols.
6213 bool isObjCQualifiedIdType() const {
6214 return getObjectType()->isObjCQualifiedId();
6215 }
6216
6217 /// True if this is equivalent to 'Class<P>' for some non-empty set of
6218 /// protocols.
6219 bool isObjCQualifiedClassType() const {
6220 return getObjectType()->isObjCQualifiedClass();
6221 }
6222
6223 /// Whether this is a "__kindof" type.
6224 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
6225
6226 /// Whether this type is specialized, meaning that it has type arguments.
6227 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
6228
6229 /// Whether this type is specialized, meaning that it has type arguments.
6230 bool isSpecializedAsWritten() const {
6231 return getObjectType()->isSpecializedAsWritten();
6232 }
6233
6234 /// Whether this type is unspecialized, meaning that is has no type arguments.
6235 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
6236
6237 /// Determine whether this object type is "unspecialized" as
6238 /// written, meaning that it has no type arguments.
6239 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
6240
6241 /// Retrieve the type arguments for this type.
6242 ArrayRef<QualType> getTypeArgs() const {
6243 return getObjectType()->getTypeArgs();
6244 }
6245
6246 /// Retrieve the type arguments for this type.
6247 ArrayRef<QualType> getTypeArgsAsWritten() const {
6248 return getObjectType()->getTypeArgsAsWritten();
6249 }
6250
6251 /// An iterator over the qualifiers on the object type. Provided
6252 /// for convenience. This will always iterate over the full set of
6253 /// protocols on a type, not just those provided directly.
6254 using qual_iterator = ObjCObjectType::qual_iterator;
6255 using qual_range = llvm::iterator_range<qual_iterator>;
6256
6257 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
6258
6259 qual_iterator qual_begin() const {
6260 return getObjectType()->qual_begin();
6261 }
6262
6263 qual_iterator qual_end() const {
6264 return getObjectType()->qual_end();
6265 }
6266
6267 bool qual_empty() const { return getObjectType()->qual_empty(); }
6268
6269 /// Return the number of qualifying protocols on the object type.
6270 unsigned getNumProtocols() const {
6271 return getObjectType()->getNumProtocols();
6272 }
6273
6274 /// Retrieve a qualifying protocol by index on the object type.
6275 ObjCProtocolDecl *getProtocol(unsigned I) const {
6276 return getObjectType()->getProtocol(I);
6277 }
6278
6279 bool isSugared() const { return false; }
6280 QualType desugar() const { return QualType(this, 0); }
6281
6282 /// Retrieve the type of the superclass of this object pointer type.
6283 ///
6284 /// This operation substitutes any type arguments into the
6285 /// superclass of the current class type, potentially producing a
6286 /// pointer to a specialization of the superclass type. Produces a
6287 /// null type if there is no superclass.
6288 QualType getSuperClassType() const;
6289
6290 /// Strip off the Objective-C "kindof" type and (with it) any
6291 /// protocol qualifiers.
6292 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6293 const ASTContext &ctx) const;
6294
6295 void Profile(llvm::FoldingSetNodeID &ID) {
6296 Profile(ID, getPointeeType());
6297 }
6298
6299 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6300 ID.AddPointer(T.getAsOpaquePtr());
6301 }
6302
6303 static bool classof(const Type *T) {
6304 return T->getTypeClass() == ObjCObjectPointer;
6305 }
6306};
6307
6308class AtomicType : public Type, public llvm::FoldingSetNode {
6309 friend class ASTContext; // ASTContext creates these.
6310
6311 QualType ValueType;
6312
6313 AtomicType(QualType ValTy, QualType Canonical)
6314 : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {}
6315
6316public:
6317 /// Gets the type contained by this atomic type, i.e.
6318 /// the type returned by performing an atomic load of this atomic type.
6319 QualType getValueType() const { return ValueType; }
6320
6321 bool isSugared() const { return false; }
6322 QualType desugar() const { return QualType(this, 0); }
6323
6324 void Profile(llvm::FoldingSetNodeID &ID) {
6325 Profile(ID, getValueType());
6326 }
6327
6328 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6329 ID.AddPointer(T.getAsOpaquePtr());
6330 }
6331
6332 static bool classof(const Type *T) {
6333 return T->getTypeClass() == Atomic;
6334 }
6335};
6336
6337/// PipeType - OpenCL20.
6338class PipeType : public Type, public llvm::FoldingSetNode {
6339 friend class ASTContext; // ASTContext creates these.
6340
6341 QualType ElementType;
6342 bool isRead;
6343
6344 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6345 : Type(Pipe, CanonicalPtr, elemType->getDependence()),
6346 ElementType(elemType), isRead(isRead) {}
6347
6348public:
6349 QualType getElementType() const { return ElementType; }
6350
6351 bool isSugared() const { return false; }
6352
6353 QualType desugar() const { return QualType(this, 0); }
6354
6355 void Profile(llvm::FoldingSetNodeID &ID) {
6356 Profile(ID, getElementType(), isReadOnly());
6357 }
6358
6359 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6360 ID.AddPointer(T.getAsOpaquePtr());
6361 ID.AddBoolean(isRead);
6362 }
6363
6364 static bool classof(const Type *T) {
6365 return T->getTypeClass() == Pipe;
6366 }
6367
6368 bool isReadOnly() const { return isRead; }
6369};
6370
6371/// A fixed int type of a specified bitwidth.
6372class BitIntType final : public Type, public llvm::FoldingSetNode {
6373 friend class ASTContext;
6374 unsigned IsUnsigned : 1;
6375 unsigned NumBits : 24;
6376
6377protected:
6378 BitIntType(bool isUnsigned, unsigned NumBits);
6379
6380public:
6381 bool isUnsigned() const { return IsUnsigned; }
6382 bool isSigned() const { return !IsUnsigned; }
6383 unsigned getNumBits() const { return NumBits; }
6384
6385 bool isSugared() const { return false; }
6386 QualType desugar() const { return QualType(this, 0); }
6387
6388 void Profile(llvm::FoldingSetNodeID &ID) {
6389 Profile(ID, isUnsigned(), getNumBits());
6390 }
6391
6392 static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned,
6393 unsigned NumBits) {
6394 ID.AddBoolean(IsUnsigned);
6395 ID.AddInteger(NumBits);
6396 }
6397
6398 static bool classof(const Type *T) { return T->getTypeClass() == BitInt; }
6399};
6400
6401class DependentBitIntType final : public Type, public llvm::FoldingSetNode {
6402 friend class ASTContext;
6403 const ASTContext &Context;
6404 llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned;
6405
6406protected:
6407 DependentBitIntType(const ASTContext &Context, bool IsUnsigned,
6408 Expr *NumBits);
6409
6410public:
6411 bool isUnsigned() const;
6412 bool isSigned() const { return !isUnsigned(); }
6413 Expr *getNumBitsExpr() const;
6414
6415 bool isSugared() const { return false; }
6416 QualType desugar() const { return QualType(this, 0); }
6417
6418 void Profile(llvm::FoldingSetNodeID &ID) {
6419 Profile(ID, Context, isUnsigned(), getNumBitsExpr());
6420 }
6421 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
6422 bool IsUnsigned, Expr *NumBitsExpr);
6423
6424 static bool classof(const Type *T) {
6425 return T->getTypeClass() == DependentBitInt;
6426 }
6427};
6428
6429/// A qualifier set is used to build a set of qualifiers.
6430class QualifierCollector : public Qualifiers {
6431public:
6432 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6433
6434 /// Collect any qualifiers on the given type and return an
6435 /// unqualified type. The qualifiers are assumed to be consistent
6436 /// with those already in the type.
6437 const Type *strip(QualType type) {
6438 addFastQualifiers(type.getLocalFastQualifiers());
6439 if (!type.hasLocalNonFastQualifiers())
6440 return type.getTypePtrUnsafe();
6441
6442 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6443 addConsistentQualifiers(extQuals->getQualifiers());
6444 return extQuals->getBaseType();
6445 }
6446
6447 /// Apply the collected qualifiers to the given type.
6448 QualType apply(const ASTContext &Context, QualType QT) const;
6449
6450 /// Apply the collected qualifiers to the given type.
6451 QualType apply(const ASTContext &Context, const Type* T) const;
6452};
6453
6454/// A container of type source information.
6455///
6456/// A client can read the relevant info using TypeLoc wrappers, e.g:
6457/// @code
6458/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
6459/// TL.getBeginLoc().print(OS, SrcMgr);
6460/// @endcode
6461class alignas(8) TypeSourceInfo {
6462 // Contains a memory block after the class, used for type source information,
6463 // allocated by ASTContext.
6464 friend class ASTContext;
6465
6466 QualType Ty;
6467
6468 TypeSourceInfo(QualType ty) : Ty(ty) {}
6469
6470public:
6471 /// Return the type wrapped by this type source info.
6472 QualType getType() const { return Ty; }
6473
6474 /// Return the TypeLoc wrapper for the type source info.
6475 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
6476
6477 /// Override the type stored in this TypeSourceInfo. Use with caution!
6478 void overrideType(QualType T) { Ty = T; }
6479};
6480
6481// Inline function definitions.
6482
6483inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6484 SplitQualType desugar =
6485 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6486 desugar.Quals.addConsistentQualifiers(Quals);
6487 return desugar;
6488}
6489
6490inline const Type *QualType::getTypePtr() const {
6491 return getCommonPtr()->BaseType;
6492}
6493
6494inline const Type *QualType::getTypePtrOrNull() const {
6495 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6496}
6497
6498inline SplitQualType QualType::split() const {
6499 if (!hasLocalNonFastQualifiers())
6500 return SplitQualType(getTypePtrUnsafe(),
6501 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6502
6503 const ExtQuals *eq = getExtQualsUnsafe();
6504 Qualifiers qs = eq->getQualifiers();
6505 qs.addFastQualifiers(getLocalFastQualifiers());
6506 return SplitQualType(eq->getBaseType(), qs);
6507}
6508
6509inline Qualifiers QualType::getLocalQualifiers() const {
6510 Qualifiers Quals;
6511 if (hasLocalNonFastQualifiers())
6512 Quals = getExtQualsUnsafe()->getQualifiers();
6513 Quals.addFastQualifiers(getLocalFastQualifiers());
6514 return Quals;
6515}
6516
6517inline Qualifiers QualType::getQualifiers() const {
6518 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6519 quals.addFastQualifiers(getLocalFastQualifiers());
6520 return quals;
6521}
6522
6523inline unsigned QualType::getCVRQualifiers() const {
6524 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6525 cvr |= getLocalCVRQualifiers();
6526 return cvr;
6527}
6528
6529inline QualType QualType::getCanonicalType() const {
6530 QualType canon = getCommonPtr()->CanonicalType;
6531 return canon.withFastQualifiers(getLocalFastQualifiers());
6532}
6533
6534inline bool QualType::isCanonical() const {
6535 return getTypePtr()->isCanonicalUnqualified();
6536}
6537
6538inline bool QualType::isCanonicalAsParam() const {
6539 if (!isCanonical()) return false;
6540 if (hasLocalQualifiers()) return false;
6541
6542 const Type *T = getTypePtr();
6543 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6544 return false;
6545
6546 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6547}
6548
6549inline bool QualType::isConstQualified() const {
6550 return isLocalConstQualified() ||
6551 getCommonPtr()->CanonicalType.isLocalConstQualified();
6552}
6553
6554inline bool QualType::isRestrictQualified() const {
6555 return isLocalRestrictQualified() ||
6556 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6557}
6558
6559
6560inline bool QualType::isVolatileQualified() const {
6561 return isLocalVolatileQualified() ||
6562 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6563}
6564
6565inline bool QualType::hasQualifiers() const {
6566 return hasLocalQualifiers() ||
6567 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6568}
6569
6570inline QualType QualType::getUnqualifiedType() const {
6571 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6572 return QualType(getTypePtr(), 0);
6573
6574 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6575}
6576
6577inline SplitQualType QualType::getSplitUnqualifiedType() const {
6578 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6579 return split();
6580
6581 return getSplitUnqualifiedTypeImpl(*this);
6582}
6583
6584inline void QualType::removeLocalConst() {
6585 removeLocalFastQualifiers(Qualifiers::Const);
6586}
6587
6588inline void QualType::removeLocalRestrict() {
6589 removeLocalFastQualifiers(Qualifiers::Restrict);
6590}
6591
6592inline void QualType::removeLocalVolatile() {
6593 removeLocalFastQualifiers(Qualifiers::Volatile);
6594}
6595
6596inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6597 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")(static_cast <bool> (!(Mask & ~Qualifiers::CVRMask)
&& "mask has non-CVR bits") ? void (0) : __assert_fail
("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "clang/include/clang/AST/Type.h", 6597, __extension__ __PRETTY_FUNCTION__
))
;
6598 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6599 "Fast bits differ from CVR bits!");
6600
6601 // Fast path: we don't need to touch the slow qualifiers.
6602 removeLocalFastQualifiers(Mask);
6603}
6604
6605/// Check if this type has any address space qualifier.
6606inline bool QualType::hasAddressSpace() const {
6607 return getQualifiers().hasAddressSpace();
6608}
6609
6610/// Return the address space of this type.
6611inline LangAS QualType::getAddressSpace() const {
6612 return getQualifiers().getAddressSpace();
6613}
6614
6615/// Return the gc attribute of this type.
6616inline Qualifiers::GC QualType::getObjCGCAttr() const {
6617 return getQualifiers().getObjCGCAttr();
6618}
6619
6620inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6621 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6622 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6623 return false;
6624}
6625
6626inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6627 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6628 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6629 return false;
6630}
6631
6632inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6633 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6634 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6635 return false;
6636}
6637
6638inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6639 if (const auto *PT = t.getAs<PointerType>()) {
6640 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6641 return FT->getExtInfo();
6642 } else if (const auto *FT = t.getAs<FunctionType>())
6643 return FT->getExtInfo();
6644
6645 return FunctionType::ExtInfo();
6646}
6647
6648inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6649 return getFunctionExtInfo(*t);
6650}
6651
6652/// Determine whether this type is more
6653/// qualified than the Other type. For example, "const volatile int"
6654/// is more qualified than "const int", "volatile int", and
6655/// "int". However, it is not more qualified than "const volatile
6656/// int".
6657inline bool QualType::isMoreQualifiedThan(QualType other) const {
6658 Qualifiers MyQuals = getQualifiers();
6659 Qualifiers OtherQuals = other.getQualifiers();
6660 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6661}
6662
6663/// Determine whether this type is at last
6664/// as qualified as the Other type. For example, "const volatile
6665/// int" is at least as qualified as "const int", "volatile int",
6666/// "int", and "const volatile int".
6667inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6668 Qualifiers OtherQuals = other.getQualifiers();
6669
6670 // Ignore __unaligned qualifier if this type is a void.
6671 if (getUnqualifiedType()->isVoidType())
6672 OtherQuals.removeUnaligned();
6673
6674 return getQualifiers().compatiblyIncludes(OtherQuals);
6675}
6676
6677/// If Type is a reference type (e.g., const
6678/// int&), returns the type that the reference refers to ("const
6679/// int"). Otherwise, returns the type itself. This routine is used
6680/// throughout Sema to implement C++ 5p6:
6681///
6682/// If an expression initially has the type "reference to T" (8.3.2,
6683/// 8.5.3), the type is adjusted to "T" prior to any further
6684/// analysis, the expression designates the object or function
6685/// denoted by the reference, and the expression is an lvalue.
6686inline QualType QualType::getNonReferenceType() const {
6687 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6688 return RefType->getPointeeType();
6689 else
6690 return *this;
6691}
6692
6693inline bool QualType::isCForbiddenLValueType() const {
6694 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6695 getTypePtr()->isFunctionType());
6696}
6697
6698/// Tests whether the type is categorized as a fundamental type.
6699///
6700/// \returns True for types specified in C++0x [basic.fundamental].
6701inline bool Type::isFundamentalType() const {
6702 return isVoidType() ||
6703 isNullPtrType() ||
6704 // FIXME: It's really annoying that we don't have an
6705 // 'isArithmeticType()' which agrees with the standard definition.
6706 (isArithmeticType() && !isEnumeralType());
6707}
6708
6709/// Tests whether the type is categorized as a compound type.
6710///
6711/// \returns True for types specified in C++0x [basic.compound].
6712inline bool Type::isCompoundType() const {
6713 // C++0x [basic.compound]p1:
6714 // Compound types can be constructed in the following ways:
6715 // -- arrays of objects of a given type [...];
6716 return isArrayType() ||
6717 // -- functions, which have parameters of given types [...];
6718 isFunctionType() ||
6719 // -- pointers to void or objects or functions [...];
6720 isPointerType() ||
6721 // -- references to objects or functions of a given type. [...]
6722 isReferenceType() ||
6723 // -- classes containing a sequence of objects of various types, [...];
6724 isRecordType() ||
6725 // -- unions, which are classes capable of containing objects of different
6726 // types at different times;
6727 isUnionType() ||
6728 // -- enumerations, which comprise a set of named constant values. [...];
6729 isEnumeralType() ||
6730 // -- pointers to non-static class members, [...].
6731 isMemberPointerType();
6732}
6733
6734inline bool Type::isFunctionType() const {
6735 return isa<FunctionType>(CanonicalType);
6736}
6737
6738inline bool Type::isPointerType() const {
6739 return isa<PointerType>(CanonicalType);
6740}
6741
6742inline bool Type::isAnyPointerType() const {
6743 return isPointerType() || isObjCObjectPointerType();
6744}
6745
6746inline bool Type::isBlockPointerType() const {
6747 return isa<BlockPointerType>(CanonicalType);
56
Assuming field 'CanonicalType' is a 'BlockPointerType'
57
Returning the value 1, which participates in a condition later
6748}
6749
6750inline bool Type::isReferenceType() const {
6751 return isa<ReferenceType>(CanonicalType);
6752}
6753
6754inline bool Type::isLValueReferenceType() const {
6755 return isa<LValueReferenceType>(CanonicalType);
6756}
6757
6758inline bool Type::isRValueReferenceType() const {
6759 return isa<RValueReferenceType>(CanonicalType);
6760}
6761
6762inline bool Type::isObjectPointerType() const {
6763 // Note: an "object pointer type" is not the same thing as a pointer to an
6764 // object type; rather, it is a pointer to an object type or a pointer to cv
6765 // void.
6766 if (const auto *T = getAs<PointerType>())
6767 return !T->getPointeeType()->isFunctionType();
6768 else
6769 return false;
6770}
6771
6772inline bool Type::isFunctionPointerType() const {
6773 if (const auto *T = getAs<PointerType>())
6774 return T->getPointeeType()->isFunctionType();
6775 else
6776 return false;
6777}
6778
6779inline bool Type::isFunctionReferenceType() const {
6780 if (const auto *T = getAs<ReferenceType>())
6781 return T->getPointeeType()->isFunctionType();
6782 else
6783 return false;
6784}
6785
6786inline bool Type::isMemberPointerType() const {
6787 return isa<MemberPointerType>(CanonicalType);
6788}
6789
6790inline bool Type::isMemberFunctionPointerType() const {
6791 if (const auto *T = getAs<MemberPointerType>())
6792 return T->isMemberFunctionPointer();
6793 else
6794 return false;
6795}
6796
6797inline bool Type::isMemberDataPointerType() const {
6798 if (const auto *T = getAs<MemberPointerType>())
6799 return T->isMemberDataPointer();
6800 else
6801 return false;
6802}
6803
6804inline bool Type::isArrayType() const {
6805 return isa<ArrayType>(CanonicalType);
6806}
6807
6808inline bool Type::isConstantArrayType() const {
6809 return isa<ConstantArrayType>(CanonicalType);
6810}
6811
6812inline bool Type::isIncompleteArrayType() const {
6813 return isa<IncompleteArrayType>(CanonicalType);
6814}
6815
6816inline bool Type::isVariableArrayType() const {
6817 return isa<VariableArrayType>(CanonicalType);
6818}
6819
6820inline bool Type::isDependentSizedArrayType() const {
6821 return isa<DependentSizedArrayType>(CanonicalType);
6822}
6823
6824inline bool Type::isBuiltinType() const {
6825 return isa<BuiltinType>(CanonicalType);
6826}
6827
6828inline bool Type::isRecordType() const {
6829 return isa<RecordType>(CanonicalType);
6830}
6831
6832inline bool Type::isEnumeralType() const {
6833 return isa<EnumType>(CanonicalType);
6834}
6835
6836inline bool Type::isAnyComplexType() const {
6837 return isa<ComplexType>(CanonicalType);
6838}
6839
6840inline bool Type::isVectorType() const {
6841 return isa<VectorType>(CanonicalType);
22
Assuming field 'CanonicalType' is not a 'VectorType'
23
Returning zero, which participates in a condition later
26
Assuming field 'CanonicalType' is not a 'VectorType'
27
Returning zero, which participates in a condition later
6842}
6843
6844inline bool Type::isExtVectorType() const {
6845 return isa<ExtVectorType>(CanonicalType);
18
Assuming field 'CanonicalType' is not a 'ExtVectorType'
19
Returning zero, which participates in a condition later
6846}
6847
6848inline bool Type::isExtVectorBoolType() const {
6849 if (!isExtVectorType())
6850 return false;
6851 return cast<ExtVectorType>(CanonicalType)->getElementType()->isBooleanType();
6852}
6853
6854inline bool Type::isMatrixType() const {
6855 return isa<MatrixType>(CanonicalType);
6856}
6857
6858inline bool Type::isConstantMatrixType() const {
6859 return isa<ConstantMatrixType>(CanonicalType);
6860}
6861
6862inline bool Type::isDependentAddressSpaceType() const {
6863 return isa<DependentAddressSpaceType>(CanonicalType);
6864}
6865
6866inline bool Type::isObjCObjectPointerType() const {
6867 return isa<ObjCObjectPointerType>(CanonicalType);
6868}
6869
6870inline bool Type::isObjCObjectType() const {
6871 return isa<ObjCObjectType>(CanonicalType);
6872}
6873
6874inline bool Type::isObjCObjectOrInterfaceType() const {
6875 return isa<ObjCInterfaceType>(CanonicalType) ||
6876 isa<ObjCObjectType>(CanonicalType);
6877}
6878
6879inline bool Type::isAtomicType() const {
6880 return isa<AtomicType>(CanonicalType);
6881}
6882
6883inline bool Type::isUndeducedAutoType() const {
6884 return isa<AutoType>(CanonicalType);
6885}
6886
6887inline bool Type::isObjCQualifiedIdType() const {
6888 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6889 return OPT->isObjCQualifiedIdType();
6890 return false;
6891}
6892
6893inline bool Type::isObjCQualifiedClassType() const {
6894 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6895 return OPT->isObjCQualifiedClassType();
6896 return false;
6897}
6898
6899inline bool Type::isObjCIdType() const {
6900 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6901 return OPT->isObjCIdType();
6902 return false;
6903}
6904
6905inline bool Type::isObjCClassType() const {
6906 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6907 return OPT->isObjCClassType();
6908 return false;
6909}
6910
6911inline bool Type::isObjCSelType() const {
6912 if (const auto *OPT = getAs<PointerType>())
6913 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6914 return false;
6915}
6916
6917inline bool Type::isObjCBuiltinType() const {
6918 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6919}
6920
6921inline bool Type::isDecltypeType() const {
6922 return isa<DecltypeType>(this);
6923}
6924
6925#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6926 inline bool Type::is##Id##Type() const { \
6927 return isSpecificBuiltinType(BuiltinType::Id); \
6928 }
6929#include "clang/Basic/OpenCLImageTypes.def"
6930
6931inline bool Type::isSamplerT() const {
6932 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6933}
6934
6935inline bool Type::isEventT() const {
6936 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6937}
6938
6939inline bool Type::isClkEventT() const {
6940 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6941}
6942
6943inline bool Type::isQueueT() const {
6944 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6945}
6946
6947inline bool Type::isReserveIDT() const {
6948 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6949}
6950
6951inline bool Type::isImageType() const {
6952#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6953 return
6954#include "clang/Basic/OpenCLImageTypes.def"
6955 false; // end boolean or operation
6956}
6957
6958inline bool Type::isPipeType() const {
6959 return isa<PipeType>(CanonicalType);
6960}
6961
6962inline bool Type::isBitIntType() const {
6963 return isa<BitIntType>(CanonicalType);
6964}
6965
6966#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6967 inline bool Type::is##Id##Type() const { \
6968 return isSpecificBuiltinType(BuiltinType::Id); \
6969 }
6970#include "clang/Basic/OpenCLExtensionTypes.def"
6971
6972inline bool Type::isOCLIntelSubgroupAVCType() const {
6973#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6974 isOCLIntelSubgroupAVC##Id##Type() ||
6975 return
6976#include "clang/Basic/OpenCLExtensionTypes.def"
6977 false; // end of boolean or operation
6978}
6979
6980inline bool Type::isOCLExtOpaqueType() const {
6981#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6982 return
6983#include "clang/Basic/OpenCLExtensionTypes.def"
6984 false; // end of boolean or operation
6985}
6986
6987inline bool Type::isOpenCLSpecificType() const {
6988 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6989 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6990}
6991
6992inline bool Type::isTemplateTypeParmType() const {
6993 return isa<TemplateTypeParmType>(CanonicalType);
6994}
6995
6996inline bool Type::isSpecificBuiltinType(unsigned K) const {
6997 if (const BuiltinType *BT = getAs<BuiltinType>()) {
6998 return BT->getKind() == static_cast<BuiltinType::Kind>(K);
6999 }
7000 return false;
7001}
7002
7003inline bool Type::isPlaceholderType() const {
7004 if (const auto *BT = dyn_cast<BuiltinType>(this))
7005 return BT->isPlaceholderType();
7006 return false;
7007}
7008
7009inline const BuiltinType *Type::getAsPlaceholderType() const {
7010 if (const auto *BT = dyn_cast<BuiltinType>(this))
7011 if (BT->isPlaceholderType())
7012 return BT;
7013 return nullptr;
7014}
7015
7016inline bool Type::isSpecificPlaceholderType(unsigned K) const {
7017 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))(static_cast <bool> (BuiltinType::isPlaceholderTypeKind
((BuiltinType::Kind) K)) ? void (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "clang/include/clang/AST/Type.h", 7017, __extension__ __PRETTY_FUNCTION__
))
;
7018 return isSpecificBuiltinType(K);
7019}
7020
7021inline bool Type::isNonOverloadPlaceholderType() const {
7022 if (const auto *BT = dyn_cast<BuiltinType>(this))
7023 return BT->isNonOverloadPlaceholderType();
7024 return false;
7025}
7026
7027inline bool Type::isVoidType() const {
7028 return isSpecificBuiltinType(BuiltinType::Void);
7029}
7030
7031inline bool Type::isHalfType() const {
7032 // FIXME: Should we allow complex __fp16? Probably not.
7033 return isSpecificBuiltinType(BuiltinType::Half);
7034}
7035
7036inline bool Type::isFloat16Type() const {
7037 return isSpecificBuiltinType(BuiltinType::Float16);
7038}
7039
7040inline bool Type::isBFloat16Type() const {
7041 return isSpecificBuiltinType(BuiltinType::BFloat16);
7042}
7043
7044inline bool Type::isFloat128Type() const {
7045 return isSpecificBuiltinType(BuiltinType::Float128);
7046}
7047
7048inline bool Type::isIbm128Type() const {
7049 return isSpecificBuiltinType(BuiltinType::Ibm128);
7050}
7051
7052inline bool Type::isNullPtrType() const {
7053 return isSpecificBuiltinType(BuiltinType::NullPtr);
7054}
7055
7056bool IsEnumDeclComplete(EnumDecl *);
7057bool IsEnumDeclScoped(EnumDecl *);
7058
7059inline bool Type::isIntegerType() const {
7060 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7061 return BT->getKind() >= BuiltinType::Bool &&
7062 BT->getKind() <= BuiltinType::Int128;
7063 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
7064 // Incomplete enum types are not treated as integer types.
7065 // FIXME: In C++, enum types are never integer types.
7066 return IsEnumDeclComplete(ET->getDecl()) &&
7067 !IsEnumDeclScoped(ET->getDecl());
7068 }
7069 return isBitIntType();
7070}
7071
7072inline bool Type::isFixedPointType() const {
7073 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7074 return BT->getKind() >= BuiltinType::ShortAccum &&
7075 BT->getKind() <= BuiltinType::SatULongFract;
7076 }
7077 return false;
7078}
7079
7080inline bool Type::isFixedPointOrIntegerType() const {
7081 return isFixedPointType() || isIntegerType();
7082}
7083
7084inline bool Type::isSaturatedFixedPointType() const {
7085 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7086 return BT->getKind() >= BuiltinType::SatShortAccum &&
7087 BT->getKind() <= BuiltinType::SatULongFract;
7088 }
7089 return false;
7090}
7091
7092inline bool Type::isUnsaturatedFixedPointType() const {
7093 return isFixedPointType() && !isSaturatedFixedPointType();
7094}
7095
7096inline bool Type::isSignedFixedPointType() const {
7097 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7098 return ((BT->getKind() >= BuiltinType::ShortAccum &&
7099 BT->getKind() <= BuiltinType::LongAccum) ||
7100 (BT->getKind() >= BuiltinType::ShortFract &&
7101 BT->getKind() <= BuiltinType::LongFract) ||
7102 (BT->getKind() >= BuiltinType::SatShortAccum &&
7103 BT->getKind() <= BuiltinType::SatLongAccum) ||
7104 (BT->getKind() >= BuiltinType::SatShortFract &&
7105 BT->getKind() <= BuiltinType::SatLongFract));
7106 }
7107 return false;
7108}
7109
7110inline bool Type::isUnsignedFixedPointType() const {
7111 return isFixedPointType() && !isSignedFixedPointType();
7112}
7113
7114inline bool Type::isScalarType() const {
7115 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7116 return BT->getKind() > BuiltinType::Void &&
7117 BT->getKind() <= BuiltinType::NullPtr;
7118 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
7119 // Enums are scalar types, but only if they are defined. Incomplete enums
7120 // are not treated as scalar types.
7121 return IsEnumDeclComplete(ET->getDecl());
7122 return isa<PointerType>(CanonicalType) ||
7123 isa<BlockPointerType>(CanonicalType) ||
7124 isa<MemberPointerType>(CanonicalType) ||
7125 isa<ComplexType>(CanonicalType) ||
7126 isa<ObjCObjectPointerType>(CanonicalType) ||
7127 isBitIntType();
7128}
7129
7130inline bool Type::isIntegralOrEnumerationType() const {
7131 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7132 return BT->getKind() >= BuiltinType::Bool &&
7133 BT->getKind() <= BuiltinType::Int128;
7134
7135 // Check for a complete enum type; incomplete enum types are not properly an
7136 // enumeration type in the sense required here.
7137 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
7138 return IsEnumDeclComplete(ET->getDecl());
7139
7140 return isBitIntType();
7141}
7142
7143inline bool Type::isBooleanType() const {
7144 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7145 return BT->getKind() == BuiltinType::Bool;
7146 return false;
7147}
7148
7149inline bool Type::isUndeducedType() const {
7150 auto *DT = getContainedDeducedType();
7151 return DT && !DT->isDeduced();
7152}
7153
7154/// Determines whether this is a type for which one can define
7155/// an overloaded operator.
7156inline bool Type::isOverloadableType() const {
7157 return isDependentType() || isRecordType() || isEnumeralType();
7158}
7159
7160/// Determines whether this type is written as a typedef-name.
7161inline bool Type::isTypedefNameType() const {
7162 if (getAs<TypedefType>())
7163 return true;
7164 if (auto *TST = getAs<TemplateSpecializationType>())
7165 return TST->isTypeAlias();
7166 return false;
7167}
7168
7169/// Determines whether this type can decay to a pointer type.
7170inline bool Type::canDecayToPointerType() const {
7171 return isFunctionType() || isArrayType();
7172}
7173
7174inline bool Type::hasPointerRepresentation() const {
7175 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
7176 isObjCObjectPointerType() || isNullPtrType());
7177}
7178
7179inline bool Type::hasObjCPointerRepresentation() const {
7180 return isObjCObjectPointerType();
7181}
7182
7183inline const Type *Type::getBaseElementTypeUnsafe() const {
7184 const Type *type = this;
7185 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
7186 type = arrayType->getElementType().getTypePtr();
7187 return type;
7188}
7189
7190inline const Type *Type::getPointeeOrArrayElementType() const {
7191 const Type *type = this;
7192 if (type->isAnyPointerType())
7193 return type->getPointeeType().getTypePtr();
7194 else if (type->isArrayType())
7195 return type->getBaseElementTypeUnsafe();
7196 return type;
7197}
7198/// Insertion operator for partial diagnostics. This allows sending adress
7199/// spaces into a diagnostic with <<.
7200inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7201 LangAS AS) {
7202 PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
7203 DiagnosticsEngine::ArgumentKind::ak_addrspace);
7204 return PD;
7205}
7206
7207/// Insertion operator for partial diagnostics. This allows sending Qualifiers
7208/// into a diagnostic with <<.
7209inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7210 Qualifiers Q) {
7211 PD.AddTaggedVal(Q.getAsOpaqueValue(),
7212 DiagnosticsEngine::ArgumentKind::ak_qual);
7213 return PD;
7214}
7215
7216/// Insertion operator for partial diagnostics. This allows sending QualType's
7217/// into a diagnostic with <<.
7218inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7219 QualType T) {
7220 PD.AddTaggedVal(reinterpret_cast<uint64_t>(T.getAsOpaquePtr()),
7221 DiagnosticsEngine::ak_qualtype);
7222 return PD;
7223}
7224
7225// Helper class template that is used by Type::getAs to ensure that one does
7226// not try to look through a qualified type to get to an array type.
7227template <typename T>
7228using TypeIsArrayType =
7229 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
7230 std::is_base_of<ArrayType, T>::value>;
7231
7232// Member-template getAs<specific type>'.
7233template <typename T> const T *Type::getAs() const {
7234 static_assert(!TypeIsArrayType<T>::value,
7235 "ArrayType cannot be used with getAs!");
7236
7237 // If this is directly a T type, return it.
7238 if (const auto *Ty = dyn_cast<T>(this))
7239 return Ty;
7240
7241 // If the canonical form of this type isn't the right kind, reject it.
7242 if (!isa<T>(CanonicalType))
7243 return nullptr;
7244
7245 // If this is a typedef for the type, strip the typedef off without
7246 // losing all typedef information.
7247 return cast<T>(getUnqualifiedDesugaredType());
7248}
7249
7250template <typename T> const T *Type::getAsAdjusted() const {
7251 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
7252
7253 // If this is directly a T type, return it.
7254 if (const auto *Ty = dyn_cast<T>(this))
7255 return Ty;
7256
7257 // If the canonical form of this type isn't the right kind, reject it.
7258 if (!isa<T>(CanonicalType))
7259 return nullptr;
7260
7261 // Strip off type adjustments that do not modify the underlying nature of the
7262 // type.
7263 const Type *Ty = this;
7264 while (Ty) {
7265 if (const auto *A = dyn_cast<AttributedType>(Ty))
7266 Ty = A->getModifiedType().getTypePtr();
7267 else if (const auto *A = dyn_cast<BTFTagAttributedType>(Ty))
7268 Ty = A->getWrappedType().getTypePtr();
7269 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
7270 Ty = E->desugar().getTypePtr();
7271 else if (const auto *P = dyn_cast<ParenType>(Ty))
7272 Ty = P->desugar().getTypePtr();
7273 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
7274 Ty = A->desugar().getTypePtr();
7275 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
7276 Ty = M->desugar().getTypePtr();
7277 else
7278 break;
7279 }
7280
7281 // Just because the canonical type is correct does not mean we can use cast<>,
7282 // since we may not have stripped off all the sugar down to the base type.
7283 return dyn_cast<T>(Ty);
7284}
7285
7286inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
7287 // If this is directly an array type, return it.
7288 if (const auto *arr = dyn_cast<ArrayType>(this))
7289 return arr;
7290
7291 // If the canonical form of this type isn't the right kind, reject it.
7292 if (!isa<ArrayType>(CanonicalType))
7293 return nullptr;
7294
7295 // If this is a typedef for the type, strip the typedef off without
7296 // losing all typedef information.
7297 return cast<ArrayType>(getUnqualifiedDesugaredType());
7298}
7299
7300template <typename T> const T *Type::castAs() const {
7301 static_assert(!TypeIsArrayType<T>::value,
7302 "ArrayType cannot be used with castAs!");
7303
7304 if (const auto *ty = dyn_cast<T>(this)) return ty;
7305 assert(isa<T>(CanonicalType))(static_cast <bool> (isa<T>(CanonicalType)) ? void
(0) : __assert_fail ("isa<T>(CanonicalType)", "clang/include/clang/AST/Type.h"
, 7305, __extension__ __PRETTY_FUNCTION__))
;
7306 return cast<T>(getUnqualifiedDesugaredType());
7307}
7308
7309inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
7310 assert(isa<ArrayType>(CanonicalType))(static_cast <bool> (isa<ArrayType>(CanonicalType
)) ? void (0) : __assert_fail ("isa<ArrayType>(CanonicalType)"
, "clang/include/clang/AST/Type.h", 7310, __extension__ __PRETTY_FUNCTION__
))
;
7311 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
7312 return cast<ArrayType>(getUnqualifiedDesugaredType());
7313}
7314
7315DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
7316 QualType CanonicalPtr)
7317 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
7318#ifndef NDEBUG
7319 QualType Adjusted = getAdjustedType();
7320 (void)AttributedType::stripOuterNullability(Adjusted);
7321 assert(isa<PointerType>(Adjusted))(static_cast <bool> (isa<PointerType>(Adjusted)) ?
void (0) : __assert_fail ("isa<PointerType>(Adjusted)"
, "clang/include/clang/AST/Type.h", 7321, __extension__ __PRETTY_FUNCTION__
))
;
7322#endif
7323}
7324
7325QualType DecayedType::getPointeeType() const {
7326 QualType Decayed = getDecayedType();
7327 (void)AttributedType::stripOuterNullability(Decayed);
7328 return cast<PointerType>(Decayed)->getPointeeType();
7329}
7330
7331// Get the decimal string representation of a fixed point type, represented
7332// as a scaled integer.
7333// TODO: At some point, we should change the arguments to instead just accept an
7334// APFixedPoint instead of APSInt and scale.
7335void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
7336 unsigned Scale);
7337
7338} // namespace clang
7339
7340#endif // LLVM_CLANG_AST_TYPE_H

/build/llvm-toolchain-snapshot-15~++20220320100729+487629cc61b5/llvm/include/llvm/ADT/PointerIntPair.h

1//===- llvm/ADT/PointerIntPair.h - Pair for pointer and int -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file defines the PointerIntPair class.
11///
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_POINTERINTPAIR_H
15#define LLVM_ADT_POINTERINTPAIR_H
16
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/PointerLikeTypeTraits.h"
19#include "llvm/Support/type_traits.h"
20#include <cassert>
21#include <cstdint>
22#include <limits>
23
24namespace llvm {
25
26template <typename T, typename Enable> struct DenseMapInfo;
27template <typename PointerT, unsigned IntBits, typename PtrTraits>
28struct PointerIntPairInfo;
29
30/// PointerIntPair - This class implements a pair of a pointer and small
31/// integer. It is designed to represent this in the space required by one
32/// pointer by bitmangling the integer into the low part of the pointer. This
33/// can only be done for small integers: typically up to 3 bits, but it depends
34/// on the number of bits available according to PointerLikeTypeTraits for the
35/// type.
36///
37/// Note that PointerIntPair always puts the IntVal part in the highest bits
38/// possible. For example, PointerIntPair<void*, 1, bool> will put the bit for
39/// the bool into bit #2, not bit #0, which allows the low two bits to be used
40/// for something else. For example, this allows:
41/// PointerIntPair<PointerIntPair<void*, 1, bool>, 1, bool>
42/// ... and the two bools will land in different bits.
43template <typename PointerTy, unsigned IntBits, typename IntType = unsigned,
44 typename PtrTraits = PointerLikeTypeTraits<PointerTy>,
45 typename Info = PointerIntPairInfo<PointerTy, IntBits, PtrTraits>>
46class PointerIntPair {
47 // Used by MSVC visualizer and generally helpful for debugging/visualizing.
48 using InfoTy = Info;
49 intptr_t Value = 0;
50
51public:
52 constexpr PointerIntPair() = default;
53
54 PointerIntPair(PointerTy PtrVal, IntType IntVal) {
55 setPointerAndInt(PtrVal, IntVal);
56 }
57
58 explicit PointerIntPair(PointerTy PtrVal) { initWithPointer(PtrVal); }
59
60 PointerTy getPointer() const { return Info::getPointer(Value); }
61
62 IntType getInt() const { return (IntType)Info::getInt(Value); }
63
64 void setPointer(PointerTy PtrVal) & {
65 Value = Info::updatePointer(Value, PtrVal);
66 }
67
68 void setInt(IntType IntVal) & {
69 Value = Info::updateInt(Value, static_cast<intptr_t>(IntVal));
70 }
71
72 void initWithPointer(PointerTy PtrVal) & {
73 Value = Info::updatePointer(0, PtrVal);
74 }
75
76 void setPointerAndInt(PointerTy PtrVal, IntType IntVal) & {
77 Value = Info::updateInt(Info::updatePointer(0, PtrVal),
78 static_cast<intptr_t>(IntVal));
79 }
80
81 PointerTy const *getAddrOfPointer() const {
82 return const_cast<PointerIntPair *>(this)->getAddrOfPointer();
83 }
84
85 PointerTy *getAddrOfPointer() {
86 assert(Value == reinterpret_cast<intptr_t>(getPointer()) &&(static_cast <bool> (Value == reinterpret_cast<intptr_t
>(getPointer()) && "Can only return the address if IntBits is cleared and "
"PtrTraits doesn't change the pointer") ? void (0) : __assert_fail
("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "llvm/include/llvm/ADT/PointerIntPair.h", 88, __extension__
__PRETTY_FUNCTION__))
87 "Can only return the address if IntBits is cleared and "(static_cast <bool> (Value == reinterpret_cast<intptr_t
>(getPointer()) && "Can only return the address if IntBits is cleared and "
"PtrTraits doesn't change the pointer") ? void (0) : __assert_fail
("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "llvm/include/llvm/ADT/PointerIntPair.h", 88, __extension__
__PRETTY_FUNCTION__))
88 "PtrTraits doesn't change the pointer")(static_cast <bool> (Value == reinterpret_cast<intptr_t
>(getPointer()) && "Can only return the address if IntBits is cleared and "
"PtrTraits doesn't change the pointer") ? void (0) : __assert_fail
("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "llvm/include/llvm/ADT/PointerIntPair.h", 88, __extension__
__PRETTY_FUNCTION__))
;
89 return reinterpret_cast<PointerTy *>(&Value);
90 }
91
92 void *getOpaqueValue() const { return reinterpret_cast<void *>(Value); }
93
94 void setFromOpaqueValue(void *Val) & {
95 Value = reinterpret_cast<intptr_t>(Val);
96 }
97
98 static PointerIntPair getFromOpaqueValue(void *V) {
99 PointerIntPair P;
100 P.setFromOpaqueValue(V);
101 return P;
102 }
103
104 // Allow PointerIntPairs to be created from const void * if and only if the
105 // pointer type could be created from a const void *.
106 static PointerIntPair getFromOpaqueValue(const void *V) {
107 (void)PtrTraits::getFromVoidPointer(V);
108 return getFromOpaqueValue(const_cast<void *>(V));
109 }
110
111 bool operator==(const PointerIntPair &RHS) const {
112 return Value == RHS.Value;
3
Assuming 'Value' is not equal to 'RHS.Value'
4
Returning zero, which participates in a condition later
113 }
114
115 bool operator!=(const PointerIntPair &RHS) const {
116 return Value != RHS.Value;
117 }
118
119 bool operator<(const PointerIntPair &RHS) const { return Value < RHS.Value; }
120 bool operator>(const PointerIntPair &RHS) const { return Value > RHS.Value; }
121
122 bool operator<=(const PointerIntPair &RHS) const {
123 return Value <= RHS.Value;
124 }
125
126 bool operator>=(const PointerIntPair &RHS) const {
127 return Value >= RHS.Value;
128 }
129};
130
131// Specialize is_trivially_copyable to avoid limitation of llvm::is_trivially_copyable
132// when compiled with gcc 4.9.
133template <typename PointerTy, unsigned IntBits, typename IntType,
134 typename PtrTraits,
135 typename Info>
136struct is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>> : std::true_type {
137#ifdef HAVE_STD_IS_TRIVIALLY_COPYABLE
138 static_assert(std::is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>>::value,
139 "inconsistent behavior between llvm:: and std:: implementation of is_trivially_copyable");
140#endif
141};
142
143
144template <typename PointerT, unsigned IntBits, typename PtrTraits>
145struct PointerIntPairInfo {
146 static_assert(PtrTraits::NumLowBitsAvailable <
147 std::numeric_limits<uintptr_t>::digits,
148 "cannot use a pointer type that has all bits free");
149 static_assert(IntBits <= PtrTraits::NumLowBitsAvailable,
150 "PointerIntPair with integer size too large for pointer");
151 enum MaskAndShiftConstants : uintptr_t {
152 /// PointerBitMask - The bits that come from the pointer.
153 PointerBitMask =
154 ~(uintptr_t)(((intptr_t)1 << PtrTraits::NumLowBitsAvailable) - 1),
155
156 /// IntShift - The number of low bits that we reserve for other uses, and
157 /// keep zero.
158 IntShift = (uintptr_t)PtrTraits::NumLowBitsAvailable - IntBits,
159
160 /// IntMask - This is the unshifted mask for valid bits of the int type.
161 IntMask = (uintptr_t)(((intptr_t)1 << IntBits) - 1),
162
163 // ShiftedIntMask - This is the bits for the integer shifted in place.
164 ShiftedIntMask = (uintptr_t)(IntMask << IntShift)
165 };
166
167 static PointerT getPointer(intptr_t Value) {
168 return PtrTraits::getFromVoidPointer(
169 reinterpret_cast<void *>(Value & PointerBitMask));
170 }
171
172 static intptr_t getInt(intptr_t Value) {
173 return (Value >> IntShift) & IntMask;
174 }
175
176 static intptr_t updatePointer(intptr_t OrigValue, PointerT Ptr) {
177 intptr_t PtrWord =
178 reinterpret_cast<intptr_t>(PtrTraits::getAsVoidPointer(Ptr));
179 assert((PtrWord & ~PointerBitMask) == 0 &&(static_cast <bool> ((PtrWord & ~PointerBitMask) ==
0 && "Pointer is not sufficiently aligned") ? void (
0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "llvm/include/llvm/ADT/PointerIntPair.h", 180, __extension__
__PRETTY_FUNCTION__))
180 "Pointer is not sufficiently aligned")(static_cast <bool> ((PtrWord & ~PointerBitMask) ==
0 && "Pointer is not sufficiently aligned") ? void (
0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "llvm/include/llvm/ADT/PointerIntPair.h", 180, __extension__
__PRETTY_FUNCTION__))
;
181 // Preserve all low bits, just update the pointer.
182 return PtrWord | (OrigValue & ~PointerBitMask);
183 }
184
185 static intptr_t updateInt(intptr_t OrigValue, intptr_t Int) {
186 intptr_t IntWord = static_cast<intptr_t>(Int);
187 assert((IntWord & ~IntMask) == 0 && "Integer too large for field")(static_cast <bool> ((IntWord & ~IntMask) == 0 &&
"Integer too large for field") ? void (0) : __assert_fail ("(IntWord & ~IntMask) == 0 && \"Integer too large for field\""
, "llvm/include/llvm/ADT/PointerIntPair.h", 187, __extension__
__PRETTY_FUNCTION__))
;
188
189 // Preserve all bits other than the ones we are updating.
190 return (OrigValue & ~ShiftedIntMask) | IntWord << IntShift;
191 }
192};
193
194// Provide specialization of DenseMapInfo for PointerIntPair.
195template <typename PointerTy, unsigned IntBits, typename IntType>
196struct DenseMapInfo<PointerIntPair<PointerTy, IntBits, IntType>, void> {
197 using Ty = PointerIntPair<PointerTy, IntBits, IntType>;
198
199 static Ty getEmptyKey() {
200 uintptr_t Val = static_cast<uintptr_t>(-1);
201 Val <<= PointerLikeTypeTraits<Ty>::NumLowBitsAvailable;
202 return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val));
203 }
204
205 static Ty getTombstoneKey() {
206 uintptr_t Val = static_cast<uintptr_t>(-2);
207 Val <<= PointerLikeTypeTraits<PointerTy>::NumLowBitsAvailable;
208 return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val));
209 }
210
211 static unsigned getHashValue(Ty V) {
212 uintptr_t IV = reinterpret_cast<uintptr_t>(V.getOpaqueValue());
213 return unsigned(IV) ^ unsigned(IV >> 9);
214 }
215
216 static bool isEqual(const Ty &LHS, const Ty &RHS) { return LHS == RHS; }
217};
218
219// Teach SmallPtrSet that PointerIntPair is "basically a pointer".
220template <typename PointerTy, unsigned IntBits, typename IntType,
221 typename PtrTraits>
222struct PointerLikeTypeTraits<
223 PointerIntPair<PointerTy, IntBits, IntType, PtrTraits>> {
224 static inline void *
225 getAsVoidPointer(const PointerIntPair<PointerTy, IntBits, IntType> &P) {
226 return P.getOpaqueValue();
227 }
228
229 static inline PointerIntPair<PointerTy, IntBits, IntType>
230 getFromVoidPointer(void *P) {
231 return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
232 }
233
234 static inline PointerIntPair<PointerTy, IntBits, IntType>
235 getFromVoidPointer(const void *P) {
236 return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
237 }
238
239 static constexpr int NumLowBitsAvailable =
240 PtrTraits::NumLowBitsAvailable - IntBits;
241};
242
243} // end namespace llvm
244
245#endif // LLVM_ADT_POINTERINTPAIR_H

/build/llvm-toolchain-snapshot-15~++20220320100729+487629cc61b5/llvm/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
10// and dyn_cast_or_null<X>() templates.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_CASTING_H
15#define LLVM_SUPPORT_CASTING_H
16
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/type_traits.h"
19#include <cassert>
20#include <memory>
21#include <type_traits>
22
23namespace llvm {
24
25//===----------------------------------------------------------------------===//
26// isa<x> Support Templates
27//===----------------------------------------------------------------------===//
28
29// Define a template that can be specialized by smart pointers to reflect the
30// fact that they are automatically dereferenced, and are not involved with the
31// template selection process... the default implementation is a noop.
32//
33template<typename From> struct simplify_type {
34 using SimpleType = From; // The real type this represents...
35
36 // An accessor to get the real value...
37 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
38};
39
40template<typename From> struct simplify_type<const From> {
41 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
42 using SimpleType =
43 typename add_const_past_pointer<NonConstSimpleType>::type;
44 using RetType =
45 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
46
47 static RetType getSimplifiedValue(const From& Val) {
48 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
49 }
50};
51
52// The core of the implementation of isa<X> is here; To and From should be
53// the names of classes. This template can be specialized to customize the
54// implementation of isa<> without rewriting it from scratch.
55template <typename To, typename From, typename Enabler = void>
56struct isa_impl {
57 static inline bool doit(const From &Val) {
58 return To::classof(&Val);
59 }
60};
61
62/// Always allow upcasts, and perform no dynamic check for them.
63template <typename To, typename From>
64struct isa_impl<To, From, std::enable_if_t<std::is_base_of<To, From>::value>> {
65 static inline bool doit(const From &) { return true; }
66};
67
68template <typename To, typename From> struct isa_impl_cl {
69 static inline bool doit(const From &Val) {
70 return isa_impl<To, From>::doit(Val);
71 }
72};
73
74template <typename To, typename From> struct isa_impl_cl<To, const From> {
75 static inline bool doit(const From &Val) {
76 return isa_impl<To, From>::doit(Val);
77 }
78};
79
80template <typename To, typename From>
81struct isa_impl_cl<To, const std::unique_ptr<From>> {
82 static inline bool doit(const std::unique_ptr<From> &Val) {
83 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 83, __extension__ __PRETTY_FUNCTION__
))
;
84 return isa_impl_cl<To, From>::doit(*Val);
85 }
86};
87
88template <typename To, typename From> struct isa_impl_cl<To, From*> {
89 static inline bool doit(const From *Val) {
90 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 90, __extension__ __PRETTY_FUNCTION__
))
;
91 return isa_impl<To, From>::doit(*Val);
92 }
93};
94
95template <typename To, typename From> struct isa_impl_cl<To, From*const> {
96 static inline bool doit(const From *Val) {
97 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 97, __extension__ __PRETTY_FUNCTION__
))
;
98 return isa_impl<To, From>::doit(*Val);
99 }
100};
101
102template <typename To, typename From> struct isa_impl_cl<To, const From*> {
103 static inline bool doit(const From *Val) {
104 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 104, __extension__ __PRETTY_FUNCTION__
))
;
105 return isa_impl<To, From>::doit(*Val);
106 }
107};
108
109template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
110 static inline bool doit(const From *Val) {
111 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 111, __extension__ __PRETTY_FUNCTION__
))
;
112 return isa_impl<To, From>::doit(*Val);
113 }
114};
115
116template<typename To, typename From, typename SimpleFrom>
117struct isa_impl_wrap {
118 // When From != SimplifiedType, we can simplify the type some more by using
119 // the simplify_type template.
120 static bool doit(const From &Val) {
121 return isa_impl_wrap<To, SimpleFrom,
122 typename simplify_type<SimpleFrom>::SimpleType>::doit(
123 simplify_type<const From>::getSimplifiedValue(Val));
124 }
125};
126
127template<typename To, typename FromTy>
128struct isa_impl_wrap<To, FromTy, FromTy> {
129 // When From == SimpleType, we are as simple as we are going to get.
130 static bool doit(const FromTy &Val) {
131 return isa_impl_cl<To,FromTy>::doit(Val);
132 }
133};
134
135// isa<X> - Return true if the parameter to the template is an instance of one
136// of the template type arguments. Used like this:
137//
138// if (isa<Type>(myVal)) { ... }
139// if (isa<Type0, Type1, Type2>(myVal)) { ... }
140//
141template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
142 return isa_impl_wrap<X, const Y,
143 typename simplify_type<const Y>::SimpleType>::doit(Val);
144}
145
146template <typename First, typename Second, typename... Rest, typename Y>
147LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
148 return isa<First>(Val) || isa<Second, Rest...>(Val);
149}
150
151// isa_and_nonnull<X> - Functionally identical to isa, except that a null value
152// is accepted.
153//
154template <typename... X, class Y>
155LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa_and_nonnull(const Y &Val) {
156 if (!Val)
157 return false;
158 return isa<X...>(Val);
159}
160
161//===----------------------------------------------------------------------===//
162// cast<x> Support Templates
163//===----------------------------------------------------------------------===//
164
165template<class To, class From> struct cast_retty;
166
167// Calculate what type the 'cast' function should return, based on a requested
168// type of To and a source type of From.
169template<class To, class From> struct cast_retty_impl {
170 using ret_type = To &; // Normal case, return Ty&
171};
172template<class To, class From> struct cast_retty_impl<To, const From> {
173 using ret_type = const To &; // Normal case, return Ty&
174};
175
176template<class To, class From> struct cast_retty_impl<To, From*> {
177 using ret_type = To *; // Pointer arg case, return Ty*
178};
179
180template<class To, class From> struct cast_retty_impl<To, const From*> {
181 using ret_type = const To *; // Constant pointer arg case, return const Ty*
182};
183
184template<class To, class From> struct cast_retty_impl<To, const From*const> {
185 using ret_type = const To *; // Constant pointer arg case, return const Ty*
186};
187
188template <class To, class From>
189struct cast_retty_impl<To, std::unique_ptr<From>> {
190private:
191 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
192 using ResultType = std::remove_pointer_t<PointerType>;
193
194public:
195 using ret_type = std::unique_ptr<ResultType>;
196};
197
198template<class To, class From, class SimpleFrom>
199struct cast_retty_wrap {
200 // When the simplified type and the from type are not the same, use the type
201 // simplifier to reduce the type, then reuse cast_retty_impl to get the
202 // resultant type.
203 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
204};
205
206template<class To, class FromTy>
207struct cast_retty_wrap<To, FromTy, FromTy> {
208 // When the simplified type is equal to the from type, use it directly.
209 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
210};
211
212template<class To, class From>
213struct cast_retty {
214 using ret_type = typename cast_retty_wrap<
215 To, From, typename simplify_type<From>::SimpleType>::ret_type;
216};
217
218// Ensure the non-simple values are converted using the simplify_type template
219// that may be specialized by smart pointers...
220//
221template<class To, class From, class SimpleFrom> struct cast_convert_val {
222 // This is not a simple type, use the template to simplify it...
223 static typename cast_retty<To, From>::ret_type doit(From &Val) {
224 return cast_convert_val<To, SimpleFrom,
225 typename simplify_type<SimpleFrom>::SimpleType>::doit(
226 simplify_type<From>::getSimplifiedValue(Val));
227 }
228};
229
230template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
231 // This _is_ a simple type, just cast it.
232 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
233 typename cast_retty<To, FromTy>::ret_type Res2
234 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
235 return Res2;
236 }
237};
238
239template <class X> struct is_simple_type {
240 static const bool value =
241 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
242};
243
244// cast<X> - Return the argument parameter cast to the specified type. This
245// casting operator asserts that the type is correct, so it does not return null
246// on failure. It does not allow a null argument (use cast_or_null for that).
247// It is typically used like this:
248//
249// cast<Instruction>(myVal)->getParent()
250//
251template <class X, class Y>
252inline std::enable_if_t<!is_simple_type<Y>::value,
253 typename cast_retty<X, const Y>::ret_type>
254cast(const Y &Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 255, __extension__ __PRETTY_FUNCTION__
))
;
256 return cast_convert_val<
257 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
262 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 262, __extension__ __PRETTY_FUNCTION__
))
;
263 return cast_convert_val<X, Y,
264 typename simplify_type<Y>::SimpleType>::doit(Val);
265}
266
267template <class X, class Y>
268inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
269 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 269, __extension__ __PRETTY_FUNCTION__
))
;
270 return cast_convert_val<X, Y*,
271 typename simplify_type<Y*>::SimpleType>::doit(Val);
272}
273
274template <class X, class Y>
275inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
276cast(std::unique_ptr<Y> &&Val) {
277 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val.get()) &&
"cast<Ty>() argument of incompatible type!") ? void (0
) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 277, __extension__ __PRETTY_FUNCTION__
))
;
278 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
279 return ret_type(
280 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
281 Val.release()));
282}
283
284// cast_or_null<X> - Functionally identical to cast, except that a null value is
285// accepted.
286//
287template <class X, class Y>
288LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
289 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
290cast_or_null(const Y &Val) {
291 if (!Val)
292 return nullptr;
293 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 293, __extension__ __PRETTY_FUNCTION__
))
;
294 return cast<X>(Val);
295}
296
297template <class X, class Y>
298LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value,
299 typename cast_retty<X, Y>::ret_type>
300cast_or_null(Y &Val) {
301 if (!Val)
302 return nullptr;
303 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 303, __extension__ __PRETTY_FUNCTION__
))
;
304 return cast<X>(Val);
305}
306
307template <class X, class Y>
308LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
309cast_or_null(Y *Val) {
310 if (!Val) return nullptr;
311 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 311, __extension__ __PRETTY_FUNCTION__
))
;
312 return cast<X>(Val);
313}
314
315template <class X, class Y>
316inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
317cast_or_null(std::unique_ptr<Y> &&Val) {
318 if (!Val)
319 return nullptr;
320 return cast<X>(std::move(Val));
321}
322
323// dyn_cast<X> - Return the argument parameter cast to the specified type. This
324// casting operator returns null if the argument is of the wrong type, so it can
325// be used to test for a type as well as cast if successful. This should be
326// used in the context of an if statement like this:
327//
328// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
329//
330
331template <class X, class Y>
332LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
333 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
334dyn_cast(const Y &Val) {
335 return isa<X>(Val) ? cast<X>(Val) : nullptr;
336}
337
338template <class X, class Y>
339LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
340 return isa<X>(Val) ? cast<X>(Val) : nullptr;
10
Assuming 'Val' is not a 'AtomicType'
11
'?' condition is false
12
Returning null pointer, which participates in a condition later
48
Assuming 'Val' is not a 'PointerType'
49
'?' condition is false
50
Returning null pointer, which participates in a condition later
341}
342
343template <class X, class Y>
344LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
345 return isa<X>(Val) ? cast<X>(Val) : nullptr;
346}
347
348// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
349// value is accepted.
350//
351template <class X, class Y>
352LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
353 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
354dyn_cast_or_null(const Y &Val) {
355 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
356}
357
358template <class X, class Y>
359LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value,
360 typename cast_retty<X, Y>::ret_type>
361dyn_cast_or_null(Y &Val) {
362 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
363}
364
365template <class X, class Y>
366LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
367dyn_cast_or_null(Y *Val) {
368 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
369}
370
371// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
372// taking ownership of the input pointer iff isa<X>(Val) is true. If the
373// cast is successful, From refers to nullptr on exit and the casted value
374// is returned. If the cast is unsuccessful, the function returns nullptr
375// and From is unchanged.
376template <class X, class Y>
377LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
378 -> decltype(cast<X>(Val)) {
379 if (!isa<X>(Val))
380 return nullptr;
381 return cast<X>(std::move(Val));
382}
383
384template <class X, class Y>
385LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) {
386 return unique_dyn_cast<X, Y>(Val);
387}
388
389// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
390// a null value is accepted.
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
393 -> decltype(cast<X>(Val)) {
394 if (!Val)
395 return nullptr;
396 return unique_dyn_cast<X, Y>(Val);
397}
398
399template <class X, class Y>
400LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) {
401 return unique_dyn_cast_or_null<X, Y>(Val);
402}
403
404} // end namespace llvm
405
406#endif // LLVM_SUPPORT_CASTING_H