Bug Summary

File:src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaExpr.cpp
Warning:line 10188, column 46
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaExpr.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSema/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libclangSema/obj/../include/clang/Sema -I /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/include -I /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libclangSema/../include -I /usr/src/gnu/usr.bin/clang/libclangSema/obj -I /usr/src/gnu/usr.bin/clang/libclangSema/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSema/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaExpr.cpp

/usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaExpr.cpp

1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "UsedDeclVisitor.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExprOpenMP.h"
27#include "clang/AST/OperationKinds.h"
28#include "clang/AST/RecursiveASTVisitor.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/Basic/Builtins.h"
31#include "clang/Basic/PartialDiagnostic.h"
32#include "clang/Basic/SourceManager.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Lex/LiteralSupport.h"
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Sema/AnalysisBasedWarnings.h"
37#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/DelayedDiagnostic.h"
39#include "clang/Sema/Designator.h"
40#include "clang/Sema/Initialization.h"
41#include "clang/Sema/Lookup.h"
42#include "clang/Sema/Overload.h"
43#include "clang/Sema/ParsedTemplate.h"
44#include "clang/Sema/Scope.h"
45#include "clang/Sema/ScopeInfo.h"
46#include "clang/Sema/SemaFixItUtils.h"
47#include "clang/Sema/SemaInternal.h"
48#include "clang/Sema/Template.h"
49#include "llvm/ADT/STLExtras.h"
50#include "llvm/ADT/StringExtras.h"
51#include "llvm/Support/ConvertUTF.h"
52#include "llvm/Support/SaveAndRestore.h"
53
54using namespace clang;
55using namespace sema;
56using llvm::RoundingMode;
57
58/// Determine whether the use of this declaration is valid, without
59/// emitting diagnostics.
60bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
61 // See if this is an auto-typed variable whose initializer we are parsing.
62 if (ParsingInitForAutoVars.count(D))
63 return false;
64
65 // See if this is a deleted function.
66 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
67 if (FD->isDeleted())
68 return false;
69
70 // If the function has a deduced return type, and we can't deduce it,
71 // then we can't use it either.
72 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
73 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
74 return false;
75
76 // See if this is an aligned allocation/deallocation function that is
77 // unavailable.
78 if (TreatUnavailableAsInvalid &&
79 isUnavailableAlignedAllocationFunction(*FD))
80 return false;
81 }
82
83 // See if this function is unavailable.
84 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
85 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
86 return false;
87
88 if (isa<UnresolvedUsingIfExistsDecl>(D))
89 return false;
90
91 return true;
92}
93
94static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
95 // Warn if this is used but marked unused.
96 if (const auto *A = D->getAttr<UnusedAttr>()) {
97 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
98 // should diagnose them.
99 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
100 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
101 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
102 if (DC && !DC->hasAttr<UnusedAttr>())
103 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
104 }
105 }
106}
107
108/// Emit a note explaining that this function is deleted.
109void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
110 assert(Decl && Decl->isDeleted())((void)0);
111
112 if (Decl->isDefaulted()) {
113 // If the method was explicitly defaulted, point at that declaration.
114 if (!Decl->isImplicit())
115 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
116
117 // Try to diagnose why this special member function was implicitly
118 // deleted. This might fail, if that reason no longer applies.
119 DiagnoseDeletedDefaultedFunction(Decl);
120 return;
121 }
122
123 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
124 if (Ctor && Ctor->isInheritingConstructor())
125 return NoteDeletedInheritingConstructor(Ctor);
126
127 Diag(Decl->getLocation(), diag::note_availability_specified_here)
128 << Decl << 1;
129}
130
131/// Determine whether a FunctionDecl was ever declared with an
132/// explicit storage class.
133static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
134 for (auto I : D->redecls()) {
135 if (I->getStorageClass() != SC_None)
136 return true;
137 }
138 return false;
139}
140
141/// Check whether we're in an extern inline function and referring to a
142/// variable or function with internal linkage (C11 6.7.4p3).
143///
144/// This is only a warning because we used to silently accept this code, but
145/// in many cases it will not behave correctly. This is not enabled in C++ mode
146/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
147/// and so while there may still be user mistakes, most of the time we can't
148/// prove that there are errors.
149static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
150 const NamedDecl *D,
151 SourceLocation Loc) {
152 // This is disabled under C++; there are too many ways for this to fire in
153 // contexts where the warning is a false positive, or where it is technically
154 // correct but benign.
155 if (S.getLangOpts().CPlusPlus)
156 return;
157
158 // Check if this is an inlined function or method.
159 FunctionDecl *Current = S.getCurFunctionDecl();
160 if (!Current)
161 return;
162 if (!Current->isInlined())
163 return;
164 if (!Current->isExternallyVisible())
165 return;
166
167 // Check if the decl has internal linkage.
168 if (D->getFormalLinkage() != InternalLinkage)
169 return;
170
171 // Downgrade from ExtWarn to Extension if
172 // (1) the supposedly external inline function is in the main file,
173 // and probably won't be included anywhere else.
174 // (2) the thing we're referencing is a pure function.
175 // (3) the thing we're referencing is another inline function.
176 // This last can give us false negatives, but it's better than warning on
177 // wrappers for simple C library functions.
178 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
179 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
180 if (!DowngradeWarning && UsedFn)
181 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
182
183 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
184 : diag::ext_internal_in_extern_inline)
185 << /*IsVar=*/!UsedFn << D;
186
187 S.MaybeSuggestAddingStaticToDecl(Current);
188
189 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
190 << D;
191}
192
193void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
194 const FunctionDecl *First = Cur->getFirstDecl();
195
196 // Suggest "static" on the function, if possible.
197 if (!hasAnyExplicitStorageClass(First)) {
198 SourceLocation DeclBegin = First->getSourceRange().getBegin();
199 Diag(DeclBegin, diag::note_convert_inline_to_static)
200 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
201 }
202}
203
204/// Determine whether the use of this declaration is valid, and
205/// emit any corresponding diagnostics.
206///
207/// This routine diagnoses various problems with referencing
208/// declarations that can occur when using a declaration. For example,
209/// it might warn if a deprecated or unavailable declaration is being
210/// used, or produce an error (and return true) if a C++0x deleted
211/// function is being used.
212///
213/// \returns true if there was an error (this declaration cannot be
214/// referenced), false otherwise.
215///
216bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
217 const ObjCInterfaceDecl *UnknownObjCClass,
218 bool ObjCPropertyAccess,
219 bool AvoidPartialAvailabilityChecks,
220 ObjCInterfaceDecl *ClassReceiver) {
221 SourceLocation Loc = Locs.front();
222 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
223 // If there were any diagnostics suppressed by template argument deduction,
224 // emit them now.
225 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
226 if (Pos != SuppressedDiagnostics.end()) {
227 for (const PartialDiagnosticAt &Suppressed : Pos->second)
228 Diag(Suppressed.first, Suppressed.second);
229
230 // Clear out the list of suppressed diagnostics, so that we don't emit
231 // them again for this specialization. However, we don't obsolete this
232 // entry from the table, because we want to avoid ever emitting these
233 // diagnostics again.
234 Pos->second.clear();
235 }
236
237 // C++ [basic.start.main]p3:
238 // The function 'main' shall not be used within a program.
239 if (cast<FunctionDecl>(D)->isMain())
240 Diag(Loc, diag::ext_main_used);
241
242 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
243 }
244
245 // See if this is an auto-typed variable whose initializer we are parsing.
246 if (ParsingInitForAutoVars.count(D)) {
247 if (isa<BindingDecl>(D)) {
248 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
249 << D->getDeclName();
250 } else {
251 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
252 << D->getDeclName() << cast<VarDecl>(D)->getType();
253 }
254 return true;
255 }
256
257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
258 // See if this is a deleted function.
259 if (FD->isDeleted()) {
260 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
261 if (Ctor && Ctor->isInheritingConstructor())
262 Diag(Loc, diag::err_deleted_inherited_ctor_use)
263 << Ctor->getParent()
264 << Ctor->getInheritedConstructor().getConstructor()->getParent();
265 else
266 Diag(Loc, diag::err_deleted_function_use);
267 NoteDeletedFunction(FD);
268 return true;
269 }
270
271 // [expr.prim.id]p4
272 // A program that refers explicitly or implicitly to a function with a
273 // trailing requires-clause whose constraint-expression is not satisfied,
274 // other than to declare it, is ill-formed. [...]
275 //
276 // See if this is a function with constraints that need to be satisfied.
277 // Check this before deducing the return type, as it might instantiate the
278 // definition.
279 if (FD->getTrailingRequiresClause()) {
280 ConstraintSatisfaction Satisfaction;
281 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
282 // A diagnostic will have already been generated (non-constant
283 // constraint expression, for example)
284 return true;
285 if (!Satisfaction.IsSatisfied) {
286 Diag(Loc,
287 diag::err_reference_to_function_with_unsatisfied_constraints)
288 << D;
289 DiagnoseUnsatisfiedConstraint(Satisfaction);
290 return true;
291 }
292 }
293
294 // If the function has a deduced return type, and we can't deduce it,
295 // then we can't use it either.
296 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
297 DeduceReturnType(FD, Loc))
298 return true;
299
300 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
301 return true;
302
303 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
304 return true;
305 }
306
307 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
308 // Lambdas are only default-constructible or assignable in C++2a onwards.
309 if (MD->getParent()->isLambda() &&
310 ((isa<CXXConstructorDecl>(MD) &&
311 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
312 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
313 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
314 << !isa<CXXConstructorDecl>(MD);
315 }
316 }
317
318 auto getReferencedObjCProp = [](const NamedDecl *D) ->
319 const ObjCPropertyDecl * {
320 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
321 return MD->findPropertyDecl();
322 return nullptr;
323 };
324 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
325 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
326 return true;
327 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
328 return true;
329 }
330
331 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
332 // Only the variables omp_in and omp_out are allowed in the combiner.
333 // Only the variables omp_priv and omp_orig are allowed in the
334 // initializer-clause.
335 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
336 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
337 isa<VarDecl>(D)) {
338 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
339 << getCurFunction()->HasOMPDeclareReductionCombiner;
340 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
341 return true;
342 }
343
344 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
345 // List-items in map clauses on this construct may only refer to the declared
346 // variable var and entities that could be referenced by a procedure defined
347 // at the same location
348 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
349 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
350 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
351 << getOpenMPDeclareMapperVarName();
352 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
353 return true;
354 }
355
356 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
357 Diag(Loc, diag::err_use_of_empty_using_if_exists);
358 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
359 return true;
360 }
361
362 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
363 AvoidPartialAvailabilityChecks, ClassReceiver);
364
365 DiagnoseUnusedOfDecl(*this, D, Loc);
366
367 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
368
369 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
370 if (auto *VD = dyn_cast<ValueDecl>(D))
371 checkDeviceDecl(VD, Loc);
372
373 if (!Context.getTargetInfo().isTLSSupported())
374 if (const auto *VD = dyn_cast<VarDecl>(D))
375 if (VD->getTLSKind() != VarDecl::TLS_None)
376 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
377 }
378
379 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
380 !isUnevaluatedContext()) {
381 // C++ [expr.prim.req.nested] p3
382 // A local parameter shall only appear as an unevaluated operand
383 // (Clause 8) within the constraint-expression.
384 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
385 << D;
386 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
387 return true;
388 }
389
390 return false;
391}
392
393/// DiagnoseSentinelCalls - This routine checks whether a call or
394/// message-send is to a declaration with the sentinel attribute, and
395/// if so, it checks that the requirements of the sentinel are
396/// satisfied.
397void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
398 ArrayRef<Expr *> Args) {
399 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
400 if (!attr)
401 return;
402
403 // The number of formal parameters of the declaration.
404 unsigned numFormalParams;
405
406 // The kind of declaration. This is also an index into a %select in
407 // the diagnostic.
408 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
409
410 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
411 numFormalParams = MD->param_size();
412 calleeType = CT_Method;
413 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
414 numFormalParams = FD->param_size();
415 calleeType = CT_Function;
416 } else if (isa<VarDecl>(D)) {
417 QualType type = cast<ValueDecl>(D)->getType();
418 const FunctionType *fn = nullptr;
419 if (const PointerType *ptr = type->getAs<PointerType>()) {
420 fn = ptr->getPointeeType()->getAs<FunctionType>();
421 if (!fn) return;
422 calleeType = CT_Function;
423 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
424 fn = ptr->getPointeeType()->castAs<FunctionType>();
425 calleeType = CT_Block;
426 } else {
427 return;
428 }
429
430 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
431 numFormalParams = proto->getNumParams();
432 } else {
433 numFormalParams = 0;
434 }
435 } else {
436 return;
437 }
438
439 // "nullPos" is the number of formal parameters at the end which
440 // effectively count as part of the variadic arguments. This is
441 // useful if you would prefer to not have *any* formal parameters,
442 // but the language forces you to have at least one.
443 unsigned nullPos = attr->getNullPos();
444 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")((void)0);
445 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
446
447 // The number of arguments which should follow the sentinel.
448 unsigned numArgsAfterSentinel = attr->getSentinel();
449
450 // If there aren't enough arguments for all the formal parameters,
451 // the sentinel, and the args after the sentinel, complain.
452 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
453 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
454 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
455 return;
456 }
457
458 // Otherwise, find the sentinel expression.
459 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
460 if (!sentinelExpr) return;
461 if (sentinelExpr->isValueDependent()) return;
462 if (Context.isSentinelNullExpr(sentinelExpr)) return;
463
464 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
465 // or 'NULL' if those are actually defined in the context. Only use
466 // 'nil' for ObjC methods, where it's much more likely that the
467 // variadic arguments form a list of object pointers.
468 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
469 std::string NullValue;
470 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
471 NullValue = "nil";
472 else if (getLangOpts().CPlusPlus11)
473 NullValue = "nullptr";
474 else if (PP.isMacroDefined("NULL"))
475 NullValue = "NULL";
476 else
477 NullValue = "(void*) 0";
478
479 if (MissingNilLoc.isInvalid())
480 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
481 else
482 Diag(MissingNilLoc, diag::warn_missing_sentinel)
483 << int(calleeType)
484 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
485 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
486}
487
488SourceRange Sema::getExprRange(Expr *E) const {
489 return E ? E->getSourceRange() : SourceRange();
490}
491
492//===----------------------------------------------------------------------===//
493// Standard Promotions and Conversions
494//===----------------------------------------------------------------------===//
495
496/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
497ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
498 // Handle any placeholder expressions which made it here.
499 if (E->getType()->isPlaceholderType()) {
500 ExprResult result = CheckPlaceholderExpr(E);
501 if (result.isInvalid()) return ExprError();
502 E = result.get();
503 }
504
505 QualType Ty = E->getType();
506 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")((void)0);
507
508 if (Ty->isFunctionType()) {
509 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
510 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
511 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
512 return ExprError();
513
514 E = ImpCastExprToType(E, Context.getPointerType(Ty),
515 CK_FunctionToPointerDecay).get();
516 } else if (Ty->isArrayType()) {
517 // In C90 mode, arrays only promote to pointers if the array expression is
518 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
519 // type 'array of type' is converted to an expression that has type 'pointer
520 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
521 // that has type 'array of type' ...". The relevant change is "an lvalue"
522 // (C90) to "an expression" (C99).
523 //
524 // C++ 4.2p1:
525 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
526 // T" can be converted to an rvalue of type "pointer to T".
527 //
528 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
529 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
530 CK_ArrayToPointerDecay);
531 if (Res.isInvalid())
532 return ExprError();
533 E = Res.get();
534 }
535 }
536 return E;
537}
538
539static void CheckForNullPointerDereference(Sema &S, Expr *E) {
540 // Check to see if we are dereferencing a null pointer. If so,
541 // and if not volatile-qualified, this is undefined behavior that the
542 // optimizer will delete, so warn about it. People sometimes try to use this
543 // to get a deterministic trap and are surprised by clang's behavior. This
544 // only handles the pattern "*null", which is a very syntactic check.
545 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
546 if (UO && UO->getOpcode() == UO_Deref &&
547 UO->getSubExpr()->getType()->isPointerType()) {
548 const LangAS AS =
549 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
550 if ((!isTargetAddressSpace(AS) ||
551 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
552 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
553 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
554 !UO->getType().isVolatileQualified()) {
555 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
556 S.PDiag(diag::warn_indirection_through_null)
557 << UO->getSubExpr()->getSourceRange());
558 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
559 S.PDiag(diag::note_indirection_through_null));
560 }
561 }
562}
563
564static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
565 SourceLocation AssignLoc,
566 const Expr* RHS) {
567 const ObjCIvarDecl *IV = OIRE->getDecl();
568 if (!IV)
569 return;
570
571 DeclarationName MemberName = IV->getDeclName();
572 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
573 if (!Member || !Member->isStr("isa"))
574 return;
575
576 const Expr *Base = OIRE->getBase();
577 QualType BaseType = Base->getType();
578 if (OIRE->isArrow())
579 BaseType = BaseType->getPointeeType();
580 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
581 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
582 ObjCInterfaceDecl *ClassDeclared = nullptr;
583 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
584 if (!ClassDeclared->getSuperClass()
585 && (*ClassDeclared->ivar_begin()) == IV) {
586 if (RHS) {
587 NamedDecl *ObjectSetClass =
588 S.LookupSingleName(S.TUScope,
589 &S.Context.Idents.get("object_setClass"),
590 SourceLocation(), S.LookupOrdinaryName);
591 if (ObjectSetClass) {
592 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
595 "object_setClass(")
596 << FixItHint::CreateReplacement(
597 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
598 << FixItHint::CreateInsertion(RHSLocEnd, ")");
599 }
600 else
601 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
602 } else {
603 NamedDecl *ObjectGetClass =
604 S.LookupSingleName(S.TUScope,
605 &S.Context.Idents.get("object_getClass"),
606 SourceLocation(), S.LookupOrdinaryName);
607 if (ObjectGetClass)
608 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
609 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
610 "object_getClass(")
611 << FixItHint::CreateReplacement(
612 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
613 else
614 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
615 }
616 S.Diag(IV->getLocation(), diag::note_ivar_decl);
617 }
618 }
619}
620
621ExprResult Sema::DefaultLvalueConversion(Expr *E) {
622 // Handle any placeholder expressions which made it here.
623 if (E->getType()->isPlaceholderType()) {
624 ExprResult result = CheckPlaceholderExpr(E);
625 if (result.isInvalid()) return ExprError();
626 E = result.get();
627 }
628
629 // C++ [conv.lval]p1:
630 // A glvalue of a non-function, non-array type T can be
631 // converted to a prvalue.
632 if (!E->isGLValue()) return E;
633
634 QualType T = E->getType();
635 assert(!T.isNull() && "r-value conversion on typeless expression?")((void)0);
636
637 // lvalue-to-rvalue conversion cannot be applied to function or array types.
638 if (T->isFunctionType() || T->isArrayType())
639 return E;
640
641 // We don't want to throw lvalue-to-rvalue casts on top of
642 // expressions of certain types in C++.
643 if (getLangOpts().CPlusPlus &&
644 (E->getType() == Context.OverloadTy ||
645 T->isDependentType() ||
646 T->isRecordType()))
647 return E;
648
649 // The C standard is actually really unclear on this point, and
650 // DR106 tells us what the result should be but not why. It's
651 // generally best to say that void types just doesn't undergo
652 // lvalue-to-rvalue at all. Note that expressions of unqualified
653 // 'void' type are never l-values, but qualified void can be.
654 if (T->isVoidType())
655 return E;
656
657 // OpenCL usually rejects direct accesses to values of 'half' type.
658 if (getLangOpts().OpenCL &&
659 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
660 T->isHalfType()) {
661 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
662 << 0 << T;
663 return ExprError();
664 }
665
666 CheckForNullPointerDereference(*this, E);
667 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
668 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
669 &Context.Idents.get("object_getClass"),
670 SourceLocation(), LookupOrdinaryName);
671 if (ObjectGetClass)
672 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
673 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
674 << FixItHint::CreateReplacement(
675 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
676 else
677 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
678 }
679 else if (const ObjCIvarRefExpr *OIRE =
680 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
681 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
682
683 // C++ [conv.lval]p1:
684 // [...] If T is a non-class type, the type of the prvalue is the
685 // cv-unqualified version of T. Otherwise, the type of the
686 // rvalue is T.
687 //
688 // C99 6.3.2.1p2:
689 // If the lvalue has qualified type, the value has the unqualified
690 // version of the type of the lvalue; otherwise, the value has the
691 // type of the lvalue.
692 if (T.hasQualifiers())
693 T = T.getUnqualifiedType();
694
695 // Under the MS ABI, lock down the inheritance model now.
696 if (T->isMemberPointerType() &&
697 Context.getTargetInfo().getCXXABI().isMicrosoft())
698 (void)isCompleteType(E->getExprLoc(), T);
699
700 ExprResult Res = CheckLValueToRValueConversionOperand(E);
701 if (Res.isInvalid())
702 return Res;
703 E = Res.get();
704
705 // Loading a __weak object implicitly retains the value, so we need a cleanup to
706 // balance that.
707 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
708 Cleanup.setExprNeedsCleanups(true);
709
710 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
711 Cleanup.setExprNeedsCleanups(true);
712
713 // C++ [conv.lval]p3:
714 // If T is cv std::nullptr_t, the result is a null pointer constant.
715 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
716 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
717 CurFPFeatureOverrides());
718
719 // C11 6.3.2.1p2:
720 // ... if the lvalue has atomic type, the value has the non-atomic version
721 // of the type of the lvalue ...
722 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
723 T = Atomic->getValueType().getUnqualifiedType();
724 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
725 nullptr, VK_PRValue, FPOptionsOverride());
726 }
727
728 return Res;
729}
730
731ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
732 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
733 if (Res.isInvalid())
734 return ExprError();
735 Res = DefaultLvalueConversion(Res.get());
736 if (Res.isInvalid())
737 return ExprError();
738 return Res;
739}
740
741/// CallExprUnaryConversions - a special case of an unary conversion
742/// performed on a function designator of a call expression.
743ExprResult Sema::CallExprUnaryConversions(Expr *E) {
744 QualType Ty = E->getType();
745 ExprResult Res = E;
746 // Only do implicit cast for a function type, but not for a pointer
747 // to function type.
748 if (Ty->isFunctionType()) {
749 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
750 CK_FunctionToPointerDecay);
751 if (Res.isInvalid())
752 return ExprError();
753 }
754 Res = DefaultLvalueConversion(Res.get());
755 if (Res.isInvalid())
756 return ExprError();
757 return Res.get();
758}
759
760/// UsualUnaryConversions - Performs various conversions that are common to most
761/// operators (C99 6.3). The conversions of array and function types are
762/// sometimes suppressed. For example, the array->pointer conversion doesn't
763/// apply if the array is an argument to the sizeof or address (&) operators.
764/// In these instances, this routine should *not* be called.
765ExprResult Sema::UsualUnaryConversions(Expr *E) {
766 // First, convert to an r-value.
767 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
768 if (Res.isInvalid())
769 return ExprError();
770 E = Res.get();
771
772 QualType Ty = E->getType();
773 assert(!Ty.isNull() && "UsualUnaryConversions - missing type")((void)0);
774
775 // Half FP have to be promoted to float unless it is natively supported
776 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
777 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
778
779 // Try to perform integral promotions if the object has a theoretically
780 // promotable type.
781 if (Ty->isIntegralOrUnscopedEnumerationType()) {
782 // C99 6.3.1.1p2:
783 //
784 // The following may be used in an expression wherever an int or
785 // unsigned int may be used:
786 // - an object or expression with an integer type whose integer
787 // conversion rank is less than or equal to the rank of int
788 // and unsigned int.
789 // - A bit-field of type _Bool, int, signed int, or unsigned int.
790 //
791 // If an int can represent all values of the original type, the
792 // value is converted to an int; otherwise, it is converted to an
793 // unsigned int. These are called the integer promotions. All
794 // other types are unchanged by the integer promotions.
795
796 QualType PTy = Context.isPromotableBitField(E);
797 if (!PTy.isNull()) {
798 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
799 return E;
800 }
801 if (Ty->isPromotableIntegerType()) {
802 QualType PT = Context.getPromotedIntegerType(Ty);
803 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
804 return E;
805 }
806 }
807 return E;
808}
809
810/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
811/// do not have a prototype. Arguments that have type float or __fp16
812/// are promoted to double. All other argument types are converted by
813/// UsualUnaryConversions().
814ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
815 QualType Ty = E->getType();
816 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")((void)0);
817
818 ExprResult Res = UsualUnaryConversions(E);
819 if (Res.isInvalid())
820 return ExprError();
821 E = Res.get();
822
823 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
824 // promote to double.
825 // Note that default argument promotion applies only to float (and
826 // half/fp16); it does not apply to _Float16.
827 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
828 if (BTy && (BTy->getKind() == BuiltinType::Half ||
829 BTy->getKind() == BuiltinType::Float)) {
830 if (getLangOpts().OpenCL &&
831 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
832 if (BTy->getKind() == BuiltinType::Half) {
833 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
834 }
835 } else {
836 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
837 }
838 }
839 if (BTy &&
840 getLangOpts().getExtendIntArgs() ==
841 LangOptions::ExtendArgsKind::ExtendTo64 &&
842 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
843 Context.getTypeSizeInChars(BTy) <
844 Context.getTypeSizeInChars(Context.LongLongTy)) {
845 E = (Ty->isUnsignedIntegerType())
846 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
847 .get()
848 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
849 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&((void)0)
850 "Unexpected typesize for LongLongTy")((void)0);
851 }
852
853 // C++ performs lvalue-to-rvalue conversion as a default argument
854 // promotion, even on class types, but note:
855 // C++11 [conv.lval]p2:
856 // When an lvalue-to-rvalue conversion occurs in an unevaluated
857 // operand or a subexpression thereof the value contained in the
858 // referenced object is not accessed. Otherwise, if the glvalue
859 // has a class type, the conversion copy-initializes a temporary
860 // of type T from the glvalue and the result of the conversion
861 // is a prvalue for the temporary.
862 // FIXME: add some way to gate this entire thing for correctness in
863 // potentially potentially evaluated contexts.
864 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
865 ExprResult Temp = PerformCopyInitialization(
866 InitializedEntity::InitializeTemporary(E->getType()),
867 E->getExprLoc(), E);
868 if (Temp.isInvalid())
869 return ExprError();
870 E = Temp.get();
871 }
872
873 return E;
874}
875
876/// Determine the degree of POD-ness for an expression.
877/// Incomplete types are considered POD, since this check can be performed
878/// when we're in an unevaluated context.
879Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
880 if (Ty->isIncompleteType()) {
881 // C++11 [expr.call]p7:
882 // After these conversions, if the argument does not have arithmetic,
883 // enumeration, pointer, pointer to member, or class type, the program
884 // is ill-formed.
885 //
886 // Since we've already performed array-to-pointer and function-to-pointer
887 // decay, the only such type in C++ is cv void. This also handles
888 // initializer lists as variadic arguments.
889 if (Ty->isVoidType())
890 return VAK_Invalid;
891
892 if (Ty->isObjCObjectType())
893 return VAK_Invalid;
894 return VAK_Valid;
895 }
896
897 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
898 return VAK_Invalid;
899
900 if (Ty.isCXX98PODType(Context))
901 return VAK_Valid;
902
903 // C++11 [expr.call]p7:
904 // Passing a potentially-evaluated argument of class type (Clause 9)
905 // having a non-trivial copy constructor, a non-trivial move constructor,
906 // or a non-trivial destructor, with no corresponding parameter,
907 // is conditionally-supported with implementation-defined semantics.
908 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
909 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
910 if (!Record->hasNonTrivialCopyConstructor() &&
911 !Record->hasNonTrivialMoveConstructor() &&
912 !Record->hasNonTrivialDestructor())
913 return VAK_ValidInCXX11;
914
915 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
916 return VAK_Valid;
917
918 if (Ty->isObjCObjectType())
919 return VAK_Invalid;
920
921 if (getLangOpts().MSVCCompat)
922 return VAK_MSVCUndefined;
923
924 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
925 // permitted to reject them. We should consider doing so.
926 return VAK_Undefined;
927}
928
929void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
930 // Don't allow one to pass an Objective-C interface to a vararg.
931 const QualType &Ty = E->getType();
932 VarArgKind VAK = isValidVarArgType(Ty);
933
934 // Complain about passing non-POD types through varargs.
935 switch (VAK) {
936 case VAK_ValidInCXX11:
937 DiagRuntimeBehavior(
938 E->getBeginLoc(), nullptr,
939 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
940 LLVM_FALLTHROUGH[[gnu::fallthrough]];
941 case VAK_Valid:
942 if (Ty->isRecordType()) {
943 // This is unlikely to be what the user intended. If the class has a
944 // 'c_str' member function, the user probably meant to call that.
945 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
946 PDiag(diag::warn_pass_class_arg_to_vararg)
947 << Ty << CT << hasCStrMethod(E) << ".c_str()");
948 }
949 break;
950
951 case VAK_Undefined:
952 case VAK_MSVCUndefined:
953 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
954 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
955 << getLangOpts().CPlusPlus11 << Ty << CT);
956 break;
957
958 case VAK_Invalid:
959 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
960 Diag(E->getBeginLoc(),
961 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
962 << Ty << CT;
963 else if (Ty->isObjCObjectType())
964 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
965 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
966 << Ty << CT);
967 else
968 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
969 << isa<InitListExpr>(E) << Ty << CT;
970 break;
971 }
972}
973
974/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
975/// will create a trap if the resulting type is not a POD type.
976ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
977 FunctionDecl *FDecl) {
978 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
979 // Strip the unbridged-cast placeholder expression off, if applicable.
980 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
981 (CT == VariadicMethod ||
982 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
983 E = stripARCUnbridgedCast(E);
984
985 // Otherwise, do normal placeholder checking.
986 } else {
987 ExprResult ExprRes = CheckPlaceholderExpr(E);
988 if (ExprRes.isInvalid())
989 return ExprError();
990 E = ExprRes.get();
991 }
992 }
993
994 ExprResult ExprRes = DefaultArgumentPromotion(E);
995 if (ExprRes.isInvalid())
996 return ExprError();
997
998 // Copy blocks to the heap.
999 if (ExprRes.get()->getType()->isBlockPointerType())
1000 maybeExtendBlockObject(ExprRes);
1001
1002 E = ExprRes.get();
1003
1004 // Diagnostics regarding non-POD argument types are
1005 // emitted along with format string checking in Sema::CheckFunctionCall().
1006 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1007 // Turn this into a trap.
1008 CXXScopeSpec SS;
1009 SourceLocation TemplateKWLoc;
1010 UnqualifiedId Name;
1011 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1012 E->getBeginLoc());
1013 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1014 /*HasTrailingLParen=*/true,
1015 /*IsAddressOfOperand=*/false);
1016 if (TrapFn.isInvalid())
1017 return ExprError();
1018
1019 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1020 None, E->getEndLoc());
1021 if (Call.isInvalid())
1022 return ExprError();
1023
1024 ExprResult Comma =
1025 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1026 if (Comma.isInvalid())
1027 return ExprError();
1028 return Comma.get();
1029 }
1030
1031 if (!getLangOpts().CPlusPlus &&
1032 RequireCompleteType(E->getExprLoc(), E->getType(),
1033 diag::err_call_incomplete_argument))
1034 return ExprError();
1035
1036 return E;
1037}
1038
1039/// Converts an integer to complex float type. Helper function of
1040/// UsualArithmeticConversions()
1041///
1042/// \return false if the integer expression is an integer type and is
1043/// successfully converted to the complex type.
1044static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1045 ExprResult &ComplexExpr,
1046 QualType IntTy,
1047 QualType ComplexTy,
1048 bool SkipCast) {
1049 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1050 if (SkipCast) return false;
1051 if (IntTy->isIntegerType()) {
1052 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1053 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1054 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1055 CK_FloatingRealToComplex);
1056 } else {
1057 assert(IntTy->isComplexIntegerType())((void)0);
1058 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1059 CK_IntegralComplexToFloatingComplex);
1060 }
1061 return false;
1062}
1063
1064/// Handle arithmetic conversion with complex types. Helper function of
1065/// UsualArithmeticConversions()
1066static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1067 ExprResult &RHS, QualType LHSType,
1068 QualType RHSType,
1069 bool IsCompAssign) {
1070 // if we have an integer operand, the result is the complex type.
1071 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1072 /*skipCast*/false))
1073 return LHSType;
1074 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1075 /*skipCast*/IsCompAssign))
1076 return RHSType;
1077
1078 // This handles complex/complex, complex/float, or float/complex.
1079 // When both operands are complex, the shorter operand is converted to the
1080 // type of the longer, and that is the type of the result. This corresponds
1081 // to what is done when combining two real floating-point operands.
1082 // The fun begins when size promotion occur across type domains.
1083 // From H&S 6.3.4: When one operand is complex and the other is a real
1084 // floating-point type, the less precise type is converted, within it's
1085 // real or complex domain, to the precision of the other type. For example,
1086 // when combining a "long double" with a "double _Complex", the
1087 // "double _Complex" is promoted to "long double _Complex".
1088
1089 // Compute the rank of the two types, regardless of whether they are complex.
1090 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1091
1092 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1093 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1094 QualType LHSElementType =
1095 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1096 QualType RHSElementType =
1097 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1098
1099 QualType ResultType = S.Context.getComplexType(LHSElementType);
1100 if (Order < 0) {
1101 // Promote the precision of the LHS if not an assignment.
1102 ResultType = S.Context.getComplexType(RHSElementType);
1103 if (!IsCompAssign) {
1104 if (LHSComplexType)
1105 LHS =
1106 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1107 else
1108 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1109 }
1110 } else if (Order > 0) {
1111 // Promote the precision of the RHS.
1112 if (RHSComplexType)
1113 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1114 else
1115 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1116 }
1117 return ResultType;
1118}
1119
1120/// Handle arithmetic conversion from integer to float. Helper function
1121/// of UsualArithmeticConversions()
1122static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1123 ExprResult &IntExpr,
1124 QualType FloatTy, QualType IntTy,
1125 bool ConvertFloat, bool ConvertInt) {
1126 if (IntTy->isIntegerType()) {
1127 if (ConvertInt)
1128 // Convert intExpr to the lhs floating point type.
1129 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1130 CK_IntegralToFloating);
1131 return FloatTy;
1132 }
1133
1134 // Convert both sides to the appropriate complex float.
1135 assert(IntTy->isComplexIntegerType())((void)0);
1136 QualType result = S.Context.getComplexType(FloatTy);
1137
1138 // _Complex int -> _Complex float
1139 if (ConvertInt)
1140 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1141 CK_IntegralComplexToFloatingComplex);
1142
1143 // float -> _Complex float
1144 if (ConvertFloat)
1145 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1146 CK_FloatingRealToComplex);
1147
1148 return result;
1149}
1150
1151/// Handle arithmethic conversion with floating point types. Helper
1152/// function of UsualArithmeticConversions()
1153static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1154 ExprResult &RHS, QualType LHSType,
1155 QualType RHSType, bool IsCompAssign) {
1156 bool LHSFloat = LHSType->isRealFloatingType();
1157 bool RHSFloat = RHSType->isRealFloatingType();
1158
1159 // N1169 4.1.4: If one of the operands has a floating type and the other
1160 // operand has a fixed-point type, the fixed-point operand
1161 // is converted to the floating type [...]
1162 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1163 if (LHSFloat)
1164 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1165 else if (!IsCompAssign)
1166 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1167 return LHSFloat ? LHSType : RHSType;
1168 }
1169
1170 // If we have two real floating types, convert the smaller operand
1171 // to the bigger result.
1172 if (LHSFloat && RHSFloat) {
1173 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1174 if (order > 0) {
1175 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1176 return LHSType;
1177 }
1178
1179 assert(order < 0 && "illegal float comparison")((void)0);
1180 if (!IsCompAssign)
1181 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1182 return RHSType;
1183 }
1184
1185 if (LHSFloat) {
1186 // Half FP has to be promoted to float unless it is natively supported
1187 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1188 LHSType = S.Context.FloatTy;
1189
1190 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1191 /*ConvertFloat=*/!IsCompAssign,
1192 /*ConvertInt=*/ true);
1193 }
1194 assert(RHSFloat)((void)0);
1195 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1196 /*ConvertFloat=*/ true,
1197 /*ConvertInt=*/!IsCompAssign);
1198}
1199
1200/// Diagnose attempts to convert between __float128 and long double if
1201/// there is no support for such conversion. Helper function of
1202/// UsualArithmeticConversions().
1203static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1204 QualType RHSType) {
1205 /* No issue converting if at least one of the types is not a floating point
1206 type or the two types have the same rank.
1207 */
1208 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1209 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1210 return false;
1211
1212 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&((void)0)
1213 "The remaining types must be floating point types.")((void)0);
1214
1215 auto *LHSComplex = LHSType->getAs<ComplexType>();
1216 auto *RHSComplex = RHSType->getAs<ComplexType>();
1217
1218 QualType LHSElemType = LHSComplex ?
1219 LHSComplex->getElementType() : LHSType;
1220 QualType RHSElemType = RHSComplex ?
1221 RHSComplex->getElementType() : RHSType;
1222
1223 // No issue if the two types have the same representation
1224 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1225 &S.Context.getFloatTypeSemantics(RHSElemType))
1226 return false;
1227
1228 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1229 RHSElemType == S.Context.LongDoubleTy);
1230 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1231 RHSElemType == S.Context.Float128Ty);
1232
1233 // We've handled the situation where __float128 and long double have the same
1234 // representation. We allow all conversions for all possible long double types
1235 // except PPC's double double.
1236 return Float128AndLongDouble &&
1237 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1238 &llvm::APFloat::PPCDoubleDouble());
1239}
1240
1241typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1242
1243namespace {
1244/// These helper callbacks are placed in an anonymous namespace to
1245/// permit their use as function template parameters.
1246ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1247 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1248}
1249
1250ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1251 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1252 CK_IntegralComplexCast);
1253}
1254}
1255
1256/// Handle integer arithmetic conversions. Helper function of
1257/// UsualArithmeticConversions()
1258template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1259static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1260 ExprResult &RHS, QualType LHSType,
1261 QualType RHSType, bool IsCompAssign) {
1262 // The rules for this case are in C99 6.3.1.8
1263 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1264 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1265 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1266 if (LHSSigned == RHSSigned) {
1267 // Same signedness; use the higher-ranked type
1268 if (order >= 0) {
1269 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1270 return LHSType;
1271 } else if (!IsCompAssign)
1272 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1273 return RHSType;
1274 } else if (order != (LHSSigned ? 1 : -1)) {
1275 // The unsigned type has greater than or equal rank to the
1276 // signed type, so use the unsigned type
1277 if (RHSSigned) {
1278 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1279 return LHSType;
1280 } else if (!IsCompAssign)
1281 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1282 return RHSType;
1283 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1284 // The two types are different widths; if we are here, that
1285 // means the signed type is larger than the unsigned type, so
1286 // use the signed type.
1287 if (LHSSigned) {
1288 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1289 return LHSType;
1290 } else if (!IsCompAssign)
1291 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1292 return RHSType;
1293 } else {
1294 // The signed type is higher-ranked than the unsigned type,
1295 // but isn't actually any bigger (like unsigned int and long
1296 // on most 32-bit systems). Use the unsigned type corresponding
1297 // to the signed type.
1298 QualType result =
1299 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1300 RHS = (*doRHSCast)(S, RHS.get(), result);
1301 if (!IsCompAssign)
1302 LHS = (*doLHSCast)(S, LHS.get(), result);
1303 return result;
1304 }
1305}
1306
1307/// Handle conversions with GCC complex int extension. Helper function
1308/// of UsualArithmeticConversions()
1309static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1310 ExprResult &RHS, QualType LHSType,
1311 QualType RHSType,
1312 bool IsCompAssign) {
1313 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1314 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1315
1316 if (LHSComplexInt && RHSComplexInt) {
1317 QualType LHSEltType = LHSComplexInt->getElementType();
1318 QualType RHSEltType = RHSComplexInt->getElementType();
1319 QualType ScalarType =
1320 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1321 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1322
1323 return S.Context.getComplexType(ScalarType);
1324 }
1325
1326 if (LHSComplexInt) {
1327 QualType LHSEltType = LHSComplexInt->getElementType();
1328 QualType ScalarType =
1329 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1330 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1331 QualType ComplexType = S.Context.getComplexType(ScalarType);
1332 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1333 CK_IntegralRealToComplex);
1334
1335 return ComplexType;
1336 }
1337
1338 assert(RHSComplexInt)((void)0);
1339
1340 QualType RHSEltType = RHSComplexInt->getElementType();
1341 QualType ScalarType =
1342 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1343 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1344 QualType ComplexType = S.Context.getComplexType(ScalarType);
1345
1346 if (!IsCompAssign)
1347 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1348 CK_IntegralRealToComplex);
1349 return ComplexType;
1350}
1351
1352/// Return the rank of a given fixed point or integer type. The value itself
1353/// doesn't matter, but the values must be increasing with proper increasing
1354/// rank as described in N1169 4.1.1.
1355static unsigned GetFixedPointRank(QualType Ty) {
1356 const auto *BTy = Ty->getAs<BuiltinType>();
1357 assert(BTy && "Expected a builtin type.")((void)0);
1358
1359 switch (BTy->getKind()) {
1360 case BuiltinType::ShortFract:
1361 case BuiltinType::UShortFract:
1362 case BuiltinType::SatShortFract:
1363 case BuiltinType::SatUShortFract:
1364 return 1;
1365 case BuiltinType::Fract:
1366 case BuiltinType::UFract:
1367 case BuiltinType::SatFract:
1368 case BuiltinType::SatUFract:
1369 return 2;
1370 case BuiltinType::LongFract:
1371 case BuiltinType::ULongFract:
1372 case BuiltinType::SatLongFract:
1373 case BuiltinType::SatULongFract:
1374 return 3;
1375 case BuiltinType::ShortAccum:
1376 case BuiltinType::UShortAccum:
1377 case BuiltinType::SatShortAccum:
1378 case BuiltinType::SatUShortAccum:
1379 return 4;
1380 case BuiltinType::Accum:
1381 case BuiltinType::UAccum:
1382 case BuiltinType::SatAccum:
1383 case BuiltinType::SatUAccum:
1384 return 5;
1385 case BuiltinType::LongAccum:
1386 case BuiltinType::ULongAccum:
1387 case BuiltinType::SatLongAccum:
1388 case BuiltinType::SatULongAccum:
1389 return 6;
1390 default:
1391 if (BTy->isInteger())
1392 return 0;
1393 llvm_unreachable("Unexpected fixed point or integer type")__builtin_unreachable();
1394 }
1395}
1396
1397/// handleFixedPointConversion - Fixed point operations between fixed
1398/// point types and integers or other fixed point types do not fall under
1399/// usual arithmetic conversion since these conversions could result in loss
1400/// of precsision (N1169 4.1.4). These operations should be calculated with
1401/// the full precision of their result type (N1169 4.1.6.2.1).
1402static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1403 QualType RHSTy) {
1404 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&((void)0)
1405 "Expected at least one of the operands to be a fixed point type")((void)0);
1406 assert((LHSTy->isFixedPointOrIntegerType() ||((void)0)
1407 RHSTy->isFixedPointOrIntegerType()) &&((void)0)
1408 "Special fixed point arithmetic operation conversions are only "((void)0)
1409 "applied to ints or other fixed point types")((void)0);
1410
1411 // If one operand has signed fixed-point type and the other operand has
1412 // unsigned fixed-point type, then the unsigned fixed-point operand is
1413 // converted to its corresponding signed fixed-point type and the resulting
1414 // type is the type of the converted operand.
1415 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1416 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1417 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1418 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1419
1420 // The result type is the type with the highest rank, whereby a fixed-point
1421 // conversion rank is always greater than an integer conversion rank; if the
1422 // type of either of the operands is a saturating fixedpoint type, the result
1423 // type shall be the saturating fixed-point type corresponding to the type
1424 // with the highest rank; the resulting value is converted (taking into
1425 // account rounding and overflow) to the precision of the resulting type.
1426 // Same ranks between signed and unsigned types are resolved earlier, so both
1427 // types are either signed or both unsigned at this point.
1428 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1429 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1430
1431 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1432
1433 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1434 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1435
1436 return ResultTy;
1437}
1438
1439/// Check that the usual arithmetic conversions can be performed on this pair of
1440/// expressions that might be of enumeration type.
1441static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1442 SourceLocation Loc,
1443 Sema::ArithConvKind ACK) {
1444 // C++2a [expr.arith.conv]p1:
1445 // If one operand is of enumeration type and the other operand is of a
1446 // different enumeration type or a floating-point type, this behavior is
1447 // deprecated ([depr.arith.conv.enum]).
1448 //
1449 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1450 // Eventually we will presumably reject these cases (in C++23 onwards?).
1451 QualType L = LHS->getType(), R = RHS->getType();
1452 bool LEnum = L->isUnscopedEnumerationType(),
1453 REnum = R->isUnscopedEnumerationType();
1454 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1455 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1456 (REnum && L->isFloatingType())) {
1457 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1458 ? diag::warn_arith_conv_enum_float_cxx20
1459 : diag::warn_arith_conv_enum_float)
1460 << LHS->getSourceRange() << RHS->getSourceRange()
1461 << (int)ACK << LEnum << L << R;
1462 } else if (!IsCompAssign && LEnum && REnum &&
1463 !S.Context.hasSameUnqualifiedType(L, R)) {
1464 unsigned DiagID;
1465 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1466 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1467 // If either enumeration type is unnamed, it's less likely that the
1468 // user cares about this, but this situation is still deprecated in
1469 // C++2a. Use a different warning group.
1470 DiagID = S.getLangOpts().CPlusPlus20
1471 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1472 : diag::warn_arith_conv_mixed_anon_enum_types;
1473 } else if (ACK == Sema::ACK_Conditional) {
1474 // Conditional expressions are separated out because they have
1475 // historically had a different warning flag.
1476 DiagID = S.getLangOpts().CPlusPlus20
1477 ? diag::warn_conditional_mixed_enum_types_cxx20
1478 : diag::warn_conditional_mixed_enum_types;
1479 } else if (ACK == Sema::ACK_Comparison) {
1480 // Comparison expressions are separated out because they have
1481 // historically had a different warning flag.
1482 DiagID = S.getLangOpts().CPlusPlus20
1483 ? diag::warn_comparison_mixed_enum_types_cxx20
1484 : diag::warn_comparison_mixed_enum_types;
1485 } else {
1486 DiagID = S.getLangOpts().CPlusPlus20
1487 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1488 : diag::warn_arith_conv_mixed_enum_types;
1489 }
1490 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1491 << (int)ACK << L << R;
1492 }
1493}
1494
1495/// UsualArithmeticConversions - Performs various conversions that are common to
1496/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1497/// routine returns the first non-arithmetic type found. The client is
1498/// responsible for emitting appropriate error diagnostics.
1499QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1500 SourceLocation Loc,
1501 ArithConvKind ACK) {
1502 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1503
1504 if (ACK != ACK_CompAssign) {
1505 LHS = UsualUnaryConversions(LHS.get());
1506 if (LHS.isInvalid())
1507 return QualType();
1508 }
1509
1510 RHS = UsualUnaryConversions(RHS.get());
1511 if (RHS.isInvalid())
1512 return QualType();
1513
1514 // For conversion purposes, we ignore any qualifiers.
1515 // For example, "const float" and "float" are equivalent.
1516 QualType LHSType =
1517 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1518 QualType RHSType =
1519 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1520
1521 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1522 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1523 LHSType = AtomicLHS->getValueType();
1524
1525 // If both types are identical, no conversion is needed.
1526 if (LHSType == RHSType)
1527 return LHSType;
1528
1529 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1530 // The caller can deal with this (e.g. pointer + int).
1531 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1532 return QualType();
1533
1534 // Apply unary and bitfield promotions to the LHS's type.
1535 QualType LHSUnpromotedType = LHSType;
1536 if (LHSType->isPromotableIntegerType())
1537 LHSType = Context.getPromotedIntegerType(LHSType);
1538 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1539 if (!LHSBitfieldPromoteTy.isNull())
1540 LHSType = LHSBitfieldPromoteTy;
1541 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1542 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1543
1544 // If both types are identical, no conversion is needed.
1545 if (LHSType == RHSType)
1546 return LHSType;
1547
1548 // At this point, we have two different arithmetic types.
1549
1550 // Diagnose attempts to convert between __float128 and long double where
1551 // such conversions currently can't be handled.
1552 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1553 return QualType();
1554
1555 // Handle complex types first (C99 6.3.1.8p1).
1556 if (LHSType->isComplexType() || RHSType->isComplexType())
1557 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1558 ACK == ACK_CompAssign);
1559
1560 // Now handle "real" floating types (i.e. float, double, long double).
1561 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1562 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1563 ACK == ACK_CompAssign);
1564
1565 // Handle GCC complex int extension.
1566 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1567 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1568 ACK == ACK_CompAssign);
1569
1570 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1571 return handleFixedPointConversion(*this, LHSType, RHSType);
1572
1573 // Finally, we have two differing integer types.
1574 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1575 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1576}
1577
1578//===----------------------------------------------------------------------===//
1579// Semantic Analysis for various Expression Types
1580//===----------------------------------------------------------------------===//
1581
1582
1583ExprResult
1584Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1585 SourceLocation DefaultLoc,
1586 SourceLocation RParenLoc,
1587 Expr *ControllingExpr,
1588 ArrayRef<ParsedType> ArgTypes,
1589 ArrayRef<Expr *> ArgExprs) {
1590 unsigned NumAssocs = ArgTypes.size();
1591 assert(NumAssocs == ArgExprs.size())((void)0);
1592
1593 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1594 for (unsigned i = 0; i < NumAssocs; ++i) {
1595 if (ArgTypes[i])
1596 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1597 else
1598 Types[i] = nullptr;
1599 }
1600
1601 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1602 ControllingExpr,
1603 llvm::makeArrayRef(Types, NumAssocs),
1604 ArgExprs);
1605 delete [] Types;
1606 return ER;
1607}
1608
1609ExprResult
1610Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1611 SourceLocation DefaultLoc,
1612 SourceLocation RParenLoc,
1613 Expr *ControllingExpr,
1614 ArrayRef<TypeSourceInfo *> Types,
1615 ArrayRef<Expr *> Exprs) {
1616 unsigned NumAssocs = Types.size();
1617 assert(NumAssocs == Exprs.size())((void)0);
1618
1619 // Decay and strip qualifiers for the controlling expression type, and handle
1620 // placeholder type replacement. See committee discussion from WG14 DR423.
1621 {
1622 EnterExpressionEvaluationContext Unevaluated(
1623 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1624 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1625 if (R.isInvalid())
1626 return ExprError();
1627 ControllingExpr = R.get();
1628 }
1629
1630 // The controlling expression is an unevaluated operand, so side effects are
1631 // likely unintended.
1632 if (!inTemplateInstantiation() &&
1633 ControllingExpr->HasSideEffects(Context, false))
1634 Diag(ControllingExpr->getExprLoc(),
1635 diag::warn_side_effects_unevaluated_context);
1636
1637 bool TypeErrorFound = false,
1638 IsResultDependent = ControllingExpr->isTypeDependent(),
1639 ContainsUnexpandedParameterPack
1640 = ControllingExpr->containsUnexpandedParameterPack();
1641
1642 for (unsigned i = 0; i < NumAssocs; ++i) {
1643 if (Exprs[i]->containsUnexpandedParameterPack())
1644 ContainsUnexpandedParameterPack = true;
1645
1646 if (Types[i]) {
1647 if (Types[i]->getType()->containsUnexpandedParameterPack())
1648 ContainsUnexpandedParameterPack = true;
1649
1650 if (Types[i]->getType()->isDependentType()) {
1651 IsResultDependent = true;
1652 } else {
1653 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1654 // complete object type other than a variably modified type."
1655 unsigned D = 0;
1656 if (Types[i]->getType()->isIncompleteType())
1657 D = diag::err_assoc_type_incomplete;
1658 else if (!Types[i]->getType()->isObjectType())
1659 D = diag::err_assoc_type_nonobject;
1660 else if (Types[i]->getType()->isVariablyModifiedType())
1661 D = diag::err_assoc_type_variably_modified;
1662
1663 if (D != 0) {
1664 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1665 << Types[i]->getTypeLoc().getSourceRange()
1666 << Types[i]->getType();
1667 TypeErrorFound = true;
1668 }
1669
1670 // C11 6.5.1.1p2 "No two generic associations in the same generic
1671 // selection shall specify compatible types."
1672 for (unsigned j = i+1; j < NumAssocs; ++j)
1673 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1674 Context.typesAreCompatible(Types[i]->getType(),
1675 Types[j]->getType())) {
1676 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1677 diag::err_assoc_compatible_types)
1678 << Types[j]->getTypeLoc().getSourceRange()
1679 << Types[j]->getType()
1680 << Types[i]->getType();
1681 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1682 diag::note_compat_assoc)
1683 << Types[i]->getTypeLoc().getSourceRange()
1684 << Types[i]->getType();
1685 TypeErrorFound = true;
1686 }
1687 }
1688 }
1689 }
1690 if (TypeErrorFound)
1691 return ExprError();
1692
1693 // If we determined that the generic selection is result-dependent, don't
1694 // try to compute the result expression.
1695 if (IsResultDependent)
1696 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1697 Exprs, DefaultLoc, RParenLoc,
1698 ContainsUnexpandedParameterPack);
1699
1700 SmallVector<unsigned, 1> CompatIndices;
1701 unsigned DefaultIndex = -1U;
1702 for (unsigned i = 0; i < NumAssocs; ++i) {
1703 if (!Types[i])
1704 DefaultIndex = i;
1705 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1706 Types[i]->getType()))
1707 CompatIndices.push_back(i);
1708 }
1709
1710 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1711 // type compatible with at most one of the types named in its generic
1712 // association list."
1713 if (CompatIndices.size() > 1) {
1714 // We strip parens here because the controlling expression is typically
1715 // parenthesized in macro definitions.
1716 ControllingExpr = ControllingExpr->IgnoreParens();
1717 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1718 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1719 << (unsigned)CompatIndices.size();
1720 for (unsigned I : CompatIndices) {
1721 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1722 diag::note_compat_assoc)
1723 << Types[I]->getTypeLoc().getSourceRange()
1724 << Types[I]->getType();
1725 }
1726 return ExprError();
1727 }
1728
1729 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1730 // its controlling expression shall have type compatible with exactly one of
1731 // the types named in its generic association list."
1732 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1733 // We strip parens here because the controlling expression is typically
1734 // parenthesized in macro definitions.
1735 ControllingExpr = ControllingExpr->IgnoreParens();
1736 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1737 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1738 return ExprError();
1739 }
1740
1741 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1742 // type name that is compatible with the type of the controlling expression,
1743 // then the result expression of the generic selection is the expression
1744 // in that generic association. Otherwise, the result expression of the
1745 // generic selection is the expression in the default generic association."
1746 unsigned ResultIndex =
1747 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1748
1749 return GenericSelectionExpr::Create(
1750 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1751 ContainsUnexpandedParameterPack, ResultIndex);
1752}
1753
1754/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1755/// location of the token and the offset of the ud-suffix within it.
1756static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1757 unsigned Offset) {
1758 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1759 S.getLangOpts());
1760}
1761
1762/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1763/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1764static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1765 IdentifierInfo *UDSuffix,
1766 SourceLocation UDSuffixLoc,
1767 ArrayRef<Expr*> Args,
1768 SourceLocation LitEndLoc) {
1769 assert(Args.size() <= 2 && "too many arguments for literal operator")((void)0);
1770
1771 QualType ArgTy[2];
1772 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1773 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1774 if (ArgTy[ArgIdx]->isArrayType())
1775 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1776 }
1777
1778 DeclarationName OpName =
1779 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1780 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1781 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1782
1783 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1784 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1785 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1786 /*AllowStringTemplatePack*/ false,
1787 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1788 return ExprError();
1789
1790 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1791}
1792
1793/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1794/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1795/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1796/// multiple tokens. However, the common case is that StringToks points to one
1797/// string.
1798///
1799ExprResult
1800Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1801 assert(!StringToks.empty() && "Must have at least one string!")((void)0);
1802
1803 StringLiteralParser Literal(StringToks, PP);
1804 if (Literal.hadError)
1805 return ExprError();
1806
1807 SmallVector<SourceLocation, 4> StringTokLocs;
1808 for (const Token &Tok : StringToks)
1809 StringTokLocs.push_back(Tok.getLocation());
1810
1811 QualType CharTy = Context.CharTy;
1812 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1813 if (Literal.isWide()) {
1814 CharTy = Context.getWideCharType();
1815 Kind = StringLiteral::Wide;
1816 } else if (Literal.isUTF8()) {
1817 if (getLangOpts().Char8)
1818 CharTy = Context.Char8Ty;
1819 Kind = StringLiteral::UTF8;
1820 } else if (Literal.isUTF16()) {
1821 CharTy = Context.Char16Ty;
1822 Kind = StringLiteral::UTF16;
1823 } else if (Literal.isUTF32()) {
1824 CharTy = Context.Char32Ty;
1825 Kind = StringLiteral::UTF32;
1826 } else if (Literal.isPascal()) {
1827 CharTy = Context.UnsignedCharTy;
1828 }
1829
1830 // Warn on initializing an array of char from a u8 string literal; this
1831 // becomes ill-formed in C++2a.
1832 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1833 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1834 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1835
1836 // Create removals for all 'u8' prefixes in the string literal(s). This
1837 // ensures C++2a compatibility (but may change the program behavior when
1838 // built by non-Clang compilers for which the execution character set is
1839 // not always UTF-8).
1840 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1841 SourceLocation RemovalDiagLoc;
1842 for (const Token &Tok : StringToks) {
1843 if (Tok.getKind() == tok::utf8_string_literal) {
1844 if (RemovalDiagLoc.isInvalid())
1845 RemovalDiagLoc = Tok.getLocation();
1846 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1847 Tok.getLocation(),
1848 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1849 getSourceManager(), getLangOpts())));
1850 }
1851 }
1852 Diag(RemovalDiagLoc, RemovalDiag);
1853 }
1854
1855 QualType StrTy =
1856 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1857
1858 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1859 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1860 Kind, Literal.Pascal, StrTy,
1861 &StringTokLocs[0],
1862 StringTokLocs.size());
1863 if (Literal.getUDSuffix().empty())
1864 return Lit;
1865
1866 // We're building a user-defined literal.
1867 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1868 SourceLocation UDSuffixLoc =
1869 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1870 Literal.getUDSuffixOffset());
1871
1872 // Make sure we're allowed user-defined literals here.
1873 if (!UDLScope)
1874 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1875
1876 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1877 // operator "" X (str, len)
1878 QualType SizeType = Context.getSizeType();
1879
1880 DeclarationName OpName =
1881 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1882 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1883 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1884
1885 QualType ArgTy[] = {
1886 Context.getArrayDecayedType(StrTy), SizeType
1887 };
1888
1889 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1890 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1891 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1892 /*AllowStringTemplatePack*/ true,
1893 /*DiagnoseMissing*/ true, Lit)) {
1894
1895 case LOLR_Cooked: {
1896 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1897 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1898 StringTokLocs[0]);
1899 Expr *Args[] = { Lit, LenArg };
1900
1901 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1902 }
1903
1904 case LOLR_Template: {
1905 TemplateArgumentListInfo ExplicitArgs;
1906 TemplateArgument Arg(Lit);
1907 TemplateArgumentLocInfo ArgInfo(Lit);
1908 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1909 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1910 &ExplicitArgs);
1911 }
1912
1913 case LOLR_StringTemplatePack: {
1914 TemplateArgumentListInfo ExplicitArgs;
1915
1916 unsigned CharBits = Context.getIntWidth(CharTy);
1917 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1918 llvm::APSInt Value(CharBits, CharIsUnsigned);
1919
1920 TemplateArgument TypeArg(CharTy);
1921 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1922 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1923
1924 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1925 Value = Lit->getCodeUnit(I);
1926 TemplateArgument Arg(Context, Value, CharTy);
1927 TemplateArgumentLocInfo ArgInfo;
1928 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1929 }
1930 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1931 &ExplicitArgs);
1932 }
1933 case LOLR_Raw:
1934 case LOLR_ErrorNoDiagnostic:
1935 llvm_unreachable("unexpected literal operator lookup result")__builtin_unreachable();
1936 case LOLR_Error:
1937 return ExprError();
1938 }
1939 llvm_unreachable("unexpected literal operator lookup result")__builtin_unreachable();
1940}
1941
1942DeclRefExpr *
1943Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1944 SourceLocation Loc,
1945 const CXXScopeSpec *SS) {
1946 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1947 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1948}
1949
1950DeclRefExpr *
1951Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1952 const DeclarationNameInfo &NameInfo,
1953 const CXXScopeSpec *SS, NamedDecl *FoundD,
1954 SourceLocation TemplateKWLoc,
1955 const TemplateArgumentListInfo *TemplateArgs) {
1956 NestedNameSpecifierLoc NNS =
1957 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1958 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1959 TemplateArgs);
1960}
1961
1962// CUDA/HIP: Check whether a captured reference variable is referencing a
1963// host variable in a device or host device lambda.
1964static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1965 VarDecl *VD) {
1966 if (!S.getLangOpts().CUDA || !VD->hasInit())
1967 return false;
1968 assert(VD->getType()->isReferenceType())((void)0);
1969
1970 // Check whether the reference variable is referencing a host variable.
1971 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1972 if (!DRE)
1973 return false;
1974 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1975 if (!Referee || !Referee->hasGlobalStorage() ||
1976 Referee->hasAttr<CUDADeviceAttr>())
1977 return false;
1978
1979 // Check whether the current function is a device or host device lambda.
1980 // Check whether the reference variable is a capture by getDeclContext()
1981 // since refersToEnclosingVariableOrCapture() is not ready at this point.
1982 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
1983 if (MD && MD->getParent()->isLambda() &&
1984 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
1985 VD->getDeclContext() != MD)
1986 return true;
1987
1988 return false;
1989}
1990
1991NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1992 // A declaration named in an unevaluated operand never constitutes an odr-use.
1993 if (isUnevaluatedContext())
1994 return NOUR_Unevaluated;
1995
1996 // C++2a [basic.def.odr]p4:
1997 // A variable x whose name appears as a potentially-evaluated expression e
1998 // is odr-used by e unless [...] x is a reference that is usable in
1999 // constant expressions.
2000 // CUDA/HIP:
2001 // If a reference variable referencing a host variable is captured in a
2002 // device or host device lambda, the value of the referee must be copied
2003 // to the capture and the reference variable must be treated as odr-use
2004 // since the value of the referee is not known at compile time and must
2005 // be loaded from the captured.
2006 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2007 if (VD->getType()->isReferenceType() &&
2008 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2009 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2010 VD->isUsableInConstantExpressions(Context))
2011 return NOUR_Constant;
2012 }
2013
2014 // All remaining non-variable cases constitute an odr-use. For variables, we
2015 // need to wait and see how the expression is used.
2016 return NOUR_None;
2017}
2018
2019/// BuildDeclRefExpr - Build an expression that references a
2020/// declaration that does not require a closure capture.
2021DeclRefExpr *
2022Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2023 const DeclarationNameInfo &NameInfo,
2024 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2025 SourceLocation TemplateKWLoc,
2026 const TemplateArgumentListInfo *TemplateArgs) {
2027 bool RefersToCapturedVariable =
2028 isa<VarDecl>(D) &&
2029 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2030
2031 DeclRefExpr *E = DeclRefExpr::Create(
2032 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2033 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2034 MarkDeclRefReferenced(E);
2035
2036 // C++ [except.spec]p17:
2037 // An exception-specification is considered to be needed when:
2038 // - in an expression, the function is the unique lookup result or
2039 // the selected member of a set of overloaded functions.
2040 //
2041 // We delay doing this until after we've built the function reference and
2042 // marked it as used so that:
2043 // a) if the function is defaulted, we get errors from defining it before /
2044 // instead of errors from computing its exception specification, and
2045 // b) if the function is a defaulted comparison, we can use the body we
2046 // build when defining it as input to the exception specification
2047 // computation rather than computing a new body.
2048 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2049 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2050 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2051 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2052 }
2053 }
2054
2055 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2056 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2057 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2058 getCurFunction()->recordUseOfWeak(E);
2059
2060 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2061 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2062 FD = IFD->getAnonField();
2063 if (FD) {
2064 UnusedPrivateFields.remove(FD);
2065 // Just in case we're building an illegal pointer-to-member.
2066 if (FD->isBitField())
2067 E->setObjectKind(OK_BitField);
2068 }
2069
2070 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2071 // designates a bit-field.
2072 if (auto *BD = dyn_cast<BindingDecl>(D))
2073 if (auto *BE = BD->getBinding())
2074 E->setObjectKind(BE->getObjectKind());
2075
2076 return E;
2077}
2078
2079/// Decomposes the given name into a DeclarationNameInfo, its location, and
2080/// possibly a list of template arguments.
2081///
2082/// If this produces template arguments, it is permitted to call
2083/// DecomposeTemplateName.
2084///
2085/// This actually loses a lot of source location information for
2086/// non-standard name kinds; we should consider preserving that in
2087/// some way.
2088void
2089Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2090 TemplateArgumentListInfo &Buffer,
2091 DeclarationNameInfo &NameInfo,
2092 const TemplateArgumentListInfo *&TemplateArgs) {
2093 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2094 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2095 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2096
2097 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2098 Id.TemplateId->NumArgs);
2099 translateTemplateArguments(TemplateArgsPtr, Buffer);
2100
2101 TemplateName TName = Id.TemplateId->Template.get();
2102 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2103 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2104 TemplateArgs = &Buffer;
2105 } else {
2106 NameInfo = GetNameFromUnqualifiedId(Id);
2107 TemplateArgs = nullptr;
2108 }
2109}
2110
2111static void emitEmptyLookupTypoDiagnostic(
2112 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2113 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2114 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2115 DeclContext *Ctx =
2116 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2117 if (!TC) {
2118 // Emit a special diagnostic for failed member lookups.
2119 // FIXME: computing the declaration context might fail here (?)
2120 if (Ctx)
2121 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2122 << SS.getRange();
2123 else
2124 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2125 return;
2126 }
2127
2128 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2129 bool DroppedSpecifier =
2130 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2131 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2132 ? diag::note_implicit_param_decl
2133 : diag::note_previous_decl;
2134 if (!Ctx)
2135 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2136 SemaRef.PDiag(NoteID));
2137 else
2138 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2139 << Typo << Ctx << DroppedSpecifier
2140 << SS.getRange(),
2141 SemaRef.PDiag(NoteID));
2142}
2143
2144/// Diagnose a lookup that found results in an enclosing class during error
2145/// recovery. This usually indicates that the results were found in a dependent
2146/// base class that could not be searched as part of a template definition.
2147/// Always issues a diagnostic (though this may be only a warning in MS
2148/// compatibility mode).
2149///
2150/// Return \c true if the error is unrecoverable, or \c false if the caller
2151/// should attempt to recover using these lookup results.
2152bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2153 // During a default argument instantiation the CurContext points
2154 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2155 // function parameter list, hence add an explicit check.
2156 bool isDefaultArgument =
2157 !CodeSynthesisContexts.empty() &&
2158 CodeSynthesisContexts.back().Kind ==
2159 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2160 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2161 bool isInstance = CurMethod && CurMethod->isInstance() &&
2162 R.getNamingClass() == CurMethod->getParent() &&
2163 !isDefaultArgument;
2164
2165 // There are two ways we can find a class-scope declaration during template
2166 // instantiation that we did not find in the template definition: if it is a
2167 // member of a dependent base class, or if it is declared after the point of
2168 // use in the same class. Distinguish these by comparing the class in which
2169 // the member was found to the naming class of the lookup.
2170 unsigned DiagID = diag::err_found_in_dependent_base;
2171 unsigned NoteID = diag::note_member_declared_at;
2172 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2173 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2174 : diag::err_found_later_in_class;
2175 } else if (getLangOpts().MSVCCompat) {
2176 DiagID = diag::ext_found_in_dependent_base;
2177 NoteID = diag::note_dependent_member_use;
2178 }
2179
2180 if (isInstance) {
2181 // Give a code modification hint to insert 'this->'.
2182 Diag(R.getNameLoc(), DiagID)
2183 << R.getLookupName()
2184 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2185 CheckCXXThisCapture(R.getNameLoc());
2186 } else {
2187 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2188 // they're not shadowed).
2189 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2190 }
2191
2192 for (NamedDecl *D : R)
2193 Diag(D->getLocation(), NoteID);
2194
2195 // Return true if we are inside a default argument instantiation
2196 // and the found name refers to an instance member function, otherwise
2197 // the caller will try to create an implicit member call and this is wrong
2198 // for default arguments.
2199 //
2200 // FIXME: Is this special case necessary? We could allow the caller to
2201 // diagnose this.
2202 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2203 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2204 return true;
2205 }
2206
2207 // Tell the callee to try to recover.
2208 return false;
2209}
2210
2211/// Diagnose an empty lookup.
2212///
2213/// \return false if new lookup candidates were found
2214bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2215 CorrectionCandidateCallback &CCC,
2216 TemplateArgumentListInfo *ExplicitTemplateArgs,
2217 ArrayRef<Expr *> Args, TypoExpr **Out) {
2218 DeclarationName Name = R.getLookupName();
2219
2220 unsigned diagnostic = diag::err_undeclared_var_use;
2221 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2222 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2223 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2224 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2225 diagnostic = diag::err_undeclared_use;
2226 diagnostic_suggest = diag::err_undeclared_use_suggest;
2227 }
2228
2229 // If the original lookup was an unqualified lookup, fake an
2230 // unqualified lookup. This is useful when (for example) the
2231 // original lookup would not have found something because it was a
2232 // dependent name.
2233 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2234 while (DC) {
2235 if (isa<CXXRecordDecl>(DC)) {
2236 LookupQualifiedName(R, DC);
2237
2238 if (!R.empty()) {
2239 // Don't give errors about ambiguities in this lookup.
2240 R.suppressDiagnostics();
2241
2242 // If there's a best viable function among the results, only mention
2243 // that one in the notes.
2244 OverloadCandidateSet Candidates(R.getNameLoc(),
2245 OverloadCandidateSet::CSK_Normal);
2246 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2247 OverloadCandidateSet::iterator Best;
2248 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2249 OR_Success) {
2250 R.clear();
2251 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2252 R.resolveKind();
2253 }
2254
2255 return DiagnoseDependentMemberLookup(R);
2256 }
2257
2258 R.clear();
2259 }
2260
2261 DC = DC->getLookupParent();
2262 }
2263
2264 // We didn't find anything, so try to correct for a typo.
2265 TypoCorrection Corrected;
2266 if (S && Out) {
2267 SourceLocation TypoLoc = R.getNameLoc();
2268 assert(!ExplicitTemplateArgs &&((void)0)
2269 "Diagnosing an empty lookup with explicit template args!")((void)0);
2270 *Out = CorrectTypoDelayed(
2271 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2272 [=](const TypoCorrection &TC) {
2273 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2274 diagnostic, diagnostic_suggest);
2275 },
2276 nullptr, CTK_ErrorRecovery);
2277 if (*Out)
2278 return true;
2279 } else if (S &&
2280 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2281 S, &SS, CCC, CTK_ErrorRecovery))) {
2282 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2283 bool DroppedSpecifier =
2284 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2285 R.setLookupName(Corrected.getCorrection());
2286
2287 bool AcceptableWithRecovery = false;
2288 bool AcceptableWithoutRecovery = false;
2289 NamedDecl *ND = Corrected.getFoundDecl();
2290 if (ND) {
2291 if (Corrected.isOverloaded()) {
2292 OverloadCandidateSet OCS(R.getNameLoc(),
2293 OverloadCandidateSet::CSK_Normal);
2294 OverloadCandidateSet::iterator Best;
2295 for (NamedDecl *CD : Corrected) {
2296 if (FunctionTemplateDecl *FTD =
2297 dyn_cast<FunctionTemplateDecl>(CD))
2298 AddTemplateOverloadCandidate(
2299 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2300 Args, OCS);
2301 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2302 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2303 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2304 Args, OCS);
2305 }
2306 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2307 case OR_Success:
2308 ND = Best->FoundDecl;
2309 Corrected.setCorrectionDecl(ND);
2310 break;
2311 default:
2312 // FIXME: Arbitrarily pick the first declaration for the note.
2313 Corrected.setCorrectionDecl(ND);
2314 break;
2315 }
2316 }
2317 R.addDecl(ND);
2318 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2319 CXXRecordDecl *Record = nullptr;
2320 if (Corrected.getCorrectionSpecifier()) {
2321 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2322 Record = Ty->getAsCXXRecordDecl();
2323 }
2324 if (!Record)
2325 Record = cast<CXXRecordDecl>(
2326 ND->getDeclContext()->getRedeclContext());
2327 R.setNamingClass(Record);
2328 }
2329
2330 auto *UnderlyingND = ND->getUnderlyingDecl();
2331 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2332 isa<FunctionTemplateDecl>(UnderlyingND);
2333 // FIXME: If we ended up with a typo for a type name or
2334 // Objective-C class name, we're in trouble because the parser
2335 // is in the wrong place to recover. Suggest the typo
2336 // correction, but don't make it a fix-it since we're not going
2337 // to recover well anyway.
2338 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2339 getAsTypeTemplateDecl(UnderlyingND) ||
2340 isa<ObjCInterfaceDecl>(UnderlyingND);
2341 } else {
2342 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2343 // because we aren't able to recover.
2344 AcceptableWithoutRecovery = true;
2345 }
2346
2347 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2348 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2349 ? diag::note_implicit_param_decl
2350 : diag::note_previous_decl;
2351 if (SS.isEmpty())
2352 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2353 PDiag(NoteID), AcceptableWithRecovery);
2354 else
2355 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2356 << Name << computeDeclContext(SS, false)
2357 << DroppedSpecifier << SS.getRange(),
2358 PDiag(NoteID), AcceptableWithRecovery);
2359
2360 // Tell the callee whether to try to recover.
2361 return !AcceptableWithRecovery;
2362 }
2363 }
2364 R.clear();
2365
2366 // Emit a special diagnostic for failed member lookups.
2367 // FIXME: computing the declaration context might fail here (?)
2368 if (!SS.isEmpty()) {
2369 Diag(R.getNameLoc(), diag::err_no_member)
2370 << Name << computeDeclContext(SS, false)
2371 << SS.getRange();
2372 return true;
2373 }
2374
2375 // Give up, we can't recover.
2376 Diag(R.getNameLoc(), diagnostic) << Name;
2377 return true;
2378}
2379
2380/// In Microsoft mode, if we are inside a template class whose parent class has
2381/// dependent base classes, and we can't resolve an unqualified identifier, then
2382/// assume the identifier is a member of a dependent base class. We can only
2383/// recover successfully in static methods, instance methods, and other contexts
2384/// where 'this' is available. This doesn't precisely match MSVC's
2385/// instantiation model, but it's close enough.
2386static Expr *
2387recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2388 DeclarationNameInfo &NameInfo,
2389 SourceLocation TemplateKWLoc,
2390 const TemplateArgumentListInfo *TemplateArgs) {
2391 // Only try to recover from lookup into dependent bases in static methods or
2392 // contexts where 'this' is available.
2393 QualType ThisType = S.getCurrentThisType();
2394 const CXXRecordDecl *RD = nullptr;
2395 if (!ThisType.isNull())
2396 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2397 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2398 RD = MD->getParent();
2399 if (!RD || !RD->hasAnyDependentBases())
2400 return nullptr;
2401
2402 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2403 // is available, suggest inserting 'this->' as a fixit.
2404 SourceLocation Loc = NameInfo.getLoc();
2405 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2406 DB << NameInfo.getName() << RD;
2407
2408 if (!ThisType.isNull()) {
2409 DB << FixItHint::CreateInsertion(Loc, "this->");
2410 return CXXDependentScopeMemberExpr::Create(
2411 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2412 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2413 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2414 }
2415
2416 // Synthesize a fake NNS that points to the derived class. This will
2417 // perform name lookup during template instantiation.
2418 CXXScopeSpec SS;
2419 auto *NNS =
2420 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2421 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2422 return DependentScopeDeclRefExpr::Create(
2423 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2424 TemplateArgs);
2425}
2426
2427ExprResult
2428Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2429 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2430 bool HasTrailingLParen, bool IsAddressOfOperand,
2431 CorrectionCandidateCallback *CCC,
2432 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2433 assert(!(IsAddressOfOperand && HasTrailingLParen) &&((void)0)
2434 "cannot be direct & operand and have a trailing lparen")((void)0);
2435 if (SS.isInvalid())
2436 return ExprError();
2437
2438 TemplateArgumentListInfo TemplateArgsBuffer;
2439
2440 // Decompose the UnqualifiedId into the following data.
2441 DeclarationNameInfo NameInfo;
2442 const TemplateArgumentListInfo *TemplateArgs;
2443 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2444
2445 DeclarationName Name = NameInfo.getName();
2446 IdentifierInfo *II = Name.getAsIdentifierInfo();
2447 SourceLocation NameLoc = NameInfo.getLoc();
2448
2449 if (II && II->isEditorPlaceholder()) {
2450 // FIXME: When typed placeholders are supported we can create a typed
2451 // placeholder expression node.
2452 return ExprError();
2453 }
2454
2455 // C++ [temp.dep.expr]p3:
2456 // An id-expression is type-dependent if it contains:
2457 // -- an identifier that was declared with a dependent type,
2458 // (note: handled after lookup)
2459 // -- a template-id that is dependent,
2460 // (note: handled in BuildTemplateIdExpr)
2461 // -- a conversion-function-id that specifies a dependent type,
2462 // -- a nested-name-specifier that contains a class-name that
2463 // names a dependent type.
2464 // Determine whether this is a member of an unknown specialization;
2465 // we need to handle these differently.
2466 bool DependentID = false;
2467 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2468 Name.getCXXNameType()->isDependentType()) {
2469 DependentID = true;
2470 } else if (SS.isSet()) {
2471 if (DeclContext *DC = computeDeclContext(SS, false)) {
2472 if (RequireCompleteDeclContext(SS, DC))
2473 return ExprError();
2474 } else {
2475 DependentID = true;
2476 }
2477 }
2478
2479 if (DependentID)
2480 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2481 IsAddressOfOperand, TemplateArgs);
2482
2483 // Perform the required lookup.
2484 LookupResult R(*this, NameInfo,
2485 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2486 ? LookupObjCImplicitSelfParam
2487 : LookupOrdinaryName);
2488 if (TemplateKWLoc.isValid() || TemplateArgs) {
2489 // Lookup the template name again to correctly establish the context in
2490 // which it was found. This is really unfortunate as we already did the
2491 // lookup to determine that it was a template name in the first place. If
2492 // this becomes a performance hit, we can work harder to preserve those
2493 // results until we get here but it's likely not worth it.
2494 bool MemberOfUnknownSpecialization;
2495 AssumedTemplateKind AssumedTemplate;
2496 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2497 MemberOfUnknownSpecialization, TemplateKWLoc,
2498 &AssumedTemplate))
2499 return ExprError();
2500
2501 if (MemberOfUnknownSpecialization ||
2502 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2503 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2504 IsAddressOfOperand, TemplateArgs);
2505 } else {
2506 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2507 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2508
2509 // If the result might be in a dependent base class, this is a dependent
2510 // id-expression.
2511 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2512 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2513 IsAddressOfOperand, TemplateArgs);
2514
2515 // If this reference is in an Objective-C method, then we need to do
2516 // some special Objective-C lookup, too.
2517 if (IvarLookupFollowUp) {
2518 ExprResult E(LookupInObjCMethod(R, S, II, true));
2519 if (E.isInvalid())
2520 return ExprError();
2521
2522 if (Expr *Ex = E.getAs<Expr>())
2523 return Ex;
2524 }
2525 }
2526
2527 if (R.isAmbiguous())
2528 return ExprError();
2529
2530 // This could be an implicitly declared function reference (legal in C90,
2531 // extension in C99, forbidden in C++).
2532 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2533 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2534 if (D) R.addDecl(D);
2535 }
2536
2537 // Determine whether this name might be a candidate for
2538 // argument-dependent lookup.
2539 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2540
2541 if (R.empty() && !ADL) {
2542 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2543 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2544 TemplateKWLoc, TemplateArgs))
2545 return E;
2546 }
2547
2548 // Don't diagnose an empty lookup for inline assembly.
2549 if (IsInlineAsmIdentifier)
2550 return ExprError();
2551
2552 // If this name wasn't predeclared and if this is not a function
2553 // call, diagnose the problem.
2554 TypoExpr *TE = nullptr;
2555 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2556 : nullptr);
2557 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2558 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&((void)0)
2559 "Typo correction callback misconfigured")((void)0);
2560 if (CCC) {
2561 // Make sure the callback knows what the typo being diagnosed is.
2562 CCC->setTypoName(II);
2563 if (SS.isValid())
2564 CCC->setTypoNNS(SS.getScopeRep());
2565 }
2566 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2567 // a template name, but we happen to have always already looked up the name
2568 // before we get here if it must be a template name.
2569 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2570 None, &TE)) {
2571 if (TE && KeywordReplacement) {
2572 auto &State = getTypoExprState(TE);
2573 auto BestTC = State.Consumer->getNextCorrection();
2574 if (BestTC.isKeyword()) {
2575 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2576 if (State.DiagHandler)
2577 State.DiagHandler(BestTC);
2578 KeywordReplacement->startToken();
2579 KeywordReplacement->setKind(II->getTokenID());
2580 KeywordReplacement->setIdentifierInfo(II);
2581 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2582 // Clean up the state associated with the TypoExpr, since it has
2583 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2584 clearDelayedTypo(TE);
2585 // Signal that a correction to a keyword was performed by returning a
2586 // valid-but-null ExprResult.
2587 return (Expr*)nullptr;
2588 }
2589 State.Consumer->resetCorrectionStream();
2590 }
2591 return TE ? TE : ExprError();
2592 }
2593
2594 assert(!R.empty() &&((void)0)
2595 "DiagnoseEmptyLookup returned false but added no results")((void)0);
2596
2597 // If we found an Objective-C instance variable, let
2598 // LookupInObjCMethod build the appropriate expression to
2599 // reference the ivar.
2600 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2601 R.clear();
2602 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2603 // In a hopelessly buggy code, Objective-C instance variable
2604 // lookup fails and no expression will be built to reference it.
2605 if (!E.isInvalid() && !E.get())
2606 return ExprError();
2607 return E;
2608 }
2609 }
2610
2611 // This is guaranteed from this point on.
2612 assert(!R.empty() || ADL)((void)0);
2613
2614 // Check whether this might be a C++ implicit instance member access.
2615 // C++ [class.mfct.non-static]p3:
2616 // When an id-expression that is not part of a class member access
2617 // syntax and not used to form a pointer to member is used in the
2618 // body of a non-static member function of class X, if name lookup
2619 // resolves the name in the id-expression to a non-static non-type
2620 // member of some class C, the id-expression is transformed into a
2621 // class member access expression using (*this) as the
2622 // postfix-expression to the left of the . operator.
2623 //
2624 // But we don't actually need to do this for '&' operands if R
2625 // resolved to a function or overloaded function set, because the
2626 // expression is ill-formed if it actually works out to be a
2627 // non-static member function:
2628 //
2629 // C++ [expr.ref]p4:
2630 // Otherwise, if E1.E2 refers to a non-static member function. . .
2631 // [t]he expression can be used only as the left-hand operand of a
2632 // member function call.
2633 //
2634 // There are other safeguards against such uses, but it's important
2635 // to get this right here so that we don't end up making a
2636 // spuriously dependent expression if we're inside a dependent
2637 // instance method.
2638 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2639 bool MightBeImplicitMember;
2640 if (!IsAddressOfOperand)
2641 MightBeImplicitMember = true;
2642 else if (!SS.isEmpty())
2643 MightBeImplicitMember = false;
2644 else if (R.isOverloadedResult())
2645 MightBeImplicitMember = false;
2646 else if (R.isUnresolvableResult())
2647 MightBeImplicitMember = true;
2648 else
2649 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2650 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2651 isa<MSPropertyDecl>(R.getFoundDecl());
2652
2653 if (MightBeImplicitMember)
2654 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2655 R, TemplateArgs, S);
2656 }
2657
2658 if (TemplateArgs || TemplateKWLoc.isValid()) {
2659
2660 // In C++1y, if this is a variable template id, then check it
2661 // in BuildTemplateIdExpr().
2662 // The single lookup result must be a variable template declaration.
2663 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2664 Id.TemplateId->Kind == TNK_Var_template) {
2665 assert(R.getAsSingle<VarTemplateDecl>() &&((void)0)
2666 "There should only be one declaration found.")((void)0);
2667 }
2668
2669 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2670 }
2671
2672 return BuildDeclarationNameExpr(SS, R, ADL);
2673}
2674
2675/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2676/// declaration name, generally during template instantiation.
2677/// There's a large number of things which don't need to be done along
2678/// this path.
2679ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2680 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2681 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2682 DeclContext *DC = computeDeclContext(SS, false);
2683 if (!DC)
2684 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2685 NameInfo, /*TemplateArgs=*/nullptr);
2686
2687 if (RequireCompleteDeclContext(SS, DC))
2688 return ExprError();
2689
2690 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2691 LookupQualifiedName(R, DC);
2692
2693 if (R.isAmbiguous())
2694 return ExprError();
2695
2696 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2697 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2698 NameInfo, /*TemplateArgs=*/nullptr);
2699
2700 if (R.empty()) {
2701 // Don't diagnose problems with invalid record decl, the secondary no_member
2702 // diagnostic during template instantiation is likely bogus, e.g. if a class
2703 // is invalid because it's derived from an invalid base class, then missing
2704 // members were likely supposed to be inherited.
2705 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2706 if (CD->isInvalidDecl())
2707 return ExprError();
2708 Diag(NameInfo.getLoc(), diag::err_no_member)
2709 << NameInfo.getName() << DC << SS.getRange();
2710 return ExprError();
2711 }
2712
2713 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2714 // Diagnose a missing typename if this resolved unambiguously to a type in
2715 // a dependent context. If we can recover with a type, downgrade this to
2716 // a warning in Microsoft compatibility mode.
2717 unsigned DiagID = diag::err_typename_missing;
2718 if (RecoveryTSI && getLangOpts().MSVCCompat)
2719 DiagID = diag::ext_typename_missing;
2720 SourceLocation Loc = SS.getBeginLoc();
2721 auto D = Diag(Loc, DiagID);
2722 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2723 << SourceRange(Loc, NameInfo.getEndLoc());
2724
2725 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2726 // context.
2727 if (!RecoveryTSI)
2728 return ExprError();
2729
2730 // Only issue the fixit if we're prepared to recover.
2731 D << FixItHint::CreateInsertion(Loc, "typename ");
2732
2733 // Recover by pretending this was an elaborated type.
2734 QualType Ty = Context.getTypeDeclType(TD);
2735 TypeLocBuilder TLB;
2736 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2737
2738 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2739 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2740 QTL.setElaboratedKeywordLoc(SourceLocation());
2741 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2742
2743 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2744
2745 return ExprEmpty();
2746 }
2747
2748 // Defend against this resolving to an implicit member access. We usually
2749 // won't get here if this might be a legitimate a class member (we end up in
2750 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2751 // a pointer-to-member or in an unevaluated context in C++11.
2752 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2753 return BuildPossibleImplicitMemberExpr(SS,
2754 /*TemplateKWLoc=*/SourceLocation(),
2755 R, /*TemplateArgs=*/nullptr, S);
2756
2757 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2758}
2759
2760/// The parser has read a name in, and Sema has detected that we're currently
2761/// inside an ObjC method. Perform some additional checks and determine if we
2762/// should form a reference to an ivar.
2763///
2764/// Ideally, most of this would be done by lookup, but there's
2765/// actually quite a lot of extra work involved.
2766DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2767 IdentifierInfo *II) {
2768 SourceLocation Loc = Lookup.getNameLoc();
2769 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2770
2771 // Check for error condition which is already reported.
2772 if (!CurMethod)
2773 return DeclResult(true);
2774
2775 // There are two cases to handle here. 1) scoped lookup could have failed,
2776 // in which case we should look for an ivar. 2) scoped lookup could have
2777 // found a decl, but that decl is outside the current instance method (i.e.
2778 // a global variable). In these two cases, we do a lookup for an ivar with
2779 // this name, if the lookup sucedes, we replace it our current decl.
2780
2781 // If we're in a class method, we don't normally want to look for
2782 // ivars. But if we don't find anything else, and there's an
2783 // ivar, that's an error.
2784 bool IsClassMethod = CurMethod->isClassMethod();
2785
2786 bool LookForIvars;
2787 if (Lookup.empty())
2788 LookForIvars = true;
2789 else if (IsClassMethod)
2790 LookForIvars = false;
2791 else
2792 LookForIvars = (Lookup.isSingleResult() &&
2793 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2794 ObjCInterfaceDecl *IFace = nullptr;
2795 if (LookForIvars) {
2796 IFace = CurMethod->getClassInterface();
2797 ObjCInterfaceDecl *ClassDeclared;
2798 ObjCIvarDecl *IV = nullptr;
2799 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2800 // Diagnose using an ivar in a class method.
2801 if (IsClassMethod) {
2802 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2803 return DeclResult(true);
2804 }
2805
2806 // Diagnose the use of an ivar outside of the declaring class.
2807 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2808 !declaresSameEntity(ClassDeclared, IFace) &&
2809 !getLangOpts().DebuggerSupport)
2810 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2811
2812 // Success.
2813 return IV;
2814 }
2815 } else if (CurMethod->isInstanceMethod()) {
2816 // We should warn if a local variable hides an ivar.
2817 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2818 ObjCInterfaceDecl *ClassDeclared;
2819 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2820 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2821 declaresSameEntity(IFace, ClassDeclared))
2822 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2823 }
2824 }
2825 } else if (Lookup.isSingleResult() &&
2826 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2827 // If accessing a stand-alone ivar in a class method, this is an error.
2828 if (const ObjCIvarDecl *IV =
2829 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2830 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2831 return DeclResult(true);
2832 }
2833 }
2834
2835 // Didn't encounter an error, didn't find an ivar.
2836 return DeclResult(false);
2837}
2838
2839ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2840 ObjCIvarDecl *IV) {
2841 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2842 assert(CurMethod && CurMethod->isInstanceMethod() &&((void)0)
2843 "should not reference ivar from this context")((void)0);
2844
2845 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2846 assert(IFace && "should not reference ivar from this context")((void)0);
2847
2848 // If we're referencing an invalid decl, just return this as a silent
2849 // error node. The error diagnostic was already emitted on the decl.
2850 if (IV->isInvalidDecl())
2851 return ExprError();
2852
2853 // Check if referencing a field with __attribute__((deprecated)).
2854 if (DiagnoseUseOfDecl(IV, Loc))
2855 return ExprError();
2856
2857 // FIXME: This should use a new expr for a direct reference, don't
2858 // turn this into Self->ivar, just return a BareIVarExpr or something.
2859 IdentifierInfo &II = Context.Idents.get("self");
2860 UnqualifiedId SelfName;
2861 SelfName.setImplicitSelfParam(&II);
2862 CXXScopeSpec SelfScopeSpec;
2863 SourceLocation TemplateKWLoc;
2864 ExprResult SelfExpr =
2865 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2866 /*HasTrailingLParen=*/false,
2867 /*IsAddressOfOperand=*/false);
2868 if (SelfExpr.isInvalid())
2869 return ExprError();
2870
2871 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2872 if (SelfExpr.isInvalid())
2873 return ExprError();
2874
2875 MarkAnyDeclReferenced(Loc, IV, true);
2876
2877 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2878 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2879 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2880 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2881
2882 ObjCIvarRefExpr *Result = new (Context)
2883 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2884 IV->getLocation(), SelfExpr.get(), true, true);
2885
2886 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2887 if (!isUnevaluatedContext() &&
2888 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2889 getCurFunction()->recordUseOfWeak(Result);
2890 }
2891 if (getLangOpts().ObjCAutoRefCount)
2892 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2893 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2894
2895 return Result;
2896}
2897
2898/// The parser has read a name in, and Sema has detected that we're currently
2899/// inside an ObjC method. Perform some additional checks and determine if we
2900/// should form a reference to an ivar. If so, build an expression referencing
2901/// that ivar.
2902ExprResult
2903Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2904 IdentifierInfo *II, bool AllowBuiltinCreation) {
2905 // FIXME: Integrate this lookup step into LookupParsedName.
2906 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2907 if (Ivar.isInvalid())
2908 return ExprError();
2909 if (Ivar.isUsable())
2910 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2911 cast<ObjCIvarDecl>(Ivar.get()));
2912
2913 if (Lookup.empty() && II && AllowBuiltinCreation)
2914 LookupBuiltin(Lookup);
2915
2916 // Sentinel value saying that we didn't do anything special.
2917 return ExprResult(false);
2918}
2919
2920/// Cast a base object to a member's actual type.
2921///
2922/// There are two relevant checks:
2923///
2924/// C++ [class.access.base]p7:
2925///
2926/// If a class member access operator [...] is used to access a non-static
2927/// data member or non-static member function, the reference is ill-formed if
2928/// the left operand [...] cannot be implicitly converted to a pointer to the
2929/// naming class of the right operand.
2930///
2931/// C++ [expr.ref]p7:
2932///
2933/// If E2 is a non-static data member or a non-static member function, the
2934/// program is ill-formed if the class of which E2 is directly a member is an
2935/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
2936///
2937/// Note that the latter check does not consider access; the access of the
2938/// "real" base class is checked as appropriate when checking the access of the
2939/// member name.
2940ExprResult
2941Sema::PerformObjectMemberConversion(Expr *From,
2942 NestedNameSpecifier *Qualifier,
2943 NamedDecl *FoundDecl,
2944 NamedDecl *Member) {
2945 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2946 if (!RD)
2947 return From;
2948
2949 QualType DestRecordType;
2950 QualType DestType;
2951 QualType FromRecordType;
2952 QualType FromType = From->getType();
2953 bool PointerConversions = false;
2954 if (isa<FieldDecl>(Member)) {
2955 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2956 auto FromPtrType = FromType->getAs<PointerType>();
2957 DestRecordType = Context.getAddrSpaceQualType(
2958 DestRecordType, FromPtrType
2959 ? FromType->getPointeeType().getAddressSpace()
2960 : FromType.getAddressSpace());
2961
2962 if (FromPtrType) {
2963 DestType = Context.getPointerType(DestRecordType);
2964 FromRecordType = FromPtrType->getPointeeType();
2965 PointerConversions = true;
2966 } else {
2967 DestType = DestRecordType;
2968 FromRecordType = FromType;
2969 }
2970 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2971 if (Method->isStatic())
2972 return From;
2973
2974 DestType = Method->getThisType();
2975 DestRecordType = DestType->getPointeeType();
2976
2977 if (FromType->getAs<PointerType>()) {
2978 FromRecordType = FromType->getPointeeType();
2979 PointerConversions = true;
2980 } else {
2981 FromRecordType = FromType;
2982 DestType = DestRecordType;
2983 }
2984
2985 LangAS FromAS = FromRecordType.getAddressSpace();
2986 LangAS DestAS = DestRecordType.getAddressSpace();
2987 if (FromAS != DestAS) {
2988 QualType FromRecordTypeWithoutAS =
2989 Context.removeAddrSpaceQualType(FromRecordType);
2990 QualType FromTypeWithDestAS =
2991 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2992 if (PointerConversions)
2993 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2994 From = ImpCastExprToType(From, FromTypeWithDestAS,
2995 CK_AddressSpaceConversion, From->getValueKind())
2996 .get();
2997 }
2998 } else {
2999 // No conversion necessary.
3000 return From;
3001 }
3002
3003 if (DestType->isDependentType() || FromType->isDependentType())
3004 return From;
3005
3006 // If the unqualified types are the same, no conversion is necessary.
3007 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3008 return From;
3009
3010 SourceRange FromRange = From->getSourceRange();
3011 SourceLocation FromLoc = FromRange.getBegin();
3012
3013 ExprValueKind VK = From->getValueKind();
3014
3015 // C++ [class.member.lookup]p8:
3016 // [...] Ambiguities can often be resolved by qualifying a name with its
3017 // class name.
3018 //
3019 // If the member was a qualified name and the qualified referred to a
3020 // specific base subobject type, we'll cast to that intermediate type
3021 // first and then to the object in which the member is declared. That allows
3022 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3023 //
3024 // class Base { public: int x; };
3025 // class Derived1 : public Base { };
3026 // class Derived2 : public Base { };
3027 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3028 //
3029 // void VeryDerived::f() {
3030 // x = 17; // error: ambiguous base subobjects
3031 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3032 // }
3033 if (Qualifier && Qualifier->getAsType()) {
3034 QualType QType = QualType(Qualifier->getAsType(), 0);
3035 assert(QType->isRecordType() && "lookup done with non-record type")((void)0);
3036
3037 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
3038
3039 // In C++98, the qualifier type doesn't actually have to be a base
3040 // type of the object type, in which case we just ignore it.
3041 // Otherwise build the appropriate casts.
3042 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3043 CXXCastPath BasePath;
3044 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3045 FromLoc, FromRange, &BasePath))
3046 return ExprError();
3047
3048 if (PointerConversions)
3049 QType = Context.getPointerType(QType);
3050 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3051 VK, &BasePath).get();
3052
3053 FromType = QType;
3054 FromRecordType = QRecordType;
3055
3056 // If the qualifier type was the same as the destination type,
3057 // we're done.
3058 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3059 return From;
3060 }
3061 }
3062
3063 CXXCastPath BasePath;
3064 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3065 FromLoc, FromRange, &BasePath,
3066 /*IgnoreAccess=*/true))
3067 return ExprError();
3068
3069 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3070 VK, &BasePath);
3071}
3072
3073bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3074 const LookupResult &R,
3075 bool HasTrailingLParen) {
3076 // Only when used directly as the postfix-expression of a call.
3077 if (!HasTrailingLParen)
3078 return false;
3079
3080 // Never if a scope specifier was provided.
3081 if (SS.isSet())
3082 return false;
3083
3084 // Only in C++ or ObjC++.
3085 if (!getLangOpts().CPlusPlus)
3086 return false;
3087
3088 // Turn off ADL when we find certain kinds of declarations during
3089 // normal lookup:
3090 for (NamedDecl *D : R) {
3091 // C++0x [basic.lookup.argdep]p3:
3092 // -- a declaration of a class member
3093 // Since using decls preserve this property, we check this on the
3094 // original decl.
3095 if (D->isCXXClassMember())
3096 return false;
3097
3098 // C++0x [basic.lookup.argdep]p3:
3099 // -- a block-scope function declaration that is not a
3100 // using-declaration
3101 // NOTE: we also trigger this for function templates (in fact, we
3102 // don't check the decl type at all, since all other decl types
3103 // turn off ADL anyway).
3104 if (isa<UsingShadowDecl>(D))
3105 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3106 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3107 return false;
3108
3109 // C++0x [basic.lookup.argdep]p3:
3110 // -- a declaration that is neither a function or a function
3111 // template
3112 // And also for builtin functions.
3113 if (isa<FunctionDecl>(D)) {
3114 FunctionDecl *FDecl = cast<FunctionDecl>(D);
3115
3116 // But also builtin functions.
3117 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3118 return false;
3119 } else if (!isa<FunctionTemplateDecl>(D))
3120 return false;
3121 }
3122
3123 return true;
3124}
3125
3126
3127/// Diagnoses obvious problems with the use of the given declaration
3128/// as an expression. This is only actually called for lookups that
3129/// were not overloaded, and it doesn't promise that the declaration
3130/// will in fact be used.
3131static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3132 if (D->isInvalidDecl())
3133 return true;
3134
3135 if (isa<TypedefNameDecl>(D)) {
3136 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3137 return true;
3138 }
3139
3140 if (isa<ObjCInterfaceDecl>(D)) {
3141 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3142 return true;
3143 }
3144
3145 if (isa<NamespaceDecl>(D)) {
3146 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3147 return true;
3148 }
3149
3150 return false;
3151}
3152
3153// Certain multiversion types should be treated as overloaded even when there is
3154// only one result.
3155static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3156 assert(R.isSingleResult() && "Expected only a single result")((void)0);
3157 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3158 return FD &&
3159 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3160}
3161
3162ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3163 LookupResult &R, bool NeedsADL,
3164 bool AcceptInvalidDecl) {
3165 // If this is a single, fully-resolved result and we don't need ADL,
3166 // just build an ordinary singleton decl ref.
3167 if (!NeedsADL && R.isSingleResult() &&
3168 !R.getAsSingle<FunctionTemplateDecl>() &&
3169 !ShouldLookupResultBeMultiVersionOverload(R))
3170 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3171 R.getRepresentativeDecl(), nullptr,
3172 AcceptInvalidDecl);
3173
3174 // We only need to check the declaration if there's exactly one
3175 // result, because in the overloaded case the results can only be
3176 // functions and function templates.
3177 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3178 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3179 return ExprError();
3180
3181 // Otherwise, just build an unresolved lookup expression. Suppress
3182 // any lookup-related diagnostics; we'll hash these out later, when
3183 // we've picked a target.
3184 R.suppressDiagnostics();
3185
3186 UnresolvedLookupExpr *ULE
3187 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3188 SS.getWithLocInContext(Context),
3189 R.getLookupNameInfo(),
3190 NeedsADL, R.isOverloadedResult(),
3191 R.begin(), R.end());
3192
3193 return ULE;
3194}
3195
3196static void
3197diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3198 ValueDecl *var, DeclContext *DC);
3199
3200/// Complete semantic analysis for a reference to the given declaration.
3201ExprResult Sema::BuildDeclarationNameExpr(
3202 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3203 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3204 bool AcceptInvalidDecl) {
3205 assert(D && "Cannot refer to a NULL declaration")((void)0);
3206 assert(!isa<FunctionTemplateDecl>(D) &&((void)0)
3207 "Cannot refer unambiguously to a function template")((void)0);
3208
3209 SourceLocation Loc = NameInfo.getLoc();
3210 if (CheckDeclInExpr(*this, Loc, D))
3211 return ExprError();
3212
3213 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3214 // Specifically diagnose references to class templates that are missing
3215 // a template argument list.
3216 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3217 return ExprError();
3218 }
3219
3220 // Make sure that we're referring to a value.
3221 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3222 Diag(Loc, diag::err_ref_non_value)
3223 << D << SS.getRange();
3224 Diag(D->getLocation(), diag::note_declared_at);
3225 return ExprError();
3226 }
3227
3228 // Check whether this declaration can be used. Note that we suppress
3229 // this check when we're going to perform argument-dependent lookup
3230 // on this function name, because this might not be the function
3231 // that overload resolution actually selects.
3232 if (DiagnoseUseOfDecl(D, Loc))
3233 return ExprError();
3234
3235 auto *VD = cast<ValueDecl>(D);
3236
3237 // Only create DeclRefExpr's for valid Decl's.
3238 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3239 return ExprError();
3240
3241 // Handle members of anonymous structs and unions. If we got here,
3242 // and the reference is to a class member indirect field, then this
3243 // must be the subject of a pointer-to-member expression.
3244 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3245 if (!indirectField->isCXXClassMember())
3246 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3247 indirectField);
3248
3249 {
3250 QualType type = VD->getType();
3251 if (type.isNull())
3252 return ExprError();
3253 ExprValueKind valueKind = VK_PRValue;
3254
3255 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3256 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3257 // is expanded by some outer '...' in the context of the use.
3258 type = type.getNonPackExpansionType();
3259
3260 switch (D->getKind()) {
3261 // Ignore all the non-ValueDecl kinds.
3262#define ABSTRACT_DECL(kind)
3263#define VALUE(type, base)
3264#define DECL(type, base) \
3265 case Decl::type:
3266#include "clang/AST/DeclNodes.inc"
3267 llvm_unreachable("invalid value decl kind")__builtin_unreachable();
3268
3269 // These shouldn't make it here.
3270 case Decl::ObjCAtDefsField:
3271 llvm_unreachable("forming non-member reference to ivar?")__builtin_unreachable();
3272
3273 // Enum constants are always r-values and never references.
3274 // Unresolved using declarations are dependent.
3275 case Decl::EnumConstant:
3276 case Decl::UnresolvedUsingValue:
3277 case Decl::OMPDeclareReduction:
3278 case Decl::OMPDeclareMapper:
3279 valueKind = VK_PRValue;
3280 break;
3281
3282 // Fields and indirect fields that got here must be for
3283 // pointer-to-member expressions; we just call them l-values for
3284 // internal consistency, because this subexpression doesn't really
3285 // exist in the high-level semantics.
3286 case Decl::Field:
3287 case Decl::IndirectField:
3288 case Decl::ObjCIvar:
3289 assert(getLangOpts().CPlusPlus &&((void)0)
3290 "building reference to field in C?")((void)0);
3291
3292 // These can't have reference type in well-formed programs, but
3293 // for internal consistency we do this anyway.
3294 type = type.getNonReferenceType();
3295 valueKind = VK_LValue;
3296 break;
3297
3298 // Non-type template parameters are either l-values or r-values
3299 // depending on the type.
3300 case Decl::NonTypeTemplateParm: {
3301 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3302 type = reftype->getPointeeType();
3303 valueKind = VK_LValue; // even if the parameter is an r-value reference
3304 break;
3305 }
3306
3307 // [expr.prim.id.unqual]p2:
3308 // If the entity is a template parameter object for a template
3309 // parameter of type T, the type of the expression is const T.
3310 // [...] The expression is an lvalue if the entity is a [...] template
3311 // parameter object.
3312 if (type->isRecordType()) {
3313 type = type.getUnqualifiedType().withConst();
3314 valueKind = VK_LValue;
3315 break;
3316 }
3317
3318 // For non-references, we need to strip qualifiers just in case
3319 // the template parameter was declared as 'const int' or whatever.
3320 valueKind = VK_PRValue;
3321 type = type.getUnqualifiedType();
3322 break;
3323 }
3324
3325 case Decl::Var:
3326 case Decl::VarTemplateSpecialization:
3327 case Decl::VarTemplatePartialSpecialization:
3328 case Decl::Decomposition:
3329 case Decl::OMPCapturedExpr:
3330 // In C, "extern void blah;" is valid and is an r-value.
3331 if (!getLangOpts().CPlusPlus &&
3332 !type.hasQualifiers() &&
3333 type->isVoidType()) {
3334 valueKind = VK_PRValue;
3335 break;
3336 }
3337 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3338
3339 case Decl::ImplicitParam:
3340 case Decl::ParmVar: {
3341 // These are always l-values.
3342 valueKind = VK_LValue;
3343 type = type.getNonReferenceType();
3344
3345 // FIXME: Does the addition of const really only apply in
3346 // potentially-evaluated contexts? Since the variable isn't actually
3347 // captured in an unevaluated context, it seems that the answer is no.
3348 if (!isUnevaluatedContext()) {
3349 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3350 if (!CapturedType.isNull())
3351 type = CapturedType;
3352 }
3353
3354 break;
3355 }
3356
3357 case Decl::Binding: {
3358 // These are always lvalues.
3359 valueKind = VK_LValue;
3360 type = type.getNonReferenceType();
3361 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3362 // decides how that's supposed to work.
3363 auto *BD = cast<BindingDecl>(VD);
3364 if (BD->getDeclContext() != CurContext) {
3365 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3366 if (DD && DD->hasLocalStorage())
3367 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3368 }
3369 break;
3370 }
3371
3372 case Decl::Function: {
3373 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3374 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3375 type = Context.BuiltinFnTy;
3376 valueKind = VK_PRValue;
3377 break;
3378 }
3379 }
3380
3381 const FunctionType *fty = type->castAs<FunctionType>();
3382
3383 // If we're referring to a function with an __unknown_anytype
3384 // result type, make the entire expression __unknown_anytype.
3385 if (fty->getReturnType() == Context.UnknownAnyTy) {
3386 type = Context.UnknownAnyTy;
3387 valueKind = VK_PRValue;
3388 break;
3389 }
3390
3391 // Functions are l-values in C++.
3392 if (getLangOpts().CPlusPlus) {
3393 valueKind = VK_LValue;
3394 break;
3395 }
3396
3397 // C99 DR 316 says that, if a function type comes from a
3398 // function definition (without a prototype), that type is only
3399 // used for checking compatibility. Therefore, when referencing
3400 // the function, we pretend that we don't have the full function
3401 // type.
3402 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3403 isa<FunctionProtoType>(fty))
3404 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3405 fty->getExtInfo());
3406
3407 // Functions are r-values in C.
3408 valueKind = VK_PRValue;
3409 break;
3410 }
3411
3412 case Decl::CXXDeductionGuide:
3413 llvm_unreachable("building reference to deduction guide")__builtin_unreachable();
3414
3415 case Decl::MSProperty:
3416 case Decl::MSGuid:
3417 case Decl::TemplateParamObject:
3418 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3419 // capture in OpenMP, or duplicated between host and device?
3420 valueKind = VK_LValue;
3421 break;
3422
3423 case Decl::CXXMethod:
3424 // If we're referring to a method with an __unknown_anytype
3425 // result type, make the entire expression __unknown_anytype.
3426 // This should only be possible with a type written directly.
3427 if (const FunctionProtoType *proto
3428 = dyn_cast<FunctionProtoType>(VD->getType()))
3429 if (proto->getReturnType() == Context.UnknownAnyTy) {
3430 type = Context.UnknownAnyTy;
3431 valueKind = VK_PRValue;
3432 break;
3433 }
3434
3435 // C++ methods are l-values if static, r-values if non-static.
3436 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3437 valueKind = VK_LValue;
3438 break;
3439 }
3440 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3441
3442 case Decl::CXXConversion:
3443 case Decl::CXXDestructor:
3444 case Decl::CXXConstructor:
3445 valueKind = VK_PRValue;
3446 break;
3447 }
3448
3449 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3450 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3451 TemplateArgs);
3452 }
3453}
3454
3455static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3456 SmallString<32> &Target) {
3457 Target.resize(CharByteWidth * (Source.size() + 1));
3458 char *ResultPtr = &Target[0];
3459 const llvm::UTF8 *ErrorPtr;
3460 bool success =
3461 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3462 (void)success;
3463 assert(success)((void)0);
3464 Target.resize(ResultPtr - &Target[0]);
3465}
3466
3467ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3468 PredefinedExpr::IdentKind IK) {
3469 // Pick the current block, lambda, captured statement or function.
3470 Decl *currentDecl = nullptr;
3471 if (const BlockScopeInfo *BSI = getCurBlock())
3472 currentDecl = BSI->TheDecl;
3473 else if (const LambdaScopeInfo *LSI = getCurLambda())
3474 currentDecl = LSI->CallOperator;
3475 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3476 currentDecl = CSI->TheCapturedDecl;
3477 else
3478 currentDecl = getCurFunctionOrMethodDecl();
3479
3480 if (!currentDecl) {
3481 Diag(Loc, diag::ext_predef_outside_function);
3482 currentDecl = Context.getTranslationUnitDecl();
3483 }
3484
3485 QualType ResTy;
3486 StringLiteral *SL = nullptr;
3487 if (cast<DeclContext>(currentDecl)->isDependentContext())
3488 ResTy = Context.DependentTy;
3489 else {
3490 // Pre-defined identifiers are of type char[x], where x is the length of
3491 // the string.
3492 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3493 unsigned Length = Str.length();
3494
3495 llvm::APInt LengthI(32, Length + 1);
3496 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3497 ResTy =
3498 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3499 SmallString<32> RawChars;
3500 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3501 Str, RawChars);
3502 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3503 ArrayType::Normal,
3504 /*IndexTypeQuals*/ 0);
3505 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3506 /*Pascal*/ false, ResTy, Loc);
3507 } else {
3508 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3509 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3510 ArrayType::Normal,
3511 /*IndexTypeQuals*/ 0);
3512 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3513 /*Pascal*/ false, ResTy, Loc);
3514 }
3515 }
3516
3517 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3518}
3519
3520ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3521 SourceLocation LParen,
3522 SourceLocation RParen,
3523 TypeSourceInfo *TSI) {
3524 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3525}
3526
3527ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3528 SourceLocation LParen,
3529 SourceLocation RParen,
3530 ParsedType ParsedTy) {
3531 TypeSourceInfo *TSI = nullptr;
3532 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3533
3534 if (Ty.isNull())
3535 return ExprError();
3536 if (!TSI)
3537 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3538
3539 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3540}
3541
3542ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3543 PredefinedExpr::IdentKind IK;
3544
3545 switch (Kind) {
3546 default: llvm_unreachable("Unknown simple primary expr!")__builtin_unreachable();
3547 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3548 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3549 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3550 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3551 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3552 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3553 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3554 }
3555
3556 return BuildPredefinedExpr(Loc, IK);
3557}
3558
3559ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3560 SmallString<16> CharBuffer;
3561 bool Invalid = false;
3562 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3563 if (Invalid)
3564 return ExprError();
3565
3566 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3567 PP, Tok.getKind());
3568 if (Literal.hadError())
3569 return ExprError();
3570
3571 QualType Ty;
3572 if (Literal.isWide())
3573 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3574 else if (Literal.isUTF8() && getLangOpts().Char8)
3575 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3576 else if (Literal.isUTF16())
3577 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3578 else if (Literal.isUTF32())
3579 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3580 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3581 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3582 else
3583 Ty = Context.CharTy; // 'x' -> char in C++
3584
3585 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3586 if (Literal.isWide())
3587 Kind = CharacterLiteral::Wide;
3588 else if (Literal.isUTF16())
3589 Kind = CharacterLiteral::UTF16;
3590 else if (Literal.isUTF32())
3591 Kind = CharacterLiteral::UTF32;
3592 else if (Literal.isUTF8())
3593 Kind = CharacterLiteral::UTF8;
3594
3595 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3596 Tok.getLocation());
3597
3598 if (Literal.getUDSuffix().empty())
3599 return Lit;
3600
3601 // We're building a user-defined literal.
3602 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3603 SourceLocation UDSuffixLoc =
3604 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3605
3606 // Make sure we're allowed user-defined literals here.
3607 if (!UDLScope)
3608 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3609
3610 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3611 // operator "" X (ch)
3612 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3613 Lit, Tok.getLocation());
3614}
3615
3616ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3617 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3618 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3619 Context.IntTy, Loc);
3620}
3621
3622static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3623 QualType Ty, SourceLocation Loc) {
3624 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3625
3626 using llvm::APFloat;
3627 APFloat Val(Format);
3628
3629 APFloat::opStatus result = Literal.GetFloatValue(Val);
3630
3631 // Overflow is always an error, but underflow is only an error if
3632 // we underflowed to zero (APFloat reports denormals as underflow).
3633 if ((result & APFloat::opOverflow) ||
3634 ((result & APFloat::opUnderflow) && Val.isZero())) {
3635 unsigned diagnostic;
3636 SmallString<20> buffer;
3637 if (result & APFloat::opOverflow) {
3638 diagnostic = diag::warn_float_overflow;
3639 APFloat::getLargest(Format).toString(buffer);
3640 } else {
3641 diagnostic = diag::warn_float_underflow;
3642 APFloat::getSmallest(Format).toString(buffer);
3643 }
3644
3645 S.Diag(Loc, diagnostic)
3646 << Ty
3647 << StringRef(buffer.data(), buffer.size());
3648 }
3649
3650 bool isExact = (result == APFloat::opOK);
3651 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3652}
3653
3654bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3655 assert(E && "Invalid expression")((void)0);
3656
3657 if (E->isValueDependent())
3658 return false;
3659
3660 QualType QT = E->getType();
3661 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3662 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3663 return true;
3664 }
3665
3666 llvm::APSInt ValueAPS;
3667 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3668
3669 if (R.isInvalid())
3670 return true;
3671
3672 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3673 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3674 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3675 << toString(ValueAPS, 10) << ValueIsPositive;
3676 return true;
3677 }
3678
3679 return false;
3680}
3681
3682ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3683 // Fast path for a single digit (which is quite common). A single digit
3684 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3685 if (Tok.getLength() == 1) {
3686 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3687 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3688 }
3689
3690 SmallString<128> SpellingBuffer;
3691 // NumericLiteralParser wants to overread by one character. Add padding to
3692 // the buffer in case the token is copied to the buffer. If getSpelling()
3693 // returns a StringRef to the memory buffer, it should have a null char at
3694 // the EOF, so it is also safe.
3695 SpellingBuffer.resize(Tok.getLength() + 1);
3696
3697 // Get the spelling of the token, which eliminates trigraphs, etc.
3698 bool Invalid = false;
3699 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3700 if (Invalid)
3701 return ExprError();
3702
3703 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3704 PP.getSourceManager(), PP.getLangOpts(),
3705 PP.getTargetInfo(), PP.getDiagnostics());
3706 if (Literal.hadError)
3707 return ExprError();
3708
3709 if (Literal.hasUDSuffix()) {
3710 // We're building a user-defined literal.
3711 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3712 SourceLocation UDSuffixLoc =
3713 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3714
3715 // Make sure we're allowed user-defined literals here.
3716 if (!UDLScope)
3717 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3718
3719 QualType CookedTy;
3720 if (Literal.isFloatingLiteral()) {
3721 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3722 // long double, the literal is treated as a call of the form
3723 // operator "" X (f L)
3724 CookedTy = Context.LongDoubleTy;
3725 } else {
3726 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3727 // unsigned long long, the literal is treated as a call of the form
3728 // operator "" X (n ULL)
3729 CookedTy = Context.UnsignedLongLongTy;
3730 }
3731
3732 DeclarationName OpName =
3733 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3734 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3735 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3736
3737 SourceLocation TokLoc = Tok.getLocation();
3738
3739 // Perform literal operator lookup to determine if we're building a raw
3740 // literal or a cooked one.
3741 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3742 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3743 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3744 /*AllowStringTemplatePack*/ false,
3745 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3746 case LOLR_ErrorNoDiagnostic:
3747 // Lookup failure for imaginary constants isn't fatal, there's still the
3748 // GNU extension producing _Complex types.
3749 break;
3750 case LOLR_Error:
3751 return ExprError();
3752 case LOLR_Cooked: {
3753 Expr *Lit;
3754 if (Literal.isFloatingLiteral()) {
3755 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3756 } else {
3757 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3758 if (Literal.GetIntegerValue(ResultVal))
3759 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3760 << /* Unsigned */ 1;
3761 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3762 Tok.getLocation());
3763 }
3764 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3765 }
3766
3767 case LOLR_Raw: {
3768 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3769 // literal is treated as a call of the form
3770 // operator "" X ("n")
3771 unsigned Length = Literal.getUDSuffixOffset();
3772 QualType StrTy = Context.getConstantArrayType(
3773 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3774 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3775 Expr *Lit = StringLiteral::Create(
3776 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3777 /*Pascal*/false, StrTy, &TokLoc, 1);
3778 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3779 }
3780
3781 case LOLR_Template: {
3782 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3783 // template), L is treated as a call fo the form
3784 // operator "" X <'c1', 'c2', ... 'ck'>()
3785 // where n is the source character sequence c1 c2 ... ck.
3786 TemplateArgumentListInfo ExplicitArgs;
3787 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3788 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3789 llvm::APSInt Value(CharBits, CharIsUnsigned);
3790 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3791 Value = TokSpelling[I];
3792 TemplateArgument Arg(Context, Value, Context.CharTy);
3793 TemplateArgumentLocInfo ArgInfo;
3794 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3795 }
3796 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3797 &ExplicitArgs);
3798 }
3799 case LOLR_StringTemplatePack:
3800 llvm_unreachable("unexpected literal operator lookup result")__builtin_unreachable();
3801 }
3802 }
3803
3804 Expr *Res;
3805
3806 if (Literal.isFixedPointLiteral()) {
3807 QualType Ty;
3808
3809 if (Literal.isAccum) {
3810 if (Literal.isHalf) {
3811 Ty = Context.ShortAccumTy;
3812 } else if (Literal.isLong) {
3813 Ty = Context.LongAccumTy;
3814 } else {
3815 Ty = Context.AccumTy;
3816 }
3817 } else if (Literal.isFract) {
3818 if (Literal.isHalf) {
3819 Ty = Context.ShortFractTy;
3820 } else if (Literal.isLong) {
3821 Ty = Context.LongFractTy;
3822 } else {
3823 Ty = Context.FractTy;
3824 }
3825 }
3826
3827 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3828
3829 bool isSigned = !Literal.isUnsigned;
3830 unsigned scale = Context.getFixedPointScale(Ty);
3831 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3832
3833 llvm::APInt Val(bit_width, 0, isSigned);
3834 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3835 bool ValIsZero = Val.isNullValue() && !Overflowed;
3836
3837 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3838 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3839 // Clause 6.4.4 - The value of a constant shall be in the range of
3840 // representable values for its type, with exception for constants of a
3841 // fract type with a value of exactly 1; such a constant shall denote
3842 // the maximal value for the type.
3843 --Val;
3844 else if (Val.ugt(MaxVal) || Overflowed)
3845 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3846
3847 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3848 Tok.getLocation(), scale);
3849 } else if (Literal.isFloatingLiteral()) {
3850 QualType Ty;
3851 if (Literal.isHalf){
3852 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3853 Ty = Context.HalfTy;
3854 else {
3855 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3856 return ExprError();
3857 }
3858 } else if (Literal.isFloat)
3859 Ty = Context.FloatTy;
3860 else if (Literal.isLong)
3861 Ty = Context.LongDoubleTy;
3862 else if (Literal.isFloat16)
3863 Ty = Context.Float16Ty;
3864 else if (Literal.isFloat128)
3865 Ty = Context.Float128Ty;
3866 else
3867 Ty = Context.DoubleTy;
3868
3869 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3870
3871 if (Ty == Context.DoubleTy) {
3872 if (getLangOpts().SinglePrecisionConstants) {
3873 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3874 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3875 }
3876 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3877 "cl_khr_fp64", getLangOpts())) {
3878 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3879 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3880 << (getLangOpts().OpenCLVersion >= 300);
3881 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3882 }
3883 }
3884 } else if (!Literal.isIntegerLiteral()) {
3885 return ExprError();
3886 } else {
3887 QualType Ty;
3888
3889 // 'long long' is a C99 or C++11 feature.
3890 if (!getLangOpts().C99 && Literal.isLongLong) {
3891 if (getLangOpts().CPlusPlus)
3892 Diag(Tok.getLocation(),
3893 getLangOpts().CPlusPlus11 ?
3894 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3895 else
3896 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3897 }
3898
3899 // 'z/uz' literals are a C++2b feature.
3900 if (Literal.isSizeT)
3901 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3902 ? getLangOpts().CPlusPlus2b
3903 ? diag::warn_cxx20_compat_size_t_suffix
3904 : diag::ext_cxx2b_size_t_suffix
3905 : diag::err_cxx2b_size_t_suffix);
3906
3907 // Get the value in the widest-possible width.
3908 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3909 llvm::APInt ResultVal(MaxWidth, 0);
3910
3911 if (Literal.GetIntegerValue(ResultVal)) {
3912 // If this value didn't fit into uintmax_t, error and force to ull.
3913 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3914 << /* Unsigned */ 1;
3915 Ty = Context.UnsignedLongLongTy;
3916 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&((void)0)
3917 "long long is not intmax_t?")((void)0);
3918 } else {
3919 // If this value fits into a ULL, try to figure out what else it fits into
3920 // according to the rules of C99 6.4.4.1p5.
3921
3922 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3923 // be an unsigned int.
3924 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3925
3926 // Check from smallest to largest, picking the smallest type we can.
3927 unsigned Width = 0;
3928
3929 // Microsoft specific integer suffixes are explicitly sized.
3930 if (Literal.MicrosoftInteger) {
3931 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3932 Width = 8;
3933 Ty = Context.CharTy;
3934 } else {
3935 Width = Literal.MicrosoftInteger;
3936 Ty = Context.getIntTypeForBitwidth(Width,
3937 /*Signed=*/!Literal.isUnsigned);
3938 }
3939 }
3940
3941 // Check C++2b size_t literals.
3942 if (Literal.isSizeT) {
3943 assert(!Literal.MicrosoftInteger &&((void)0)
3944 "size_t literals can't be Microsoft literals")((void)0);
3945 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3946 Context.getTargetInfo().getSizeType());
3947
3948 // Does it fit in size_t?
3949 if (ResultVal.isIntN(SizeTSize)) {
3950 // Does it fit in ssize_t?
3951 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3952 Ty = Context.getSignedSizeType();
3953 else if (AllowUnsigned)
3954 Ty = Context.getSizeType();
3955 Width = SizeTSize;
3956 }
3957 }
3958
3959 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3960 !Literal.isSizeT) {
3961 // Are int/unsigned possibilities?
3962 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3963
3964 // Does it fit in a unsigned int?
3965 if (ResultVal.isIntN(IntSize)) {
3966 // Does it fit in a signed int?
3967 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3968 Ty = Context.IntTy;
3969 else if (AllowUnsigned)
3970 Ty = Context.UnsignedIntTy;
3971 Width = IntSize;
3972 }
3973 }
3974
3975 // Are long/unsigned long possibilities?
3976 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
3977 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3978
3979 // Does it fit in a unsigned long?
3980 if (ResultVal.isIntN(LongSize)) {
3981 // Does it fit in a signed long?
3982 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3983 Ty = Context.LongTy;
3984 else if (AllowUnsigned)
3985 Ty = Context.UnsignedLongTy;
3986 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3987 // is compatible.
3988 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3989 const unsigned LongLongSize =
3990 Context.getTargetInfo().getLongLongWidth();
3991 Diag(Tok.getLocation(),
3992 getLangOpts().CPlusPlus
3993 ? Literal.isLong
3994 ? diag::warn_old_implicitly_unsigned_long_cxx
3995 : /*C++98 UB*/ diag::
3996 ext_old_implicitly_unsigned_long_cxx
3997 : diag::warn_old_implicitly_unsigned_long)
3998 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3999 : /*will be ill-formed*/ 1);
4000 Ty = Context.UnsignedLongTy;
4001 }
4002 Width = LongSize;
4003 }
4004 }
4005
4006 // Check long long if needed.
4007 if (Ty.isNull() && !Literal.isSizeT) {
4008 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4009
4010 // Does it fit in a unsigned long long?
4011 if (ResultVal.isIntN(LongLongSize)) {
4012 // Does it fit in a signed long long?
4013 // To be compatible with MSVC, hex integer literals ending with the
4014 // LL or i64 suffix are always signed in Microsoft mode.
4015 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4016 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4017 Ty = Context.LongLongTy;
4018 else if (AllowUnsigned)
4019 Ty = Context.UnsignedLongLongTy;
4020 Width = LongLongSize;
4021 }
4022 }
4023
4024 // If we still couldn't decide a type, we either have 'size_t' literal
4025 // that is out of range, or a decimal literal that does not fit in a
4026 // signed long long and has no U suffix.
4027 if (Ty.isNull()) {
4028 if (Literal.isSizeT)
4029 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4030 << Literal.isUnsigned;
4031 else
4032 Diag(Tok.getLocation(),
4033 diag::ext_integer_literal_too_large_for_signed);
4034 Ty = Context.UnsignedLongLongTy;
4035 Width = Context.getTargetInfo().getLongLongWidth();
4036 }
4037
4038 if (ResultVal.getBitWidth() != Width)
4039 ResultVal = ResultVal.trunc(Width);
4040 }
4041 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4042 }
4043
4044 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4045 if (Literal.isImaginary) {
4046 Res = new (Context) ImaginaryLiteral(Res,
4047 Context.getComplexType(Res->getType()));
4048
4049 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4050 }
4051 return Res;
4052}
4053
4054ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4055 assert(E && "ActOnParenExpr() missing expr")((void)0);
4056 QualType ExprTy = E->getType();
4057 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4058 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4059 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4060 return new (Context) ParenExpr(L, R, E);
4061}
4062
4063static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4064 SourceLocation Loc,
4065 SourceRange ArgRange) {
4066 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4067 // scalar or vector data type argument..."
4068 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4069 // type (C99 6.2.5p18) or void.
4070 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4071 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4072 << T << ArgRange;
4073 return true;
4074 }
4075
4076 assert((T->isVoidType() || !T->isIncompleteType()) &&((void)0)
4077 "Scalar types should always be complete")((void)0);
4078 return false;
4079}
4080
4081static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4082 SourceLocation Loc,
4083 SourceRange ArgRange,
4084 UnaryExprOrTypeTrait TraitKind) {
4085 // Invalid types must be hard errors for SFINAE in C++.
4086 if (S.LangOpts.CPlusPlus)
4087 return true;
4088
4089 // C99 6.5.3.4p1:
4090 if (T->isFunctionType() &&
4091 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4092 TraitKind == UETT_PreferredAlignOf)) {
4093 // sizeof(function)/alignof(function) is allowed as an extension.
4094 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4095 << getTraitSpelling(TraitKind) << ArgRange;
4096 return false;
4097 }
4098
4099 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4100 // this is an error (OpenCL v1.1 s6.3.k)
4101 if (T->isVoidType()) {
4102 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4103 : diag::ext_sizeof_alignof_void_type;
4104 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4105 return false;
4106 }
4107
4108 return true;
4109}
4110
4111static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4112 SourceLocation Loc,
4113 SourceRange ArgRange,
4114 UnaryExprOrTypeTrait TraitKind) {
4115 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4116 // runtime doesn't allow it.
4117 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4118 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4119 << T << (TraitKind == UETT_SizeOf)
4120 << ArgRange;
4121 return true;
4122 }
4123
4124 return false;
4125}
4126
4127/// Check whether E is a pointer from a decayed array type (the decayed
4128/// pointer type is equal to T) and emit a warning if it is.
4129static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4130 Expr *E) {
4131 // Don't warn if the operation changed the type.
4132 if (T != E->getType())
4133 return;
4134
4135 // Now look for array decays.
4136 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4137 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4138 return;
4139
4140 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4141 << ICE->getType()
4142 << ICE->getSubExpr()->getType();
4143}
4144
4145/// Check the constraints on expression operands to unary type expression
4146/// and type traits.
4147///
4148/// Completes any types necessary and validates the constraints on the operand
4149/// expression. The logic mostly mirrors the type-based overload, but may modify
4150/// the expression as it completes the type for that expression through template
4151/// instantiation, etc.
4152bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4153 UnaryExprOrTypeTrait ExprKind) {
4154 QualType ExprTy = E->getType();
4155 assert(!ExprTy->isReferenceType())((void)0);
4156
4157 bool IsUnevaluatedOperand =
4158 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4159 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4160 if (IsUnevaluatedOperand) {
4161 ExprResult Result = CheckUnevaluatedOperand(E);
4162 if (Result.isInvalid())
4163 return true;
4164 E = Result.get();
4165 }
4166
4167 // The operand for sizeof and alignof is in an unevaluated expression context,
4168 // so side effects could result in unintended consequences.
4169 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4170 // used to build SFINAE gadgets.
4171 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4172 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4173 !E->isInstantiationDependent() &&
4174 E->HasSideEffects(Context, false))
4175 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4176
4177 if (ExprKind == UETT_VecStep)
4178 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4179 E->getSourceRange());
4180
4181 // Explicitly list some types as extensions.
4182 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4183 E->getSourceRange(), ExprKind))
4184 return false;
4185
4186 // 'alignof' applied to an expression only requires the base element type of
4187 // the expression to be complete. 'sizeof' requires the expression's type to
4188 // be complete (and will attempt to complete it if it's an array of unknown
4189 // bound).
4190 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4191 if (RequireCompleteSizedType(
4192 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4193 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4194 getTraitSpelling(ExprKind), E->getSourceRange()))
4195 return true;
4196 } else {
4197 if (RequireCompleteSizedExprType(
4198 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4199 getTraitSpelling(ExprKind), E->getSourceRange()))
4200 return true;
4201 }
4202
4203 // Completing the expression's type may have changed it.
4204 ExprTy = E->getType();
4205 assert(!ExprTy->isReferenceType())((void)0);
4206
4207 if (ExprTy->isFunctionType()) {
4208 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4209 << getTraitSpelling(ExprKind) << E->getSourceRange();
4210 return true;
4211 }
4212
4213 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4214 E->getSourceRange(), ExprKind))
4215 return true;
4216
4217 if (ExprKind == UETT_SizeOf) {
4218 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4219 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4220 QualType OType = PVD->getOriginalType();
4221 QualType Type = PVD->getType();
4222 if (Type->isPointerType() && OType->isArrayType()) {
4223 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4224 << Type << OType;
4225 Diag(PVD->getLocation(), diag::note_declared_at);
4226 }
4227 }
4228 }
4229
4230 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4231 // decays into a pointer and returns an unintended result. This is most
4232 // likely a typo for "sizeof(array) op x".
4233 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4234 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4235 BO->getLHS());
4236 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4237 BO->getRHS());
4238 }
4239 }
4240
4241 return false;
4242}
4243
4244/// Check the constraints on operands to unary expression and type
4245/// traits.
4246///
4247/// This will complete any types necessary, and validate the various constraints
4248/// on those operands.
4249///
4250/// The UsualUnaryConversions() function is *not* called by this routine.
4251/// C99 6.3.2.1p[2-4] all state:
4252/// Except when it is the operand of the sizeof operator ...
4253///
4254/// C++ [expr.sizeof]p4
4255/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4256/// standard conversions are not applied to the operand of sizeof.
4257///
4258/// This policy is followed for all of the unary trait expressions.
4259bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4260 SourceLocation OpLoc,
4261 SourceRange ExprRange,
4262 UnaryExprOrTypeTrait ExprKind) {
4263 if (ExprType->isDependentType())
4264 return false;
4265
4266 // C++ [expr.sizeof]p2:
4267 // When applied to a reference or a reference type, the result
4268 // is the size of the referenced type.
4269 // C++11 [expr.alignof]p3:
4270 // When alignof is applied to a reference type, the result
4271 // shall be the alignment of the referenced type.
4272 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4273 ExprType = Ref->getPointeeType();
4274
4275 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4276 // When alignof or _Alignof is applied to an array type, the result
4277 // is the alignment of the element type.
4278 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4279 ExprKind == UETT_OpenMPRequiredSimdAlign)
4280 ExprType = Context.getBaseElementType(ExprType);
4281
4282 if (ExprKind == UETT_VecStep)
4283 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4284
4285 // Explicitly list some types as extensions.
4286 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4287 ExprKind))
4288 return false;
4289
4290 if (RequireCompleteSizedType(
4291 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4292 getTraitSpelling(ExprKind), ExprRange))
4293 return true;
4294
4295 if (ExprType->isFunctionType()) {
4296 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4297 << getTraitSpelling(ExprKind) << ExprRange;
4298 return true;
4299 }
4300
4301 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4302 ExprKind))
4303 return true;
4304
4305 return false;
4306}
4307
4308static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4309 // Cannot know anything else if the expression is dependent.
4310 if (E->isTypeDependent())
4311 return false;
4312
4313 if (E->getObjectKind() == OK_BitField) {
4314 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4315 << 1 << E->getSourceRange();
4316 return true;
4317 }
4318
4319 ValueDecl *D = nullptr;
4320 Expr *Inner = E->IgnoreParens();
4321 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4322 D = DRE->getDecl();
4323 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4324 D = ME->getMemberDecl();
4325 }
4326
4327 // If it's a field, require the containing struct to have a
4328 // complete definition so that we can compute the layout.
4329 //
4330 // This can happen in C++11 onwards, either by naming the member
4331 // in a way that is not transformed into a member access expression
4332 // (in an unevaluated operand, for instance), or by naming the member
4333 // in a trailing-return-type.
4334 //
4335 // For the record, since __alignof__ on expressions is a GCC
4336 // extension, GCC seems to permit this but always gives the
4337 // nonsensical answer 0.
4338 //
4339 // We don't really need the layout here --- we could instead just
4340 // directly check for all the appropriate alignment-lowing
4341 // attributes --- but that would require duplicating a lot of
4342 // logic that just isn't worth duplicating for such a marginal
4343 // use-case.
4344 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4345 // Fast path this check, since we at least know the record has a
4346 // definition if we can find a member of it.
4347 if (!FD->getParent()->isCompleteDefinition()) {
4348 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4349 << E->getSourceRange();
4350 return true;
4351 }
4352
4353 // Otherwise, if it's a field, and the field doesn't have
4354 // reference type, then it must have a complete type (or be a
4355 // flexible array member, which we explicitly want to
4356 // white-list anyway), which makes the following checks trivial.
4357 if (!FD->getType()->isReferenceType())
4358 return false;
4359 }
4360
4361 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4362}
4363
4364bool Sema::CheckVecStepExpr(Expr *E) {
4365 E = E->IgnoreParens();
4366
4367 // Cannot know anything else if the expression is dependent.
4368 if (E->isTypeDependent())
4369 return false;
4370
4371 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4372}
4373
4374static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4375 CapturingScopeInfo *CSI) {
4376 assert(T->isVariablyModifiedType())((void)0);
4377 assert(CSI != nullptr)((void)0);
4378
4379 // We're going to walk down into the type and look for VLA expressions.
4380 do {
4381 const Type *Ty = T.getTypePtr();
4382 switch (Ty->getTypeClass()) {
4383#define TYPE(Class, Base)
4384#define ABSTRACT_TYPE(Class, Base)
4385#define NON_CANONICAL_TYPE(Class, Base)
4386#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4387#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4388#include "clang/AST/TypeNodes.inc"
4389 T = QualType();
4390 break;
4391 // These types are never variably-modified.
4392 case Type::Builtin:
4393 case Type::Complex:
4394 case Type::Vector:
4395 case Type::ExtVector:
4396 case Type::ConstantMatrix:
4397 case Type::Record:
4398 case Type::Enum:
4399 case Type::Elaborated:
4400 case Type::TemplateSpecialization:
4401 case Type::ObjCObject:
4402 case Type::ObjCInterface:
4403 case Type::ObjCObjectPointer:
4404 case Type::ObjCTypeParam:
4405 case Type::Pipe:
4406 case Type::ExtInt:
4407 llvm_unreachable("type class is never variably-modified!")__builtin_unreachable();
4408 case Type::Adjusted:
4409 T = cast<AdjustedType>(Ty)->getOriginalType();
4410 break;
4411 case Type::Decayed:
4412 T = cast<DecayedType>(Ty)->getPointeeType();
4413 break;
4414 case Type::Pointer:
4415 T = cast<PointerType>(Ty)->getPointeeType();
4416 break;
4417 case Type::BlockPointer:
4418 T = cast<BlockPointerType>(Ty)->getPointeeType();
4419 break;
4420 case Type::LValueReference:
4421 case Type::RValueReference:
4422 T = cast<ReferenceType>(Ty)->getPointeeType();
4423 break;
4424 case Type::MemberPointer:
4425 T = cast<MemberPointerType>(Ty)->getPointeeType();
4426 break;
4427 case Type::ConstantArray:
4428 case Type::IncompleteArray:
4429 // Losing element qualification here is fine.
4430 T = cast<ArrayType>(Ty)->getElementType();
4431 break;
4432 case Type::VariableArray: {
4433 // Losing element qualification here is fine.
4434 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4435
4436 // Unknown size indication requires no size computation.
4437 // Otherwise, evaluate and record it.
4438 auto Size = VAT->getSizeExpr();
4439 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4440 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4441 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4442
4443 T = VAT->getElementType();
4444 break;
4445 }
4446 case Type::FunctionProto:
4447 case Type::FunctionNoProto:
4448 T = cast<FunctionType>(Ty)->getReturnType();
4449 break;
4450 case Type::Paren:
4451 case Type::TypeOf:
4452 case Type::UnaryTransform:
4453 case Type::Attributed:
4454 case Type::SubstTemplateTypeParm:
4455 case Type::MacroQualified:
4456 // Keep walking after single level desugaring.
4457 T = T.getSingleStepDesugaredType(Context);
4458 break;
4459 case Type::Typedef:
4460 T = cast<TypedefType>(Ty)->desugar();
4461 break;
4462 case Type::Decltype:
4463 T = cast<DecltypeType>(Ty)->desugar();
4464 break;
4465 case Type::Auto:
4466 case Type::DeducedTemplateSpecialization:
4467 T = cast<DeducedType>(Ty)->getDeducedType();
4468 break;
4469 case Type::TypeOfExpr:
4470 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4471 break;
4472 case Type::Atomic:
4473 T = cast<AtomicType>(Ty)->getValueType();
4474 break;
4475 }
4476 } while (!T.isNull() && T->isVariablyModifiedType());
4477}
4478
4479/// Build a sizeof or alignof expression given a type operand.
4480ExprResult
4481Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4482 SourceLocation OpLoc,
4483 UnaryExprOrTypeTrait ExprKind,
4484 SourceRange R) {
4485 if (!TInfo)
4486 return ExprError();
4487
4488 QualType T = TInfo->getType();
4489
4490 if (!T->isDependentType() &&
4491 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4492 return ExprError();
4493
4494 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4495 if (auto *TT = T->getAs<TypedefType>()) {
4496 for (auto I = FunctionScopes.rbegin(),
4497 E = std::prev(FunctionScopes.rend());
4498 I != E; ++I) {
4499 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4500 if (CSI == nullptr)
4501 break;
4502 DeclContext *DC = nullptr;
4503 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4504 DC = LSI->CallOperator;
4505 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4506 DC = CRSI->TheCapturedDecl;
4507 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4508 DC = BSI->TheDecl;
4509 if (DC) {
4510 if (DC->containsDecl(TT->getDecl()))
4511 break;
4512 captureVariablyModifiedType(Context, T, CSI);
4513 }
4514 }
4515 }
4516 }
4517
4518 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4519 return new (Context) UnaryExprOrTypeTraitExpr(
4520 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4521}
4522
4523/// Build a sizeof or alignof expression given an expression
4524/// operand.
4525ExprResult
4526Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4527 UnaryExprOrTypeTrait ExprKind) {
4528 ExprResult PE = CheckPlaceholderExpr(E);
4529 if (PE.isInvalid())
4530 return ExprError();
4531
4532 E = PE.get();
4533
4534 // Verify that the operand is valid.
4535 bool isInvalid = false;
4536 if (E->isTypeDependent()) {
4537 // Delay type-checking for type-dependent expressions.
4538 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4539 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4540 } else if (ExprKind == UETT_VecStep) {
4541 isInvalid = CheckVecStepExpr(E);
4542 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4543 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4544 isInvalid = true;
4545 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4546 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4547 isInvalid = true;
4548 } else {
4549 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4550 }
4551
4552 if (isInvalid)
4553 return ExprError();
4554
4555 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4556 PE = TransformToPotentiallyEvaluated(E);
4557 if (PE.isInvalid()) return ExprError();
4558 E = PE.get();
4559 }
4560
4561 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4562 return new (Context) UnaryExprOrTypeTraitExpr(
4563 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4564}
4565
4566/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4567/// expr and the same for @c alignof and @c __alignof
4568/// Note that the ArgRange is invalid if isType is false.
4569ExprResult
4570Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4571 UnaryExprOrTypeTrait ExprKind, bool IsType,
4572 void *TyOrEx, SourceRange ArgRange) {
4573 // If error parsing type, ignore.
4574 if (!TyOrEx) return ExprError();
4575
4576 if (IsType) {
4577 TypeSourceInfo *TInfo;
4578 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4579 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4580 }
4581
4582 Expr *ArgEx = (Expr *)TyOrEx;
4583 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4584 return Result;
4585}
4586
4587static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4588 bool IsReal) {
4589 if (V.get()->isTypeDependent())
4590 return S.Context.DependentTy;
4591
4592 // _Real and _Imag are only l-values for normal l-values.
4593 if (V.get()->getObjectKind() != OK_Ordinary) {
4594 V = S.DefaultLvalueConversion(V.get());
4595 if (V.isInvalid())
4596 return QualType();
4597 }
4598
4599 // These operators return the element type of a complex type.
4600 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4601 return CT->getElementType();
4602
4603 // Otherwise they pass through real integer and floating point types here.
4604 if (V.get()->getType()->isArithmeticType())
4605 return V.get()->getType();
4606
4607 // Test for placeholders.
4608 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4609 if (PR.isInvalid()) return QualType();
4610 if (PR.get() != V.get()) {
4611 V = PR;
4612 return CheckRealImagOperand(S, V, Loc, IsReal);
4613 }
4614
4615 // Reject anything else.
4616 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4617 << (IsReal ? "__real" : "__imag");
4618 return QualType();
4619}
4620
4621
4622
4623ExprResult
4624Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4625 tok::TokenKind Kind, Expr *Input) {
4626 UnaryOperatorKind Opc;
4627 switch (Kind) {
4628 default: llvm_unreachable("Unknown unary op!")__builtin_unreachable();
4629 case tok::plusplus: Opc = UO_PostInc; break;
4630 case tok::minusminus: Opc = UO_PostDec; break;
4631 }
4632
4633 // Since this might is a postfix expression, get rid of ParenListExprs.
4634 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4635 if (Result.isInvalid()) return ExprError();
4636 Input = Result.get();
4637
4638 return BuildUnaryOp(S, OpLoc, Opc, Input);
4639}
4640
4641/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4642///
4643/// \return true on error
4644static bool checkArithmeticOnObjCPointer(Sema &S,
4645 SourceLocation opLoc,
4646 Expr *op) {
4647 assert(op->getType()->isObjCObjectPointerType())((void)0);
4648 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4649 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4650 return false;
4651
4652 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4653 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4654 << op->getSourceRange();
4655 return true;
4656}
4657
4658static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4659 auto *BaseNoParens = Base->IgnoreParens();
4660 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4661 return MSProp->getPropertyDecl()->getType()->isArrayType();
4662 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4663}
4664
4665ExprResult
4666Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4667 Expr *idx, SourceLocation rbLoc) {
4668 if (base && !base->getType().isNull() &&
4669 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4670 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4671 SourceLocation(), /*Length*/ nullptr,
4672 /*Stride=*/nullptr, rbLoc);
4673
4674 // Since this might be a postfix expression, get rid of ParenListExprs.
4675 if (isa<ParenListExpr>(base)) {
4676 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4677 if (result.isInvalid()) return ExprError();
4678 base = result.get();
4679 }
4680
4681 // Check if base and idx form a MatrixSubscriptExpr.
4682 //
4683 // Helper to check for comma expressions, which are not allowed as indices for
4684 // matrix subscript expressions.
4685 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4686 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4687 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4688 << SourceRange(base->getBeginLoc(), rbLoc);
4689 return true;
4690 }
4691 return false;
4692 };
4693 // The matrix subscript operator ([][])is considered a single operator.
4694 // Separating the index expressions by parenthesis is not allowed.
4695 if (base->getType()->isSpecificPlaceholderType(
4696 BuiltinType::IncompleteMatrixIdx) &&
4697 !isa<MatrixSubscriptExpr>(base)) {
4698 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4699 << SourceRange(base->getBeginLoc(), rbLoc);
4700 return ExprError();
4701 }
4702 // If the base is a MatrixSubscriptExpr, try to create a new
4703 // MatrixSubscriptExpr.
4704 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4705 if (matSubscriptE) {
4706 if (CheckAndReportCommaError(idx))
4707 return ExprError();
4708
4709 assert(matSubscriptE->isIncomplete() &&((void)0)
4710 "base has to be an incomplete matrix subscript")((void)0);
4711 return CreateBuiltinMatrixSubscriptExpr(
4712 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4713 }
4714
4715 // Handle any non-overload placeholder types in the base and index
4716 // expressions. We can't handle overloads here because the other
4717 // operand might be an overloadable type, in which case the overload
4718 // resolution for the operator overload should get the first crack
4719 // at the overload.
4720 bool IsMSPropertySubscript = false;
4721 if (base->getType()->isNonOverloadPlaceholderType()) {
4722 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4723 if (!IsMSPropertySubscript) {
4724 ExprResult result = CheckPlaceholderExpr(base);
4725 if (result.isInvalid())
4726 return ExprError();
4727 base = result.get();
4728 }
4729 }
4730
4731 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4732 if (base->getType()->isMatrixType()) {
4733 if (CheckAndReportCommaError(idx))
4734 return ExprError();
4735
4736 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4737 }
4738
4739 // A comma-expression as the index is deprecated in C++2a onwards.
4740 if (getLangOpts().CPlusPlus20 &&
4741 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4742 (isa<CXXOperatorCallExpr>(idx) &&
4743 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4744 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4745 << SourceRange(base->getBeginLoc(), rbLoc);
4746 }
4747
4748 if (idx->getType()->isNonOverloadPlaceholderType()) {
4749 ExprResult result = CheckPlaceholderExpr(idx);
4750 if (result.isInvalid()) return ExprError();
4751 idx = result.get();
4752 }
4753
4754 // Build an unanalyzed expression if either operand is type-dependent.
4755 if (getLangOpts().CPlusPlus &&
4756 (base->isTypeDependent() || idx->isTypeDependent())) {
4757 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4758 VK_LValue, OK_Ordinary, rbLoc);
4759 }
4760
4761 // MSDN, property (C++)
4762 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4763 // This attribute can also be used in the declaration of an empty array in a
4764 // class or structure definition. For example:
4765 // __declspec(property(get=GetX, put=PutX)) int x[];
4766 // The above statement indicates that x[] can be used with one or more array
4767 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4768 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4769 if (IsMSPropertySubscript) {
4770 // Build MS property subscript expression if base is MS property reference
4771 // or MS property subscript.
4772 return new (Context) MSPropertySubscriptExpr(
4773 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4774 }
4775
4776 // Use C++ overloaded-operator rules if either operand has record
4777 // type. The spec says to do this if either type is *overloadable*,
4778 // but enum types can't declare subscript operators or conversion
4779 // operators, so there's nothing interesting for overload resolution
4780 // to do if there aren't any record types involved.
4781 //
4782 // ObjC pointers have their own subscripting logic that is not tied
4783 // to overload resolution and so should not take this path.
4784 if (getLangOpts().CPlusPlus &&
4785 (base->getType()->isRecordType() ||
4786 (!base->getType()->isObjCObjectPointerType() &&
4787 idx->getType()->isRecordType()))) {
4788 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4789 }
4790
4791 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4792
4793 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4794 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4795
4796 return Res;
4797}
4798
4799ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4800 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4801 InitializationKind Kind =
4802 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4803 InitializationSequence InitSeq(*this, Entity, Kind, E);
4804 return InitSeq.Perform(*this, Entity, Kind, E);
4805}
4806
4807ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4808 Expr *ColumnIdx,
4809 SourceLocation RBLoc) {
4810 ExprResult BaseR = CheckPlaceholderExpr(Base);
4811 if (BaseR.isInvalid())
4812 return BaseR;
4813 Base = BaseR.get();
4814
4815 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4816 if (RowR.isInvalid())
4817 return RowR;
4818 RowIdx = RowR.get();
4819
4820 if (!ColumnIdx)
4821 return new (Context) MatrixSubscriptExpr(
4822 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4823
4824 // Build an unanalyzed expression if any of the operands is type-dependent.
4825 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4826 ColumnIdx->isTypeDependent())
4827 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4828 Context.DependentTy, RBLoc);
4829
4830 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4831 if (ColumnR.isInvalid())
4832 return ColumnR;
4833 ColumnIdx = ColumnR.get();
4834
4835 // Check that IndexExpr is an integer expression. If it is a constant
4836 // expression, check that it is less than Dim (= the number of elements in the
4837 // corresponding dimension).
4838 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4839 bool IsColumnIdx) -> Expr * {
4840 if (!IndexExpr->getType()->isIntegerType() &&
4841 !IndexExpr->isTypeDependent()) {
4842 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4843 << IsColumnIdx;
4844 return nullptr;
4845 }
4846
4847 if (Optional<llvm::APSInt> Idx =
4848 IndexExpr->getIntegerConstantExpr(Context)) {
4849 if ((*Idx < 0 || *Idx >= Dim)) {
4850 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4851 << IsColumnIdx << Dim;
4852 return nullptr;
4853 }
4854 }
4855
4856 ExprResult ConvExpr =
4857 tryConvertExprToType(IndexExpr, Context.getSizeType());
4858 assert(!ConvExpr.isInvalid() &&((void)0)
4859 "should be able to convert any integer type to size type")((void)0);
4860 return ConvExpr.get();
4861 };
4862
4863 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4864 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4865 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4866 if (!RowIdx || !ColumnIdx)
4867 return ExprError();
4868
4869 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4870 MTy->getElementType(), RBLoc);
4871}
4872
4873void Sema::CheckAddressOfNoDeref(const Expr *E) {
4874 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4875 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4876
4877 // For expressions like `&(*s).b`, the base is recorded and what should be
4878 // checked.
4879 const MemberExpr *Member = nullptr;
4880 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4881 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4882
4883 LastRecord.PossibleDerefs.erase(StrippedExpr);
4884}
4885
4886void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4887 if (isUnevaluatedContext())
4888 return;
4889
4890 QualType ResultTy = E->getType();
4891 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4892
4893 // Bail if the element is an array since it is not memory access.
4894 if (isa<ArrayType>(ResultTy))
4895 return;
4896
4897 if (ResultTy->hasAttr(attr::NoDeref)) {
4898 LastRecord.PossibleDerefs.insert(E);
4899 return;
4900 }
4901
4902 // Check if the base type is a pointer to a member access of a struct
4903 // marked with noderef.
4904 const Expr *Base = E->getBase();
4905 QualType BaseTy = Base->getType();
4906 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4907 // Not a pointer access
4908 return;
4909
4910 const MemberExpr *Member = nullptr;
4911 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4912 Member->isArrow())
4913 Base = Member->getBase();
4914
4915 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4916 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4917 LastRecord.PossibleDerefs.insert(E);
4918 }
4919}
4920
4921ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4922 Expr *LowerBound,
4923 SourceLocation ColonLocFirst,
4924 SourceLocation ColonLocSecond,
4925 Expr *Length, Expr *Stride,
4926 SourceLocation RBLoc) {
4927 if (Base->getType()->isPlaceholderType() &&
4928 !Base->getType()->isSpecificPlaceholderType(
4929 BuiltinType::OMPArraySection)) {
4930 ExprResult Result = CheckPlaceholderExpr(Base);
4931 if (Result.isInvalid())
4932 return ExprError();
4933 Base = Result.get();
4934 }
4935 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4936 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4937 if (Result.isInvalid())
4938 return ExprError();
4939 Result = DefaultLvalueConversion(Result.get());
4940 if (Result.isInvalid())
4941 return ExprError();
4942 LowerBound = Result.get();
4943 }
4944 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4945 ExprResult Result = CheckPlaceholderExpr(Length);
4946 if (Result.isInvalid())
4947 return ExprError();
4948 Result = DefaultLvalueConversion(Result.get());
4949 if (Result.isInvalid())
4950 return ExprError();
4951 Length = Result.get();
4952 }
4953 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4954 ExprResult Result = CheckPlaceholderExpr(Stride);
4955 if (Result.isInvalid())
4956 return ExprError();
4957 Result = DefaultLvalueConversion(Result.get());
4958 if (Result.isInvalid())
4959 return ExprError();
4960 Stride = Result.get();
4961 }
4962
4963 // Build an unanalyzed expression if either operand is type-dependent.
4964 if (Base->isTypeDependent() ||
4965 (LowerBound &&
4966 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4967 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4968 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4969 return new (Context) OMPArraySectionExpr(
4970 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4971 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4972 }
4973
4974 // Perform default conversions.
4975 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4976 QualType ResultTy;
4977 if (OriginalTy->isAnyPointerType()) {
4978 ResultTy = OriginalTy->getPointeeType();
4979 } else if (OriginalTy->isArrayType()) {
4980 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4981 } else {
4982 return ExprError(
4983 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4984 << Base->getSourceRange());
4985 }
4986 // C99 6.5.2.1p1
4987 if (LowerBound) {
4988 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4989 LowerBound);
4990 if (Res.isInvalid())
4991 return ExprError(Diag(LowerBound->getExprLoc(),
4992 diag::err_omp_typecheck_section_not_integer)
4993 << 0 << LowerBound->getSourceRange());
4994 LowerBound = Res.get();
4995
4996 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4997 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4998 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4999 << 0 << LowerBound->getSourceRange();
5000 }
5001 if (Length) {
5002 auto Res =
5003 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5004 if (Res.isInvalid())
5005 return ExprError(Diag(Length->getExprLoc(),
5006 diag::err_omp_typecheck_section_not_integer)
5007 << 1 << Length->getSourceRange());
5008 Length = Res.get();
5009
5010 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5011 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5012 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5013 << 1 << Length->getSourceRange();
5014 }
5015 if (Stride) {
5016 ExprResult Res =
5017 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5018 if (Res.isInvalid())
5019 return ExprError(Diag(Stride->getExprLoc(),
5020 diag::err_omp_typecheck_section_not_integer)
5021 << 1 << Stride->getSourceRange());
5022 Stride = Res.get();
5023
5024 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5025 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5026 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5027 << 1 << Stride->getSourceRange();
5028 }
5029
5030 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5031 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5032 // type. Note that functions are not objects, and that (in C99 parlance)
5033 // incomplete types are not object types.
5034 if (ResultTy->isFunctionType()) {
5035 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5036 << ResultTy << Base->getSourceRange();
5037 return ExprError();
5038 }
5039
5040 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5041 diag::err_omp_section_incomplete_type, Base))
5042 return ExprError();
5043
5044 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5045 Expr::EvalResult Result;
5046 if (LowerBound->EvaluateAsInt(Result, Context)) {
5047 // OpenMP 5.0, [2.1.5 Array Sections]
5048 // The array section must be a subset of the original array.
5049 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5050 if (LowerBoundValue.isNegative()) {
5051 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5052 << LowerBound->getSourceRange();
5053 return ExprError();
5054 }
5055 }
5056 }
5057
5058 if (Length) {
5059 Expr::EvalResult Result;
5060 if (Length->EvaluateAsInt(Result, Context)) {
5061 // OpenMP 5.0, [2.1.5 Array Sections]
5062 // The length must evaluate to non-negative integers.
5063 llvm::APSInt LengthValue = Result.Val.getInt();
5064 if (LengthValue.isNegative()) {
5065 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5066 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5067 << Length->getSourceRange();
5068 return ExprError();
5069 }
5070 }
5071 } else if (ColonLocFirst.isValid() &&
5072 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5073 !OriginalTy->isVariableArrayType()))) {
5074 // OpenMP 5.0, [2.1.5 Array Sections]
5075 // When the size of the array dimension is not known, the length must be
5076 // specified explicitly.
5077 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5078 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5079 return ExprError();
5080 }
5081
5082 if (Stride) {
5083 Expr::EvalResult Result;
5084 if (Stride->EvaluateAsInt(Result, Context)) {
5085 // OpenMP 5.0, [2.1.5 Array Sections]
5086 // The stride must evaluate to a positive integer.
5087 llvm::APSInt StrideValue = Result.Val.getInt();
5088 if (!StrideValue.isStrictlyPositive()) {
5089 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5090 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5091 << Stride->getSourceRange();
5092 return ExprError();
5093 }
5094 }
5095 }
5096
5097 if (!Base->getType()->isSpecificPlaceholderType(
5098 BuiltinType::OMPArraySection)) {
5099 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5100 if (Result.isInvalid())
5101 return ExprError();
5102 Base = Result.get();
5103 }
5104 return new (Context) OMPArraySectionExpr(
5105 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5106 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5107}
5108
5109ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5110 SourceLocation RParenLoc,
5111 ArrayRef<Expr *> Dims,
5112 ArrayRef<SourceRange> Brackets) {
5113 if (Base->getType()->isPlaceholderType()) {
5114 ExprResult Result = CheckPlaceholderExpr(Base);
5115 if (Result.isInvalid())
5116 return ExprError();
5117 Result = DefaultLvalueConversion(Result.get());
5118 if (Result.isInvalid())
5119 return ExprError();
5120 Base = Result.get();
5121 }
5122 QualType BaseTy = Base->getType();
5123 // Delay analysis of the types/expressions if instantiation/specialization is
5124 // required.
5125 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5126 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5127 LParenLoc, RParenLoc, Dims, Brackets);
5128 if (!BaseTy->isPointerType() ||
5129 (!Base->isTypeDependent() &&
5130 BaseTy->getPointeeType()->isIncompleteType()))
5131 return ExprError(Diag(Base->getExprLoc(),
5132 diag::err_omp_non_pointer_type_array_shaping_base)
5133 << Base->getSourceRange());
5134
5135 SmallVector<Expr *, 4> NewDims;
5136 bool ErrorFound = false;
5137 for (Expr *Dim : Dims) {
5138 if (Dim->getType()->isPlaceholderType()) {
5139 ExprResult Result = CheckPlaceholderExpr(Dim);
5140 if (Result.isInvalid()) {
5141 ErrorFound = true;
5142 continue;
5143 }
5144 Result = DefaultLvalueConversion(Result.get());
5145 if (Result.isInvalid()) {
5146 ErrorFound = true;
5147 continue;
5148 }
5149 Dim = Result.get();
5150 }
5151 if (!Dim->isTypeDependent()) {
5152 ExprResult Result =
5153 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5154 if (Result.isInvalid()) {
5155 ErrorFound = true;
5156 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5157 << Dim->getSourceRange();
5158 continue;
5159 }
5160 Dim = Result.get();
5161 Expr::EvalResult EvResult;
5162 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5163 // OpenMP 5.0, [2.1.4 Array Shaping]
5164 // Each si is an integral type expression that must evaluate to a
5165 // positive integer.
5166 llvm::APSInt Value = EvResult.Val.getInt();
5167 if (!Value.isStrictlyPositive()) {
5168 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5169 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5170 << Dim->getSourceRange();
5171 ErrorFound = true;
5172 continue;
5173 }
5174 }
5175 }
5176 NewDims.push_back(Dim);
5177 }
5178 if (ErrorFound)
5179 return ExprError();
5180 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5181 LParenLoc, RParenLoc, NewDims, Brackets);
5182}
5183
5184ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5185 SourceLocation LLoc, SourceLocation RLoc,
5186 ArrayRef<OMPIteratorData> Data) {
5187 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5188 bool IsCorrect = true;
5189 for (const OMPIteratorData &D : Data) {
5190 TypeSourceInfo *TInfo = nullptr;
5191 SourceLocation StartLoc;
5192 QualType DeclTy;
5193 if (!D.Type.getAsOpaquePtr()) {
5194 // OpenMP 5.0, 2.1.6 Iterators
5195 // In an iterator-specifier, if the iterator-type is not specified then
5196 // the type of that iterator is of int type.
5197 DeclTy = Context.IntTy;
5198 StartLoc = D.DeclIdentLoc;
5199 } else {
5200 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5201 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5202 }
5203
5204 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5205 DeclTy->containsUnexpandedParameterPack() ||
5206 DeclTy->isInstantiationDependentType();
5207 if (!IsDeclTyDependent) {
5208 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5209 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5210 // The iterator-type must be an integral or pointer type.
5211 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5212 << DeclTy;
5213 IsCorrect = false;
5214 continue;
5215 }
5216 if (DeclTy.isConstant(Context)) {
5217 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5218 // The iterator-type must not be const qualified.
5219 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5220 << DeclTy;
5221 IsCorrect = false;
5222 continue;
5223 }
5224 }
5225
5226 // Iterator declaration.
5227 assert(D.DeclIdent && "Identifier expected.")((void)0);
5228 // Always try to create iterator declarator to avoid extra error messages
5229 // about unknown declarations use.
5230 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5231 D.DeclIdent, DeclTy, TInfo, SC_None);
5232 VD->setImplicit();
5233 if (S) {
5234 // Check for conflicting previous declaration.
5235 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5236 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5237 ForVisibleRedeclaration);
5238 Previous.suppressDiagnostics();
5239 LookupName(Previous, S);
5240
5241 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5242 /*AllowInlineNamespace=*/false);
5243 if (!Previous.empty()) {
5244 NamedDecl *Old = Previous.getRepresentativeDecl();
5245 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5246 Diag(Old->getLocation(), diag::note_previous_definition);
5247 } else {
5248 PushOnScopeChains(VD, S);
5249 }
5250 } else {
5251 CurContext->addDecl(VD);
5252 }
5253 Expr *Begin = D.Range.Begin;
5254 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5255 ExprResult BeginRes =
5256 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5257 Begin = BeginRes.get();
5258 }
5259 Expr *End = D.Range.End;
5260 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5261 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5262 End = EndRes.get();
5263 }
5264 Expr *Step = D.Range.Step;
5265 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5266 if (!Step->getType()->isIntegralType(Context)) {
5267 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5268 << Step << Step->getSourceRange();
5269 IsCorrect = false;
5270 continue;
5271 }
5272 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5273 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5274 // If the step expression of a range-specification equals zero, the
5275 // behavior is unspecified.
5276 if (Result && Result->isNullValue()) {
5277 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5278 << Step << Step->getSourceRange();
5279 IsCorrect = false;
5280 continue;
5281 }
5282 }
5283 if (!Begin || !End || !IsCorrect) {
5284 IsCorrect = false;
5285 continue;
5286 }
5287 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5288 IDElem.IteratorDecl = VD;
5289 IDElem.AssignmentLoc = D.AssignLoc;
5290 IDElem.Range.Begin = Begin;
5291 IDElem.Range.End = End;
5292 IDElem.Range.Step = Step;
5293 IDElem.ColonLoc = D.ColonLoc;
5294 IDElem.SecondColonLoc = D.SecColonLoc;
5295 }
5296 if (!IsCorrect) {
5297 // Invalidate all created iterator declarations if error is found.
5298 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5299 if (Decl *ID = D.IteratorDecl)
5300 ID->setInvalidDecl();
5301 }
5302 return ExprError();
5303 }
5304 SmallVector<OMPIteratorHelperData, 4> Helpers;
5305 if (!CurContext->isDependentContext()) {
5306 // Build number of ityeration for each iteration range.
5307 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5308 // ((Begini-Stepi-1-Endi) / -Stepi);
5309 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5310 // (Endi - Begini)
5311 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5312 D.Range.Begin);
5313 if(!Res.isUsable()) {
5314 IsCorrect = false;
5315 continue;
5316 }
5317 ExprResult St, St1;
5318 if (D.Range.Step) {
5319 St = D.Range.Step;
5320 // (Endi - Begini) + Stepi
5321 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5322 if (!Res.isUsable()) {
5323 IsCorrect = false;
5324 continue;
5325 }
5326 // (Endi - Begini) + Stepi - 1
5327 Res =
5328 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5329 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5330 if (!Res.isUsable()) {
5331 IsCorrect = false;
5332 continue;
5333 }
5334 // ((Endi - Begini) + Stepi - 1) / Stepi
5335 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5336 if (!Res.isUsable()) {
5337 IsCorrect = false;
5338 continue;
5339 }
5340 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5341 // (Begini - Endi)
5342 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5343 D.Range.Begin, D.Range.End);
5344 if (!Res1.isUsable()) {
5345 IsCorrect = false;
5346 continue;
5347 }
5348 // (Begini - Endi) - Stepi
5349 Res1 =
5350 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5351 if (!Res1.isUsable()) {
5352 IsCorrect = false;
5353 continue;
5354 }
5355 // (Begini - Endi) - Stepi - 1
5356 Res1 =
5357 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5358 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5359 if (!Res1.isUsable()) {
5360 IsCorrect = false;
5361 continue;
5362 }
5363 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5364 Res1 =
5365 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5366 if (!Res1.isUsable()) {
5367 IsCorrect = false;
5368 continue;
5369 }
5370 // Stepi > 0.
5371 ExprResult CmpRes =
5372 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5373 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5374 if (!CmpRes.isUsable()) {
5375 IsCorrect = false;
5376 continue;
5377 }
5378 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5379 Res.get(), Res1.get());
5380 if (!Res.isUsable()) {
5381 IsCorrect = false;
5382 continue;
5383 }
5384 }
5385 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5386 if (!Res.isUsable()) {
5387 IsCorrect = false;
5388 continue;
5389 }
5390
5391 // Build counter update.
5392 // Build counter.
5393 auto *CounterVD =
5394 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5395 D.IteratorDecl->getBeginLoc(), nullptr,
5396 Res.get()->getType(), nullptr, SC_None);
5397 CounterVD->setImplicit();
5398 ExprResult RefRes =
5399 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5400 D.IteratorDecl->getBeginLoc());
5401 // Build counter update.
5402 // I = Begini + counter * Stepi;
5403 ExprResult UpdateRes;
5404 if (D.Range.Step) {
5405 UpdateRes = CreateBuiltinBinOp(
5406 D.AssignmentLoc, BO_Mul,
5407 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5408 } else {
5409 UpdateRes = DefaultLvalueConversion(RefRes.get());
5410 }
5411 if (!UpdateRes.isUsable()) {
5412 IsCorrect = false;
5413 continue;
5414 }
5415 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5416 UpdateRes.get());
5417 if (!UpdateRes.isUsable()) {
5418 IsCorrect = false;
5419 continue;
5420 }
5421 ExprResult VDRes =
5422 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5423 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5424 D.IteratorDecl->getBeginLoc());
5425 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5426 UpdateRes.get());
5427 if (!UpdateRes.isUsable()) {
5428 IsCorrect = false;
5429 continue;
5430 }
5431 UpdateRes =
5432 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5433 if (!UpdateRes.isUsable()) {
5434 IsCorrect = false;
5435 continue;
5436 }
5437 ExprResult CounterUpdateRes =
5438 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5439 if (!CounterUpdateRes.isUsable()) {
5440 IsCorrect = false;
5441 continue;
5442 }
5443 CounterUpdateRes =
5444 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5445 if (!CounterUpdateRes.isUsable()) {
5446 IsCorrect = false;
5447 continue;
5448 }
5449 OMPIteratorHelperData &HD = Helpers.emplace_back();
5450 HD.CounterVD = CounterVD;
5451 HD.Upper = Res.get();
5452 HD.Update = UpdateRes.get();
5453 HD.CounterUpdate = CounterUpdateRes.get();
5454 }
5455 } else {
5456 Helpers.assign(ID.size(), {});
5457 }
5458 if (!IsCorrect) {
5459 // Invalidate all created iterator declarations if error is found.
5460 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5461 if (Decl *ID = D.IteratorDecl)
5462 ID->setInvalidDecl();
5463 }
5464 return ExprError();
5465 }
5466 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5467 LLoc, RLoc, ID, Helpers);
5468}
5469
5470ExprResult
5471Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5472 Expr *Idx, SourceLocation RLoc) {
5473 Expr *LHSExp = Base;
5474 Expr *RHSExp = Idx;
5475
5476 ExprValueKind VK = VK_LValue;
5477 ExprObjectKind OK = OK_Ordinary;
5478
5479 // Per C++ core issue 1213, the result is an xvalue if either operand is
5480 // a non-lvalue array, and an lvalue otherwise.
5481 if (getLangOpts().CPlusPlus11) {
5482 for (auto *Op : {LHSExp, RHSExp}) {
5483 Op = Op->IgnoreImplicit();
5484 if (Op->getType()->isArrayType() && !Op->isLValue())
5485 VK = VK_XValue;
5486 }
5487 }
5488
5489 // Perform default conversions.
5490 if (!LHSExp->getType()->getAs<VectorType>()) {
5491 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5492 if (Result.isInvalid())
5493 return ExprError();
5494 LHSExp = Result.get();
5495 }
5496 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5497 if (Result.isInvalid())
5498 return ExprError();
5499 RHSExp = Result.get();
5500
5501 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5502
5503 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5504 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5505 // in the subscript position. As a result, we need to derive the array base
5506 // and index from the expression types.
5507 Expr *BaseExpr, *IndexExpr;
5508 QualType ResultType;
5509 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5510 BaseExpr = LHSExp;
5511 IndexExpr = RHSExp;
5512 ResultType = Context.DependentTy;
5513 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5514 BaseExpr = LHSExp;
5515 IndexExpr = RHSExp;
5516 ResultType = PTy->getPointeeType();
5517 } else if (const ObjCObjectPointerType *PTy =
5518 LHSTy->getAs<ObjCObjectPointerType>()) {
5519 BaseExpr = LHSExp;
5520 IndexExpr = RHSExp;
5521
5522 // Use custom logic if this should be the pseudo-object subscript
5523 // expression.
5524 if (!LangOpts.isSubscriptPointerArithmetic())
5525 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5526 nullptr);
5527
5528 ResultType = PTy->getPointeeType();
5529 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5530 // Handle the uncommon case of "123[Ptr]".
5531 BaseExpr = RHSExp;
5532 IndexExpr = LHSExp;
5533 ResultType = PTy->getPointeeType();
5534 } else if (const ObjCObjectPointerType *PTy =
5535 RHSTy->getAs<ObjCObjectPointerType>()) {
5536 // Handle the uncommon case of "123[Ptr]".
5537 BaseExpr = RHSExp;
5538 IndexExpr = LHSExp;
5539 ResultType = PTy->getPointeeType();
5540 if (!LangOpts.isSubscriptPointerArithmetic()) {
5541 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5542 << ResultType << BaseExpr->getSourceRange();
5543 return ExprError();
5544 }
5545 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5546 BaseExpr = LHSExp; // vectors: V[123]
5547 IndexExpr = RHSExp;
5548 // We apply C++ DR1213 to vector subscripting too.
5549 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5550 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5551 if (Materialized.isInvalid())
5552 return ExprError();
5553 LHSExp = Materialized.get();
5554 }
5555 VK = LHSExp->getValueKind();
5556 if (VK != VK_PRValue)
5557 OK = OK_VectorComponent;
5558
5559 ResultType = VTy->getElementType();
5560 QualType BaseType = BaseExpr->getType();
5561 Qualifiers BaseQuals = BaseType.getQualifiers();
5562 Qualifiers MemberQuals = ResultType.getQualifiers();
5563 Qualifiers Combined = BaseQuals + MemberQuals;
5564 if (Combined != MemberQuals)
5565 ResultType = Context.getQualifiedType(ResultType, Combined);
5566 } else if (LHSTy->isArrayType()) {
5567 // If we see an array that wasn't promoted by
5568 // DefaultFunctionArrayLvalueConversion, it must be an array that
5569 // wasn't promoted because of the C90 rule that doesn't
5570 // allow promoting non-lvalue arrays. Warn, then
5571 // force the promotion here.
5572 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5573 << LHSExp->getSourceRange();
5574 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5575 CK_ArrayToPointerDecay).get();
5576 LHSTy = LHSExp->getType();
5577
5578 BaseExpr = LHSExp;
5579 IndexExpr = RHSExp;
5580 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5581 } else if (RHSTy->isArrayType()) {
5582 // Same as previous, except for 123[f().a] case
5583 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5584 << RHSExp->getSourceRange();
5585 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5586 CK_ArrayToPointerDecay).get();
5587 RHSTy = RHSExp->getType();
5588
5589 BaseExpr = RHSExp;
5590 IndexExpr = LHSExp;
5591 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5592 } else {
5593 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5594 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5595 }
5596 // C99 6.5.2.1p1
5597 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5598 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5599 << IndexExpr->getSourceRange());
5600
5601 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5602 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5603 && !IndexExpr->isTypeDependent())
5604 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5605
5606 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5607 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5608 // type. Note that Functions are not objects, and that (in C99 parlance)
5609 // incomplete types are not object types.
5610 if (ResultType->isFunctionType()) {
5611 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5612 << ResultType << BaseExpr->getSourceRange();
5613 return ExprError();
5614 }
5615
5616 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5617 // GNU extension: subscripting on pointer to void
5618 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5619 << BaseExpr->getSourceRange();
5620
5621 // C forbids expressions of unqualified void type from being l-values.
5622 // See IsCForbiddenLValueType.
5623 if (!ResultType.hasQualifiers())
5624 VK = VK_PRValue;
5625 } else if (!ResultType->isDependentType() &&
5626 RequireCompleteSizedType(
5627 LLoc, ResultType,
5628 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5629 return ExprError();
5630
5631 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||((void)0)
5632 !ResultType.isCForbiddenLValueType())((void)0);
5633
5634 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5635 FunctionScopes.size() > 1) {
5636 if (auto *TT =
5637 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5638 for (auto I = FunctionScopes.rbegin(),
5639 E = std::prev(FunctionScopes.rend());
5640 I != E; ++I) {
5641 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5642 if (CSI == nullptr)
5643 break;
5644 DeclContext *DC = nullptr;
5645 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5646 DC = LSI->CallOperator;
5647 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5648 DC = CRSI->TheCapturedDecl;
5649 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5650 DC = BSI->TheDecl;
5651 if (DC) {
5652 if (DC->containsDecl(TT->getDecl()))
5653 break;
5654 captureVariablyModifiedType(
5655 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5656 }
5657 }
5658 }
5659 }
5660
5661 return new (Context)
5662 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5663}
5664
5665bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5666 ParmVarDecl *Param) {
5667 if (Param->hasUnparsedDefaultArg()) {
5668 // If we've already cleared out the location for the default argument,
5669 // that means we're parsing it right now.
5670 if (!UnparsedDefaultArgLocs.count(Param)) {
5671 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5672 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5673 Param->setInvalidDecl();
5674 return true;
5675 }
5676
5677 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5678 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5679 Diag(UnparsedDefaultArgLocs[Param],
5680 diag::note_default_argument_declared_here);
5681 return true;
5682 }
5683
5684 if (Param->hasUninstantiatedDefaultArg() &&
5685 InstantiateDefaultArgument(CallLoc, FD, Param))
5686 return true;
5687
5688 assert(Param->hasInit() && "default argument but no initializer?")((void)0);
5689
5690 // If the default expression creates temporaries, we need to
5691 // push them to the current stack of expression temporaries so they'll
5692 // be properly destroyed.
5693 // FIXME: We should really be rebuilding the default argument with new
5694 // bound temporaries; see the comment in PR5810.
5695 // We don't need to do that with block decls, though, because
5696 // blocks in default argument expression can never capture anything.
5697 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5698 // Set the "needs cleanups" bit regardless of whether there are
5699 // any explicit objects.
5700 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5701
5702 // Append all the objects to the cleanup list. Right now, this
5703 // should always be a no-op, because blocks in default argument
5704 // expressions should never be able to capture anything.
5705 assert(!Init->getNumObjects() &&((void)0)
5706 "default argument expression has capturing blocks?")((void)0);
5707 }
5708
5709 // We already type-checked the argument, so we know it works.
5710 // Just mark all of the declarations in this potentially-evaluated expression
5711 // as being "referenced".
5712 EnterExpressionEvaluationContext EvalContext(
5713 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5714 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5715 /*SkipLocalVariables=*/true);
5716 return false;
5717}
5718
5719ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5720 FunctionDecl *FD, ParmVarDecl *Param) {
5721 assert(Param->hasDefaultArg() && "can't build nonexistent default arg")((void)0);
5722 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5723 return ExprError();
5724 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5725}
5726
5727Sema::VariadicCallType
5728Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5729 Expr *Fn) {
5730 if (Proto && Proto->isVariadic()) {
5731 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5732 return VariadicConstructor;
5733 else if (Fn && Fn->getType()->isBlockPointerType())
5734 return VariadicBlock;
5735 else if (FDecl) {
5736 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5737 if (Method->isInstance())
5738 return VariadicMethod;
5739 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5740 return VariadicMethod;
5741 return VariadicFunction;
5742 }
5743 return VariadicDoesNotApply;
5744}
5745
5746namespace {
5747class FunctionCallCCC final : public FunctionCallFilterCCC {
5748public:
5749 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5750 unsigned NumArgs, MemberExpr *ME)
5751 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5752 FunctionName(FuncName) {}
5753
5754 bool ValidateCandidate(const TypoCorrection &candidate) override {
5755 if (!candidate.getCorrectionSpecifier() ||
5756 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5757 return false;
5758 }
5759
5760 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5761 }
5762
5763 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5764 return std::make_unique<FunctionCallCCC>(*this);
5765 }
5766
5767private:
5768 const IdentifierInfo *const FunctionName;
5769};
5770}
5771
5772static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5773 FunctionDecl *FDecl,
5774 ArrayRef<Expr *> Args) {
5775 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5776 DeclarationName FuncName = FDecl->getDeclName();
5777 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5778
5779 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5780 if (TypoCorrection Corrected = S.CorrectTypo(
5781 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5782 S.getScopeForContext(S.CurContext), nullptr, CCC,
5783 Sema::CTK_ErrorRecovery)) {
5784 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5785 if (Corrected.isOverloaded()) {
5786 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5787 OverloadCandidateSet::iterator Best;
5788 for (NamedDecl *CD : Corrected) {
5789 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5790 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5791 OCS);
5792 }
5793 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5794 case OR_Success:
5795 ND = Best->FoundDecl;
5796 Corrected.setCorrectionDecl(ND);
5797 break;
5798 default:
5799 break;
5800 }
5801 }
5802 ND = ND->getUnderlyingDecl();
5803 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5804 return Corrected;
5805 }
5806 }
5807 return TypoCorrection();
5808}
5809
5810/// ConvertArgumentsForCall - Converts the arguments specified in
5811/// Args/NumArgs to the parameter types of the function FDecl with
5812/// function prototype Proto. Call is the call expression itself, and
5813/// Fn is the function expression. For a C++ member function, this
5814/// routine does not attempt to convert the object argument. Returns
5815/// true if the call is ill-formed.
5816bool
5817Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5818 FunctionDecl *FDecl,
5819 const FunctionProtoType *Proto,
5820 ArrayRef<Expr *> Args,
5821 SourceLocation RParenLoc,
5822 bool IsExecConfig) {
5823 // Bail out early if calling a builtin with custom typechecking.
5824 if (FDecl)
5825 if (unsigned ID = FDecl->getBuiltinID())
5826 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5827 return false;
5828
5829 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5830 // assignment, to the types of the corresponding parameter, ...
5831 unsigned NumParams = Proto->getNumParams();
5832 bool Invalid = false;
5833 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5834 unsigned FnKind = Fn->getType()->isBlockPointerType()
5835 ? 1 /* block */
5836 : (IsExecConfig ? 3 /* kernel function (exec config) */
5837 : 0 /* function */);
5838
5839 // If too few arguments are available (and we don't have default
5840 // arguments for the remaining parameters), don't make the call.
5841 if (Args.size() < NumParams) {
5842 if (Args.size() < MinArgs) {
5843 TypoCorrection TC;
5844 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5845 unsigned diag_id =
5846 MinArgs == NumParams && !Proto->isVariadic()
5847 ? diag::err_typecheck_call_too_few_args_suggest
5848 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5849 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5850 << static_cast<unsigned>(Args.size())
5851 << TC.getCorrectionRange());
5852 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5853 Diag(RParenLoc,
5854 MinArgs == NumParams && !Proto->isVariadic()
5855 ? diag::err_typecheck_call_too_few_args_one
5856 : diag::err_typecheck_call_too_few_args_at_least_one)
5857 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5858 else
5859 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5860 ? diag::err_typecheck_call_too_few_args
5861 : diag::err_typecheck_call_too_few_args_at_least)
5862 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5863 << Fn->getSourceRange();
5864
5865 // Emit the location of the prototype.
5866 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5867 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5868
5869 return true;
5870 }
5871 // We reserve space for the default arguments when we create
5872 // the call expression, before calling ConvertArgumentsForCall.
5873 assert((Call->getNumArgs() == NumParams) &&((void)0)
5874 "We should have reserved space for the default arguments before!")((void)0);
5875 }
5876
5877 // If too many are passed and not variadic, error on the extras and drop
5878 // them.
5879 if (Args.size() > NumParams) {
5880 if (!Proto->isVariadic()) {
5881 TypoCorrection TC;
5882 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5883 unsigned diag_id =
5884 MinArgs == NumParams && !Proto->isVariadic()
5885 ? diag::err_typecheck_call_too_many_args_suggest
5886 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5887 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5888 << static_cast<unsigned>(Args.size())
5889 << TC.getCorrectionRange());
5890 } else if (NumParams == 1 && FDecl &&
5891 FDecl->getParamDecl(0)->getDeclName())
5892 Diag(Args[NumParams]->getBeginLoc(),
5893 MinArgs == NumParams
5894 ? diag::err_typecheck_call_too_many_args_one
5895 : diag::err_typecheck_call_too_many_args_at_most_one)
5896 << FnKind << FDecl->getParamDecl(0)
5897 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5898 << SourceRange(Args[NumParams]->getBeginLoc(),
5899 Args.back()->getEndLoc());
5900 else
5901 Diag(Args[NumParams]->getBeginLoc(),
5902 MinArgs == NumParams
5903 ? diag::err_typecheck_call_too_many_args
5904 : diag::err_typecheck_call_too_many_args_at_most)
5905 << FnKind << NumParams << static_cast<unsigned>(Args.size())
5906 << Fn->getSourceRange()
5907 << SourceRange(Args[NumParams]->getBeginLoc(),
5908 Args.back()->getEndLoc());
5909
5910 // Emit the location of the prototype.
5911 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5912 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5913
5914 // This deletes the extra arguments.
5915 Call->shrinkNumArgs(NumParams);
5916 return true;
5917 }
5918 }
5919 SmallVector<Expr *, 8> AllArgs;
5920 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5921
5922 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5923 AllArgs, CallType);
5924 if (Invalid)
5925 return true;
5926 unsigned TotalNumArgs = AllArgs.size();
5927 for (unsigned i = 0; i < TotalNumArgs; ++i)
5928 Call->setArg(i, AllArgs[i]);
5929
5930 Call->computeDependence();
5931 return false;
5932}
5933
5934bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5935 const FunctionProtoType *Proto,
5936 unsigned FirstParam, ArrayRef<Expr *> Args,
5937 SmallVectorImpl<Expr *> &AllArgs,
5938 VariadicCallType CallType, bool AllowExplicit,
5939 bool IsListInitialization) {
5940 unsigned NumParams = Proto->getNumParams();
5941 bool Invalid = false;
5942 size_t ArgIx = 0;
5943 // Continue to check argument types (even if we have too few/many args).
5944 for (unsigned i = FirstParam; i < NumParams; i++) {
5945 QualType ProtoArgType = Proto->getParamType(i);
5946
5947 Expr *Arg;
5948 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5949 if (ArgIx < Args.size()) {
5950 Arg = Args[ArgIx++];
5951
5952 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5953 diag::err_call_incomplete_argument, Arg))
5954 return true;
5955
5956 // Strip the unbridged-cast placeholder expression off, if applicable.
5957 bool CFAudited = false;
5958 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5959 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5960 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5961 Arg = stripARCUnbridgedCast(Arg);
5962 else if (getLangOpts().ObjCAutoRefCount &&
5963 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5964 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5965 CFAudited = true;
5966
5967 if (Proto->getExtParameterInfo(i).isNoEscape() &&
5968 ProtoArgType->isBlockPointerType())
5969 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5970 BE->getBlockDecl()->setDoesNotEscape();
5971
5972 InitializedEntity Entity =
5973 Param ? InitializedEntity::InitializeParameter(Context, Param,
5974 ProtoArgType)
5975 : InitializedEntity::InitializeParameter(
5976 Context, ProtoArgType, Proto->isParamConsumed(i));
5977
5978 // Remember that parameter belongs to a CF audited API.
5979 if (CFAudited)
5980 Entity.setParameterCFAudited();
5981
5982 ExprResult ArgE = PerformCopyInitialization(
5983 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5984 if (ArgE.isInvalid())
5985 return true;
5986
5987 Arg = ArgE.getAs<Expr>();
5988 } else {
5989 assert(Param && "can't use default arguments without a known callee")((void)0);
5990
5991 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5992 if (ArgExpr.isInvalid())
5993 return true;
5994
5995 Arg = ArgExpr.getAs<Expr>();
5996 }
5997
5998 // Check for array bounds violations for each argument to the call. This
5999 // check only triggers warnings when the argument isn't a more complex Expr
6000 // with its own checking, such as a BinaryOperator.
6001 CheckArrayAccess(Arg);
6002
6003 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6004 CheckStaticArrayArgument(CallLoc, Param, Arg);
6005
6006 AllArgs.push_back(Arg);
6007 }
6008
6009 // If this is a variadic call, handle args passed through "...".
6010 if (CallType != VariadicDoesNotApply) {
6011 // Assume that extern "C" functions with variadic arguments that
6012 // return __unknown_anytype aren't *really* variadic.
6013 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6014 FDecl->isExternC()) {
6015 for (Expr *A : Args.slice(ArgIx)) {
6016 QualType paramType; // ignored
6017 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6018 Invalid |= arg.isInvalid();
6019 AllArgs.push_back(arg.get());
6020 }
6021
6022 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6023 } else {
6024 for (Expr *A : Args.slice(ArgIx)) {
6025 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6026 Invalid |= Arg.isInvalid();
6027 AllArgs.push_back(Arg.get());
6028 }
6029 }
6030
6031 // Check for array bounds violations.
6032 for (Expr *A : Args.slice(ArgIx))
6033 CheckArrayAccess(A);
6034 }
6035 return Invalid;
6036}
6037
6038static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6039 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6040 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6041 TL = DTL.getOriginalLoc();
6042 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6043 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6044 << ATL.getLocalSourceRange();
6045}
6046
6047/// CheckStaticArrayArgument - If the given argument corresponds to a static
6048/// array parameter, check that it is non-null, and that if it is formed by
6049/// array-to-pointer decay, the underlying array is sufficiently large.
6050///
6051/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6052/// array type derivation, then for each call to the function, the value of the
6053/// corresponding actual argument shall provide access to the first element of
6054/// an array with at least as many elements as specified by the size expression.
6055void
6056Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6057 ParmVarDecl *Param,
6058 const Expr *ArgExpr) {
6059 // Static array parameters are not supported in C++.
6060 if (!Param || getLangOpts().CPlusPlus)
6061 return;
6062
6063 QualType OrigTy = Param->getOriginalType();
6064
6065 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6066 if (!AT || AT->getSizeModifier() != ArrayType::Static)
6067 return;
6068
6069 if (ArgExpr->isNullPointerConstant(Context,
6070 Expr::NPC_NeverValueDependent)) {
6071 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6072 DiagnoseCalleeStaticArrayParam(*this, Param);
6073 return;
6074 }
6075
6076 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6077 if (!CAT)
6078 return;
6079
6080 const ConstantArrayType *ArgCAT =
6081 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6082 if (!ArgCAT)
6083 return;
6084
6085 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6086 ArgCAT->getElementType())) {
6087 if (ArgCAT->getSize().ult(CAT->getSize())) {
6088 Diag(CallLoc, diag::warn_static_array_too_small)
6089 << ArgExpr->getSourceRange()
6090 << (unsigned)ArgCAT->getSize().getZExtValue()
6091 << (unsigned)CAT->getSize().getZExtValue() << 0;
6092 DiagnoseCalleeStaticArrayParam(*this, Param);
6093 }
6094 return;
6095 }
6096
6097 Optional<CharUnits> ArgSize =
6098 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6099 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6100 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6101 Diag(CallLoc, diag::warn_static_array_too_small)
6102 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6103 << (unsigned)ParmSize->getQuantity() << 1;
6104 DiagnoseCalleeStaticArrayParam(*this, Param);
6105 }
6106}
6107
6108/// Given a function expression of unknown-any type, try to rebuild it
6109/// to have a function type.
6110static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6111
6112/// Is the given type a placeholder that we need to lower out
6113/// immediately during argument processing?
6114static bool isPlaceholderToRemoveAsArg(QualType type) {
6115 // Placeholders are never sugared.
6116 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6117 if (!placeholder) return false;
6118
6119 switch (placeholder->getKind()) {
6120 // Ignore all the non-placeholder types.
6121#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6122 case BuiltinType::Id:
6123#include "clang/Basic/OpenCLImageTypes.def"
6124#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6125 case BuiltinType::Id:
6126#include "clang/Basic/OpenCLExtensionTypes.def"
6127 // In practice we'll never use this, since all SVE types are sugared
6128 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6129#define SVE_TYPE(Name, Id, SingletonId) \
6130 case BuiltinType::Id:
6131#include "clang/Basic/AArch64SVEACLETypes.def"
6132#define PPC_VECTOR_TYPE(Name, Id, Size) \
6133 case BuiltinType::Id:
6134#include "clang/Basic/PPCTypes.def"
6135#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6136#include "clang/Basic/RISCVVTypes.def"
6137#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6138#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6139#include "clang/AST/BuiltinTypes.def"
6140 return false;
6141
6142 // We cannot lower out overload sets; they might validly be resolved
6143 // by the call machinery.
6144 case BuiltinType::Overload:
6145 return false;
6146
6147 // Unbridged casts in ARC can be handled in some call positions and
6148 // should be left in place.
6149 case BuiltinType::ARCUnbridgedCast:
6150 return false;
6151
6152 // Pseudo-objects should be converted as soon as possible.
6153 case BuiltinType::PseudoObject:
6154 return true;
6155
6156 // The debugger mode could theoretically but currently does not try
6157 // to resolve unknown-typed arguments based on known parameter types.
6158 case BuiltinType::UnknownAny:
6159 return true;
6160
6161 // These are always invalid as call arguments and should be reported.
6162 case BuiltinType::BoundMember:
6163 case BuiltinType::BuiltinFn:
6164 case BuiltinType::IncompleteMatrixIdx:
6165 case BuiltinType::OMPArraySection:
6166 case BuiltinType::OMPArrayShaping:
6167 case BuiltinType::OMPIterator:
6168 return true;
6169
6170 }
6171 llvm_unreachable("bad builtin type kind")__builtin_unreachable();
6172}
6173
6174/// Check an argument list for placeholders that we won't try to
6175/// handle later.
6176static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6177 // Apply this processing to all the arguments at once instead of
6178 // dying at the first failure.
6179 bool hasInvalid = false;
6180 for (size_t i = 0, e = args.size(); i != e; i++) {
6181 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6182 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6183 if (result.isInvalid()) hasInvalid = true;
6184 else args[i] = result.get();
6185 }
6186 }
6187 return hasInvalid;
6188}
6189
6190/// If a builtin function has a pointer argument with no explicit address
6191/// space, then it should be able to accept a pointer to any address
6192/// space as input. In order to do this, we need to replace the
6193/// standard builtin declaration with one that uses the same address space
6194/// as the call.
6195///
6196/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6197/// it does not contain any pointer arguments without
6198/// an address space qualifer. Otherwise the rewritten
6199/// FunctionDecl is returned.
6200/// TODO: Handle pointer return types.
6201static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6202 FunctionDecl *FDecl,
6203 MultiExprArg ArgExprs) {
6204
6205 QualType DeclType = FDecl->getType();
6206 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6207
6208 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6209 ArgExprs.size() < FT->getNumParams())
6210 return nullptr;
6211
6212 bool NeedsNewDecl = false;
6213 unsigned i = 0;
6214 SmallVector<QualType, 8> OverloadParams;
6215
6216 for (QualType ParamType : FT->param_types()) {
6217
6218 // Convert array arguments to pointer to simplify type lookup.
6219 ExprResult ArgRes =
6220 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6221 if (ArgRes.isInvalid())
6222 return nullptr;
6223 Expr *Arg = ArgRes.get();
6224 QualType ArgType = Arg->getType();
6225 if (!ParamType->isPointerType() ||
6226 ParamType.hasAddressSpace() ||
6227 !ArgType->isPointerType() ||
6228 !ArgType->getPointeeType().hasAddressSpace()) {
6229 OverloadParams.push_back(ParamType);
6230 continue;
6231 }
6232
6233 QualType PointeeType = ParamType->getPointeeType();
6234 if (PointeeType.hasAddressSpace())
6235 continue;
6236
6237 NeedsNewDecl = true;
6238 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6239
6240 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6241 OverloadParams.push_back(Context.getPointerType(PointeeType));
6242 }
6243
6244 if (!NeedsNewDecl)
6245 return nullptr;
6246
6247 FunctionProtoType::ExtProtoInfo EPI;
6248 EPI.Variadic = FT->isVariadic();
6249 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6250 OverloadParams, EPI);
6251 DeclContext *Parent = FDecl->getParent();
6252 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6253 FDecl->getLocation(),
6254 FDecl->getLocation(),
6255 FDecl->getIdentifier(),
6256 OverloadTy,
6257 /*TInfo=*/nullptr,
6258 SC_Extern, false,
6259 /*hasPrototype=*/true);
6260 SmallVector<ParmVarDecl*, 16> Params;
6261 FT = cast<FunctionProtoType>(OverloadTy);
6262 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6263 QualType ParamType = FT->getParamType(i);
6264 ParmVarDecl *Parm =
6265 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6266 SourceLocation(), nullptr, ParamType,
6267 /*TInfo=*/nullptr, SC_None, nullptr);
6268 Parm->setScopeInfo(0, i);
6269 Params.push_back(Parm);
6270 }
6271 OverloadDecl->setParams(Params);
6272 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6273 return OverloadDecl;
6274}
6275
6276static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6277 FunctionDecl *Callee,
6278 MultiExprArg ArgExprs) {
6279 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6280 // similar attributes) really don't like it when functions are called with an
6281 // invalid number of args.
6282 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6283 /*PartialOverloading=*/false) &&
6284 !Callee->isVariadic())
6285 return;
6286 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6287 return;
6288
6289 if (const EnableIfAttr *Attr =
6290 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6291 S.Diag(Fn->getBeginLoc(),
6292 isa<CXXMethodDecl>(Callee)
6293 ? diag::err_ovl_no_viable_member_function_in_call
6294 : diag::err_ovl_no_viable_function_in_call)
6295 << Callee << Callee->getSourceRange();
6296 S.Diag(Callee->getLocation(),
6297 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6298 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6299 return;
6300 }
6301}
6302
6303static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6304 const UnresolvedMemberExpr *const UME, Sema &S) {
6305
6306 const auto GetFunctionLevelDCIfCXXClass =
6307 [](Sema &S) -> const CXXRecordDecl * {
6308 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6309 if (!DC || !DC->getParent())
6310 return nullptr;
6311
6312 // If the call to some member function was made from within a member
6313 // function body 'M' return return 'M's parent.
6314 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6315 return MD->getParent()->getCanonicalDecl();
6316 // else the call was made from within a default member initializer of a
6317 // class, so return the class.
6318 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6319 return RD->getCanonicalDecl();
6320 return nullptr;
6321 };
6322 // If our DeclContext is neither a member function nor a class (in the
6323 // case of a lambda in a default member initializer), we can't have an
6324 // enclosing 'this'.
6325
6326 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6327 if (!CurParentClass)
6328 return false;
6329
6330 // The naming class for implicit member functions call is the class in which
6331 // name lookup starts.
6332 const CXXRecordDecl *const NamingClass =
6333 UME->getNamingClass()->getCanonicalDecl();
6334 assert(NamingClass && "Must have naming class even for implicit access")((void)0);
6335
6336 // If the unresolved member functions were found in a 'naming class' that is
6337 // related (either the same or derived from) to the class that contains the
6338 // member function that itself contained the implicit member access.
6339
6340 return CurParentClass == NamingClass ||
6341 CurParentClass->isDerivedFrom(NamingClass);
6342}
6343
6344static void
6345tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6346 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6347
6348 if (!UME)
6349 return;
6350
6351 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6352 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6353 // already been captured, or if this is an implicit member function call (if
6354 // it isn't, an attempt to capture 'this' should already have been made).
6355 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6356 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6357 return;
6358
6359 // Check if the naming class in which the unresolved members were found is
6360 // related (same as or is a base of) to the enclosing class.
6361
6362 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6363 return;
6364
6365
6366 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6367 // If the enclosing function is not dependent, then this lambda is
6368 // capture ready, so if we can capture this, do so.
6369 if (!EnclosingFunctionCtx->isDependentContext()) {
6370 // If the current lambda and all enclosing lambdas can capture 'this' -
6371 // then go ahead and capture 'this' (since our unresolved overload set
6372 // contains at least one non-static member function).
6373 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6374 S.CheckCXXThisCapture(CallLoc);
6375 } else if (S.CurContext->isDependentContext()) {
6376 // ... since this is an implicit member reference, that might potentially
6377 // involve a 'this' capture, mark 'this' for potential capture in
6378 // enclosing lambdas.
6379 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6380 CurLSI->addPotentialThisCapture(CallLoc);
6381 }
6382}
6383
6384ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6385 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6386 Expr *ExecConfig) {
6387 ExprResult Call =
6388 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6389 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6390 if (Call.isInvalid())
6391 return Call;
6392
6393 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6394 // language modes.
6395 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6396 if (ULE->hasExplicitTemplateArgs() &&
6397 ULE->decls_begin() == ULE->decls_end()) {
6398 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6399 ? diag::warn_cxx17_compat_adl_only_template_id
6400 : diag::ext_adl_only_template_id)
6401 << ULE->getName();
6402 }
6403 }
6404
6405 if (LangOpts.OpenMP)
6406 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6407 ExecConfig);
6408
6409 return Call;
6410}
6411
6412/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6413/// This provides the location of the left/right parens and a list of comma
6414/// locations.
6415ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6416 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6417 Expr *ExecConfig, bool IsExecConfig,
6418 bool AllowRecovery) {
6419 // Since this might be a postfix expression, get rid of ParenListExprs.
6420 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6421 if (Result.isInvalid()) return ExprError();
6422 Fn = Result.get();
6423
6424 if (checkArgsForPlaceholders(*this, ArgExprs))
6425 return ExprError();
6426
6427 if (getLangOpts().CPlusPlus) {
6428 // If this is a pseudo-destructor expression, build the call immediately.
6429 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6430 if (!ArgExprs.empty()) {
6431 // Pseudo-destructor calls should not have any arguments.
6432 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6433 << FixItHint::CreateRemoval(
6434 SourceRange(ArgExprs.front()->getBeginLoc(),
6435 ArgExprs.back()->getEndLoc()));
6436 }
6437
6438 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6439 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6440 }
6441 if (Fn->getType() == Context.PseudoObjectTy) {
6442 ExprResult result = CheckPlaceholderExpr(Fn);
6443 if (result.isInvalid()) return ExprError();
6444 Fn = result.get();
6445 }
6446
6447 // Determine whether this is a dependent call inside a C++ template,
6448 // in which case we won't do any semantic analysis now.
6449 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6450 if (ExecConfig) {
6451 return CUDAKernelCallExpr::Create(Context, Fn,
6452 cast<CallExpr>(ExecConfig), ArgExprs,
6453 Context.DependentTy, VK_PRValue,
6454 RParenLoc, CurFPFeatureOverrides());
6455 } else {
6456
6457 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6458 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6459 Fn->getBeginLoc());
6460
6461 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6462 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6463 }
6464 }
6465
6466 // Determine whether this is a call to an object (C++ [over.call.object]).
6467 if (Fn->getType()->isRecordType())
6468 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6469 RParenLoc);
6470
6471 if (Fn->getType() == Context.UnknownAnyTy) {
6472 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6473 if (result.isInvalid()) return ExprError();
6474 Fn = result.get();
6475 }
6476
6477 if (Fn->getType() == Context.BoundMemberTy) {
6478 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6479 RParenLoc, AllowRecovery);
6480 }
6481 }
6482
6483 // Check for overloaded calls. This can happen even in C due to extensions.
6484 if (Fn->getType() == Context.OverloadTy) {
6485 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6486
6487 // We aren't supposed to apply this logic if there's an '&' involved.
6488 if (!find.HasFormOfMemberPointer) {
6489 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6490 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6491 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6492 OverloadExpr *ovl = find.Expression;
6493 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6494 return BuildOverloadedCallExpr(
6495 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6496 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6497 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6498 RParenLoc, AllowRecovery);
6499 }
6500 }
6501
6502 // If we're directly calling a function, get the appropriate declaration.
6503 if (Fn->getType() == Context.UnknownAnyTy) {
6504 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6505 if (result.isInvalid()) return ExprError();
6506 Fn = result.get();
6507 }
6508
6509 Expr *NakedFn = Fn->IgnoreParens();
6510
6511 bool CallingNDeclIndirectly = false;
6512 NamedDecl *NDecl = nullptr;
6513 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6514 if (UnOp->getOpcode() == UO_AddrOf) {
6515 CallingNDeclIndirectly = true;
6516 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6517 }
6518 }
6519
6520 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6521 NDecl = DRE->getDecl();
6522
6523 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6524 if (FDecl && FDecl->getBuiltinID()) {
6525 // Rewrite the function decl for this builtin by replacing parameters
6526 // with no explicit address space with the address space of the arguments
6527 // in ArgExprs.
6528 if ((FDecl =
6529 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6530 NDecl = FDecl;
6531 Fn = DeclRefExpr::Create(
6532 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6533 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6534 nullptr, DRE->isNonOdrUse());
6535 }
6536 }
6537 } else if (isa<MemberExpr>(NakedFn))
6538 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6539
6540 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6541 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6542 FD, /*Complain=*/true, Fn->getBeginLoc()))
6543 return ExprError();
6544
6545 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6546 }
6547
6548 if (Context.isDependenceAllowed() &&
6549 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6550 assert(!getLangOpts().CPlusPlus)((void)0);
6551 assert((Fn->containsErrors() ||((void)0)
6552 llvm::any_of(ArgExprs,((void)0)
6553 [](clang::Expr *E) { return E->containsErrors(); })) &&((void)0)
6554 "should only occur in error-recovery path.")((void)0);
6555 QualType ReturnType =
6556 llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6557 ? cast<FunctionDecl>(NDecl)->getCallResultType()
6558 : Context.DependentTy;
6559 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6560 Expr::getValueKindForType(ReturnType), RParenLoc,
6561 CurFPFeatureOverrides());
6562 }
6563 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6564 ExecConfig, IsExecConfig);
6565}
6566
6567/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6568// with the specified CallArgs
6569Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6570 MultiExprArg CallArgs) {
6571 StringRef Name = Context.BuiltinInfo.getName(Id);
6572 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6573 Sema::LookupOrdinaryName);
6574 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6575
6576 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6577 assert(BuiltInDecl && "failed to find builtin declaration")((void)0);
6578
6579 ExprResult DeclRef =
6580 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6581 assert(DeclRef.isUsable() && "Builtin reference cannot fail")((void)0);
6582
6583 ExprResult Call =
6584 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6585
6586 assert(!Call.isInvalid() && "Call to builtin cannot fail!")((void)0);
6587 return Call.get();
6588}
6589
6590/// Parse a __builtin_astype expression.
6591///
6592/// __builtin_astype( value, dst type )
6593///
6594ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6595 SourceLocation BuiltinLoc,
6596 SourceLocation RParenLoc) {
6597 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6598 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6599}
6600
6601/// Create a new AsTypeExpr node (bitcast) from the arguments.
6602ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6603 SourceLocation BuiltinLoc,
6604 SourceLocation RParenLoc) {
6605 ExprValueKind VK = VK_PRValue;
6606 ExprObjectKind OK = OK_Ordinary;
6607 QualType SrcTy = E->getType();
6608 if (!SrcTy->isDependentType() &&
6609 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6610 return ExprError(
6611 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6612 << DestTy << SrcTy << E->getSourceRange());
6613 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6614}
6615
6616/// ActOnConvertVectorExpr - create a new convert-vector expression from the
6617/// provided arguments.
6618///
6619/// __builtin_convertvector( value, dst type )
6620///
6621ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6622 SourceLocation BuiltinLoc,
6623 SourceLocation RParenLoc) {
6624 TypeSourceInfo *TInfo;
6625 GetTypeFromParser(ParsedDestTy, &TInfo);
6626 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6627}
6628
6629/// BuildResolvedCallExpr - Build a call to a resolved expression,
6630/// i.e. an expression not of \p OverloadTy. The expression should
6631/// unary-convert to an expression of function-pointer or
6632/// block-pointer type.
6633///
6634/// \param NDecl the declaration being called, if available
6635ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6636 SourceLocation LParenLoc,
6637 ArrayRef<Expr *> Args,
6638 SourceLocation RParenLoc, Expr *Config,
6639 bool IsExecConfig, ADLCallKind UsesADL) {
6640 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6641 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6642
6643 // Functions with 'interrupt' attribute cannot be called directly.
6644 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6645 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6646 return ExprError();
6647 }
6648
6649 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6650 // so there's some risk when calling out to non-interrupt handler functions
6651 // that the callee might not preserve them. This is easy to diagnose here,
6652 // but can be very challenging to debug.
6653 // Likewise, X86 interrupt handlers may only call routines with attribute
6654 // no_caller_saved_registers since there is no efficient way to
6655 // save and restore the non-GPR state.
6656 if (auto *Caller = getCurFunctionDecl()) {
6657 if (Caller->hasAttr<ARMInterruptAttr>()) {
6658 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6659 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6660 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6661 if (FDecl)
6662 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6663 }
6664 }
6665 if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6666 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6667 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6668 if (FDecl)
6669 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6670 }
6671 }
6672
6673 // Promote the function operand.
6674 // We special-case function promotion here because we only allow promoting
6675 // builtin functions to function pointers in the callee of a call.
6676 ExprResult Result;
6677 QualType ResultTy;
6678 if (BuiltinID &&
6679 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6680 // Extract the return type from the (builtin) function pointer type.
6681 // FIXME Several builtins still have setType in
6682 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6683 // Builtins.def to ensure they are correct before removing setType calls.
6684 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6685 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6686 ResultTy = FDecl->getCallResultType();
6687 } else {
6688 Result = CallExprUnaryConversions(Fn);
6689 ResultTy = Context.BoolTy;
6690 }
6691 if (Result.isInvalid())
6692 return ExprError();
6693 Fn = Result.get();
6694
6695 // Check for a valid function type, but only if it is not a builtin which
6696 // requires custom type checking. These will be handled by
6697 // CheckBuiltinFunctionCall below just after creation of the call expression.
6698 const FunctionType *FuncT = nullptr;
6699 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6700 retry:
6701 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6702 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6703 // have type pointer to function".
6704 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6705 if (!FuncT)
6706 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6707 << Fn->getType() << Fn->getSourceRange());
6708 } else if (const BlockPointerType *BPT =
6709 Fn->getType()->getAs<BlockPointerType>()) {
6710 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6711 } else {
6712 // Handle calls to expressions of unknown-any type.
6713 if (Fn->getType() == Context.UnknownAnyTy) {
6714 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6715 if (rewrite.isInvalid())
6716 return ExprError();
6717 Fn = rewrite.get();
6718 goto retry;
6719 }
6720
6721 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6722 << Fn->getType() << Fn->getSourceRange());
6723 }
6724 }
6725
6726 // Get the number of parameters in the function prototype, if any.
6727 // We will allocate space for max(Args.size(), NumParams) arguments
6728 // in the call expression.
6729 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6730 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6731
6732 CallExpr *TheCall;
6733 if (Config) {
6734 assert(UsesADL == ADLCallKind::NotADL &&((void)0)
6735 "CUDAKernelCallExpr should not use ADL")((void)0);
6736 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6737 Args, ResultTy, VK_PRValue, RParenLoc,
6738 CurFPFeatureOverrides(), NumParams);
6739 } else {
6740 TheCall =
6741 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6742 CurFPFeatureOverrides(), NumParams, UsesADL);
6743 }
6744
6745 if (!Context.isDependenceAllowed()) {
6746 // Forget about the nulled arguments since typo correction
6747 // do not handle them well.
6748 TheCall->shrinkNumArgs(Args.size());
6749 // C cannot always handle TypoExpr nodes in builtin calls and direct
6750 // function calls as their argument checking don't necessarily handle
6751 // dependent types properly, so make sure any TypoExprs have been
6752 // dealt with.
6753 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6754 if (!Result.isUsable()) return ExprError();
6755 CallExpr *TheOldCall = TheCall;
6756 TheCall = dyn_cast<CallExpr>(Result.get());
6757 bool CorrectedTypos = TheCall != TheOldCall;
6758 if (!TheCall) return Result;
6759 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6760
6761 // A new call expression node was created if some typos were corrected.
6762 // However it may not have been constructed with enough storage. In this
6763 // case, rebuild the node with enough storage. The waste of space is
6764 // immaterial since this only happens when some typos were corrected.
6765 if (CorrectedTypos && Args.size() < NumParams) {
6766 if (Config)
6767 TheCall = CUDAKernelCallExpr::Create(
6768 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6769 RParenLoc, CurFPFeatureOverrides(), NumParams);
6770 else
6771 TheCall =
6772 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6773 CurFPFeatureOverrides(), NumParams, UsesADL);
6774 }
6775 // We can now handle the nulled arguments for the default arguments.
6776 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6777 }
6778
6779 // Bail out early if calling a builtin with custom type checking.
6780 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6781 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6782
6783 if (getLangOpts().CUDA) {
6784 if (Config) {
6785 // CUDA: Kernel calls must be to global functions
6786 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6787 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6788 << FDecl << Fn->getSourceRange());
6789
6790 // CUDA: Kernel function must have 'void' return type
6791 if (!FuncT->getReturnType()->isVoidType() &&
6792 !FuncT->getReturnType()->getAs<AutoType>() &&
6793 !FuncT->getReturnType()->isInstantiationDependentType())
6794 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6795 << Fn->getType() << Fn->getSourceRange());
6796 } else {
6797 // CUDA: Calls to global functions must be configured
6798 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6799 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6800 << FDecl << Fn->getSourceRange());
6801 }
6802 }
6803
6804 // Check for a valid return type
6805 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6806 FDecl))
6807 return ExprError();
6808
6809 // We know the result type of the call, set it.
6810 TheCall->setType(FuncT->getCallResultType(Context));
6811 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6812
6813 if (Proto) {
6814 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6815 IsExecConfig))
6816 return ExprError();
6817 } else {
6818 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")((void)0);
6819
6820 if (FDecl) {
6821 // Check if we have too few/too many template arguments, based
6822 // on our knowledge of the function definition.
6823 const FunctionDecl *Def = nullptr;
6824 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6825 Proto = Def->getType()->getAs<FunctionProtoType>();
6826 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6827 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6828 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6829 }
6830
6831 // If the function we're calling isn't a function prototype, but we have
6832 // a function prototype from a prior declaratiom, use that prototype.
6833 if (!FDecl->hasPrototype())
6834 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6835 }
6836
6837 // Promote the arguments (C99 6.5.2.2p6).
6838 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6839 Expr *Arg = Args[i];
6840
6841 if (Proto && i < Proto->getNumParams()) {
6842 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6843 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6844 ExprResult ArgE =
6845 PerformCopyInitialization(Entity, SourceLocation(), Arg);
6846 if (ArgE.isInvalid())
6847 return true;
6848
6849 Arg = ArgE.getAs<Expr>();
6850
6851 } else {
6852 ExprResult ArgE = DefaultArgumentPromotion(Arg);
6853
6854 if (ArgE.isInvalid())
6855 return true;
6856
6857 Arg = ArgE.getAs<Expr>();
6858 }
6859
6860 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6861 diag::err_call_incomplete_argument, Arg))
6862 return ExprError();
6863
6864 TheCall->setArg(i, Arg);
6865 }
6866 TheCall->computeDependence();
6867 }
6868
6869 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6870 if (!Method->isStatic())
6871 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6872 << Fn->getSourceRange());
6873
6874 // Check for sentinels
6875 if (NDecl)
6876 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6877
6878 // Warn for unions passing across security boundary (CMSE).
6879 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6880 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6881 if (const auto *RT =
6882 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6883 if (RT->getDecl()->isOrContainsUnion())
6884 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6885 << 0 << i;
6886 }
6887 }
6888 }
6889
6890 // Do special checking on direct calls to functions.
6891 if (FDecl) {
6892 if (CheckFunctionCall(FDecl, TheCall, Proto))
6893 return ExprError();
6894
6895 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6896
6897 if (BuiltinID)
6898 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6899 } else if (NDecl) {
6900 if (CheckPointerCall(NDecl, TheCall, Proto))
6901 return ExprError();
6902 } else {
6903 if (CheckOtherCall(TheCall, Proto))
6904 return ExprError();
6905 }
6906
6907 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6908}
6909
6910ExprResult
6911Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6912 SourceLocation RParenLoc, Expr *InitExpr) {
6913 assert(Ty && "ActOnCompoundLiteral(): missing type")((void)0);
6914 assert(InitExpr && "ActOnCompoundLiteral(): missing expression")((void)0);
6915
6916 TypeSourceInfo *TInfo;
6917 QualType literalType = GetTypeFromParser(Ty, &TInfo);
6918 if (!TInfo)
6919 TInfo = Context.getTrivialTypeSourceInfo(literalType);
6920
6921 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6922}
6923
6924ExprResult
6925Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6926 SourceLocation RParenLoc, Expr *LiteralExpr) {
6927 QualType literalType = TInfo->getType();
6928
6929 if (literalType->isArrayType()) {
6930 if (RequireCompleteSizedType(
6931 LParenLoc, Context.getBaseElementType(literalType),
6932 diag::err_array_incomplete_or_sizeless_type,
6933 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6934 return ExprError();
6935 if (literalType->isVariableArrayType()) {
6936 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
6937 diag::err_variable_object_no_init)) {
6938 return ExprError();
6939 }
6940 }
6941 } else if (!literalType->isDependentType() &&
6942 RequireCompleteType(LParenLoc, literalType,
6943 diag::err_typecheck_decl_incomplete_type,
6944 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6945 return ExprError();
6946
6947 InitializedEntity Entity
6948 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6949 InitializationKind Kind
6950 = InitializationKind::CreateCStyleCast(LParenLoc,
6951 SourceRange(LParenLoc, RParenLoc),
6952 /*InitList=*/true);
6953 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6954 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6955 &literalType);
6956 if (Result.isInvalid())
6957 return ExprError();
6958 LiteralExpr = Result.get();
6959
6960 bool isFileScope = !CurContext->isFunctionOrMethod();
6961
6962 // In C, compound literals are l-values for some reason.
6963 // For GCC compatibility, in C++, file-scope array compound literals with
6964 // constant initializers are also l-values, and compound literals are
6965 // otherwise prvalues.
6966 //
6967 // (GCC also treats C++ list-initialized file-scope array prvalues with
6968 // constant initializers as l-values, but that's non-conforming, so we don't
6969 // follow it there.)
6970 //
6971 // FIXME: It would be better to handle the lvalue cases as materializing and
6972 // lifetime-extending a temporary object, but our materialized temporaries
6973 // representation only supports lifetime extension from a variable, not "out
6974 // of thin air".
6975 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6976 // is bound to the result of applying array-to-pointer decay to the compound
6977 // literal.
6978 // FIXME: GCC supports compound literals of reference type, which should
6979 // obviously have a value kind derived from the kind of reference involved.
6980 ExprValueKind VK =
6981 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6982 ? VK_PRValue
6983 : VK_LValue;
6984
6985 if (isFileScope)
6986 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6987 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6988 Expr *Init = ILE->getInit(i);
6989 ILE->setInit(i, ConstantExpr::Create(Context, Init));
6990 }
6991
6992 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6993 VK, LiteralExpr, isFileScope);
6994 if (isFileScope) {
6995 if (!LiteralExpr->isTypeDependent() &&
6996 !LiteralExpr->isValueDependent() &&
6997 !literalType->isDependentType()) // C99 6.5.2.5p3
6998 if (CheckForConstantInitializer(LiteralExpr, literalType))
6999 return ExprError();
7000 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7001 literalType.getAddressSpace() != LangAS::Default) {
7002 // Embedded-C extensions to C99 6.5.2.5:
7003 // "If the compound literal occurs inside the body of a function, the
7004 // type name shall not be qualified by an address-space qualifier."
7005 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7006 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7007 return ExprError();
7008 }
7009
7010 if (!isFileScope && !getLangOpts().CPlusPlus) {
7011 // Compound literals that have automatic storage duration are destroyed at
7012 // the end of the scope in C; in C++, they're just temporaries.
7013
7014 // Emit diagnostics if it is or contains a C union type that is non-trivial
7015 // to destruct.
7016 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7017 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7018 NTCUC_CompoundLiteral, NTCUK_Destruct);
7019
7020 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7021 if (literalType.isDestructedType()) {
7022 Cleanup.setExprNeedsCleanups(true);
7023 ExprCleanupObjects.push_back(E);
7024 getCurFunction()->setHasBranchProtectedScope();
7025 }
7026 }
7027
7028 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7029 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7030 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7031 E->getInitializer()->getExprLoc());
7032
7033 return MaybeBindToTemporary(E);
7034}
7035
7036ExprResult
7037Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7038 SourceLocation RBraceLoc) {
7039 // Only produce each kind of designated initialization diagnostic once.
7040 SourceLocation FirstDesignator;
7041 bool DiagnosedArrayDesignator = false;
7042 bool DiagnosedNestedDesignator = false;
7043 bool DiagnosedMixedDesignator = false;
7044
7045 // Check that any designated initializers are syntactically valid in the
7046 // current language mode.
7047 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7048 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7049 if (FirstDesignator.isInvalid())
7050 FirstDesignator = DIE->getBeginLoc();
7051
7052 if (!getLangOpts().CPlusPlus)
7053 break;
7054
7055 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7056 DiagnosedNestedDesignator = true;
7057 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7058 << DIE->getDesignatorsSourceRange();
7059 }
7060
7061 for (auto &Desig : DIE->designators()) {
7062 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7063 DiagnosedArrayDesignator = true;
7064 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7065 << Desig.getSourceRange();
7066 }
7067 }
7068
7069 if (!DiagnosedMixedDesignator &&
7070 !isa<DesignatedInitExpr>(InitArgList[0])) {
7071 DiagnosedMixedDesignator = true;
7072 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7073 << DIE->getSourceRange();
7074 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7075 << InitArgList[0]->getSourceRange();
7076 }
7077 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7078 isa<DesignatedInitExpr>(InitArgList[0])) {
7079 DiagnosedMixedDesignator = true;
7080 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7081 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7082 << DIE->getSourceRange();
7083 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7084 << InitArgList[I]->getSourceRange();
7085 }
7086 }
7087
7088 if (FirstDesignator.isValid()) {
7089 // Only diagnose designated initiaization as a C++20 extension if we didn't
7090 // already diagnose use of (non-C++20) C99 designator syntax.
7091 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7092 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7093 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7094 ? diag::warn_cxx17_compat_designated_init
7095 : diag::ext_cxx_designated_init);
7096 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7097 Diag(FirstDesignator, diag::ext_designated_init);
7098 }
7099 }
7100
7101 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7102}
7103
7104ExprResult
7105Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7106 SourceLocation RBraceLoc) {
7107 // Semantic analysis for initializers is done by ActOnDeclarator() and
7108 // CheckInitializer() - it requires knowledge of the object being initialized.
7109
7110 // Immediately handle non-overload placeholders. Overloads can be
7111 // resolved contextually, but everything else here can't.
7112 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7113 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7114 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7115
7116 // Ignore failures; dropping the entire initializer list because
7117 // of one failure would be terrible for indexing/etc.
7118 if (result.isInvalid()) continue;
7119
7120 InitArgList[I] = result.get();
7121 }
7122 }
7123
7124 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7125 RBraceLoc);
7126 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7127 return E;
7128}
7129
7130/// Do an explicit extend of the given block pointer if we're in ARC.
7131void Sema::maybeExtendBlockObject(ExprResult &E) {
7132 assert(E.get()->getType()->isBlockPointerType())((void)0);
7133 assert(E.get()->isPRValue())((void)0);
7134
7135 // Only do this in an r-value context.
7136 if (!getLangOpts().ObjCAutoRefCount) return;
7137
7138 E = ImplicitCastExpr::Create(
7139 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7140 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7141 Cleanup.setExprNeedsCleanups(true);
7142}
7143
7144/// Prepare a conversion of the given expression to an ObjC object
7145/// pointer type.
7146CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7147 QualType type = E.get()->getType();
7148 if (type->isObjCObjectPointerType()) {
7149 return CK_BitCast;
7150 } else if (type->isBlockPointerType()) {
7151 maybeExtendBlockObject(E);
7152 return CK_BlockPointerToObjCPointerCast;
7153 } else {
7154 assert(type->isPointerType())((void)0);
7155 return CK_CPointerToObjCPointerCast;
7156 }
7157}
7158
7159/// Prepares for a scalar cast, performing all the necessary stages
7160/// except the final cast and returning the kind required.
7161CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7162 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7163 // Also, callers should have filtered out the invalid cases with
7164 // pointers. Everything else should be possible.
7165
7166 QualType SrcTy = Src.get()->getType();
7167 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7168 return CK_NoOp;
7169
7170 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7171 case Type::STK_MemberPointer:
7172 llvm_unreachable("member pointer type in C")__builtin_unreachable();
7173
7174 case Type::STK_CPointer:
7175 case Type::STK_BlockPointer:
7176 case Type::STK_ObjCObjectPointer:
7177 switch (DestTy->getScalarTypeKind()) {
7178 case Type::STK_CPointer: {
7179 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7180 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7181 if (SrcAS != DestAS)
7182 return CK_AddressSpaceConversion;
7183 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7184 return CK_NoOp;
7185 return CK_BitCast;
7186 }
7187 case Type::STK_BlockPointer:
7188 return (SrcKind == Type::STK_BlockPointer
7189 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7190 case Type::STK_ObjCObjectPointer:
7191 if (SrcKind == Type::STK_ObjCObjectPointer)
7192 return CK_BitCast;
7193 if (SrcKind == Type::STK_CPointer)
7194 return CK_CPointerToObjCPointerCast;
7195 maybeExtendBlockObject(Src);
7196 return CK_BlockPointerToObjCPointerCast;
7197 case Type::STK_Bool:
7198 return CK_PointerToBoolean;
7199 case Type::STK_Integral:
7200 return CK_PointerToIntegral;
7201 case Type::STK_Floating:
7202 case Type::STK_FloatingComplex:
7203 case Type::STK_IntegralComplex:
7204 case Type::STK_MemberPointer:
7205 case Type::STK_FixedPoint:
7206 llvm_unreachable("illegal cast from pointer")__builtin_unreachable();
7207 }
7208 llvm_unreachable("Should have returned before this")__builtin_unreachable();
7209
7210 case Type::STK_FixedPoint:
7211 switch (DestTy->getScalarTypeKind()) {
7212 case Type::STK_FixedPoint:
7213 return CK_FixedPointCast;
7214 case Type::STK_Bool:
7215 return CK_FixedPointToBoolean;
7216 case Type::STK_Integral:
7217 return CK_FixedPointToIntegral;
7218 case Type::STK_Floating:
7219 return CK_FixedPointToFloating;
7220 case Type::STK_IntegralComplex:
7221 case Type::STK_FloatingComplex:
7222 Diag(Src.get()->getExprLoc(),
7223 diag::err_unimplemented_conversion_with_fixed_point_type)
7224 << DestTy;
7225 return CK_IntegralCast;
7226 case Type::STK_CPointer:
7227 case Type::STK_ObjCObjectPointer:
7228 case Type::STK_BlockPointer:
7229 case Type::STK_MemberPointer:
7230 llvm_unreachable("illegal cast to pointer type")__builtin_unreachable();
7231 }
7232 llvm_unreachable("Should have returned before this")__builtin_unreachable();
7233
7234 case Type::STK_Bool: // casting from bool is like casting from an integer
7235 case Type::STK_Integral:
7236 switch (DestTy->getScalarTypeKind()) {
7237 case Type::STK_CPointer:
7238 case Type::STK_ObjCObjectPointer:
7239 case Type::STK_BlockPointer:
7240 if (Src.get()->isNullPointerConstant(Context,
7241 Expr::NPC_ValueDependentIsNull))
7242 return CK_NullToPointer;
7243 return CK_IntegralToPointer;
7244 case Type::STK_Bool:
7245 return CK_IntegralToBoolean;
7246 case Type::STK_Integral:
7247 return CK_IntegralCast;
7248 case Type::STK_Floating:
7249 return CK_IntegralToFloating;
7250 case Type::STK_IntegralComplex:
7251 Src = ImpCastExprToType(Src.get(),
7252 DestTy->castAs<ComplexType>()->getElementType(),
7253 CK_IntegralCast);
7254 return CK_IntegralRealToComplex;
7255 case Type::STK_FloatingComplex:
7256 Src = ImpCastExprToType(Src.get(),
7257 DestTy->castAs<ComplexType>()->getElementType(),
7258 CK_IntegralToFloating);
7259 return CK_FloatingRealToComplex;
7260 case Type::STK_MemberPointer:
7261 llvm_unreachable("member pointer type in C")__builtin_unreachable();
7262 case Type::STK_FixedPoint:
7263 return CK_IntegralToFixedPoint;
7264 }
7265 llvm_unreachable("Should have returned before this")__builtin_unreachable();
7266
7267 case Type::STK_Floating:
7268 switch (DestTy->getScalarTypeKind()) {
7269 case Type::STK_Floating:
7270 return CK_FloatingCast;
7271 case Type::STK_Bool:
7272 return CK_FloatingToBoolean;
7273 case Type::STK_Integral:
7274 return CK_FloatingToIntegral;
7275 case Type::STK_FloatingComplex:
7276 Src = ImpCastExprToType(Src.get(),
7277 DestTy->castAs<ComplexType>()->getElementType(),
7278 CK_FloatingCast);
7279 return CK_FloatingRealToComplex;
7280 case Type::STK_IntegralComplex:
7281 Src = ImpCastExprToType(Src.get(),
7282 DestTy->castAs<ComplexType>()->getElementType(),
7283 CK_FloatingToIntegral);
7284 return CK_IntegralRealToComplex;
7285 case Type::STK_CPointer:
7286 case Type::STK_ObjCObjectPointer:
7287 case Type::STK_BlockPointer:
7288 llvm_unreachable("valid float->pointer cast?")__builtin_unreachable();
7289 case Type::STK_MemberPointer:
7290 llvm_unreachable("member pointer type in C")__builtin_unreachable();
7291 case Type::STK_FixedPoint:
7292 return CK_FloatingToFixedPoint;
7293 }
7294 llvm_unreachable("Should have returned before this")__builtin_unreachable();
7295
7296 case Type::STK_FloatingComplex:
7297 switch (DestTy->getScalarTypeKind()) {
7298 case Type::STK_FloatingComplex:
7299 return CK_FloatingComplexCast;
7300 case Type::STK_IntegralComplex:
7301 return CK_FloatingComplexToIntegralComplex;
7302 case Type::STK_Floating: {
7303 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7304 if (Context.hasSameType(ET, DestTy))
7305 return CK_FloatingComplexToReal;
7306 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7307 return CK_FloatingCast;
7308 }
7309 case Type::STK_Bool:
7310 return CK_FloatingComplexToBoolean;
7311 case Type::STK_Integral:
7312 Src = ImpCastExprToType(Src.get(),
7313 SrcTy->castAs<ComplexType>()->getElementType(),
7314 CK_FloatingComplexToReal);
7315 return CK_FloatingToIntegral;
7316 case Type::STK_CPointer:
7317 case Type::STK_ObjCObjectPointer:
7318 case Type::STK_BlockPointer:
7319 llvm_unreachable("valid complex float->pointer cast?")__builtin_unreachable();
7320 case Type::STK_MemberPointer:
7321 llvm_unreachable("member pointer type in C")__builtin_unreachable();
7322 case Type::STK_FixedPoint:
7323 Diag(Src.get()->getExprLoc(),
7324 diag::err_unimplemented_conversion_with_fixed_point_type)
7325 << SrcTy;
7326 return CK_IntegralCast;
7327 }
7328 llvm_unreachable("Should have returned before this")__builtin_unreachable();
7329
7330 case Type::STK_IntegralComplex:
7331 switch (DestTy->getScalarTypeKind()) {
7332 case Type::STK_FloatingComplex:
7333 return CK_IntegralComplexToFloatingComplex;
7334 case Type::STK_IntegralComplex:
7335 return CK_IntegralComplexCast;
7336 case Type::STK_Integral: {
7337 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7338 if (Context.hasSameType(ET, DestTy))
7339 return CK_IntegralComplexToReal;
7340 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7341 return CK_IntegralCast;
7342 }
7343 case Type::STK_Bool:
7344 return CK_IntegralComplexToBoolean;
7345 case Type::STK_Floating:
7346 Src = ImpCastExprToType(Src.get(),
7347 SrcTy->castAs<ComplexType>()->getElementType(),
7348 CK_IntegralComplexToReal);
7349 return CK_IntegralToFloating;
7350 case Type::STK_CPointer:
7351 case Type::STK_ObjCObjectPointer:
7352 case Type::STK_BlockPointer:
7353 llvm_unreachable("valid complex int->pointer cast?")__builtin_unreachable();
7354 case Type::STK_MemberPointer:
7355 llvm_unreachable("member pointer type in C")__builtin_unreachable();
7356 case Type::STK_FixedPoint:
7357 Diag(Src.get()->getExprLoc(),
7358 diag::err_unimplemented_conversion_with_fixed_point_type)
7359 << SrcTy;
7360 return CK_IntegralCast;
7361 }
7362 llvm_unreachable("Should have returned before this")__builtin_unreachable();
7363 }
7364
7365 llvm_unreachable("Unhandled scalar cast")__builtin_unreachable();
7366}
7367
7368static bool breakDownVectorType(QualType type, uint64_t &len,
7369 QualType &eltType) {
7370 // Vectors are simple.
7371 if (const VectorType *vecType = type->getAs<VectorType>()) {
101
Assuming the object is a 'VectorType'
102
Assuming 'vecType' is non-null
103
Taking true branch
108
Assuming the object is a 'VectorType'
109
Assuming 'vecType' is non-null
110
Taking true branch
7372 len = vecType->getNumElements();
7373 eltType = vecType->getElementType();
7374 assert(eltType->isScalarType())((void)0);
7375 return true;
104
Returning the value 1, which participates in a condition later
111
Returning the value 1, which participates in a condition later
7376 }
7377
7378 // We allow lax conversion to and from non-vector types, but only if
7379 // they're real types (i.e. non-complex, non-pointer scalar types).
7380 if (!type->isRealType()) return false;
7381
7382 len = 1;
7383 eltType = type;
7384 return true;
7385}
7386
7387/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7388/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7389/// allowed?
7390///
7391/// This will also return false if the two given types do not make sense from
7392/// the perspective of SVE bitcasts.
7393bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7394 assert(srcTy->isVectorType() || destTy->isVectorType())((void)0);
7395
7396 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7397 if (!FirstType->isSizelessBuiltinType())
7398 return false;
7399
7400 const auto *VecTy = SecondType->getAs<VectorType>();
7401 return VecTy &&
7402 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7403 };
7404
7405 return ValidScalableConversion(srcTy, destTy) ||
7406 ValidScalableConversion(destTy, srcTy);
7407}
7408
7409/// Are the two types matrix types and do they have the same dimensions i.e.
7410/// do they have the same number of rows and the same number of columns?
7411bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7412 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7413 return false;
7414
7415 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7416 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7417
7418 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7419 matSrcType->getNumColumns() == matDestType->getNumColumns();
7420}
7421
7422bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7423 assert(DestTy->isVectorType() || SrcTy->isVectorType())((void)0);
7424
7425 uint64_t SrcLen, DestLen;
7426 QualType SrcEltTy, DestEltTy;
7427 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
100
Calling 'breakDownVectorType'
105
Returning from 'breakDownVectorType'
106
Taking false branch
7428 return false;
7429 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
107
Calling 'breakDownVectorType'
112
Returning from 'breakDownVectorType'
113
Taking false branch
7430 return false;
7431
7432 // ASTContext::getTypeSize will return the size rounded up to a
7433 // power of 2, so instead of using that, we need to use the raw
7434 // element size multiplied by the element count.
7435 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7436 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7437
7438 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
114
Assuming the condition is true
115
Returning the value 1, which participates in a condition later
7439}
7440
7441/// Are the two types lax-compatible vector types? That is, given
7442/// that one of them is a vector, do they have equal storage sizes,
7443/// where the storage size is the number of elements times the element
7444/// size?
7445///
7446/// This will also return false if either of the types is neither a
7447/// vector nor a real type.
7448bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7449 assert(destTy->isVectorType() || srcTy->isVectorType())((void)0);
7450
7451 // Disallow lax conversions between scalars and ExtVectors (these
7452 // conversions are allowed for other vector types because common headers
7453 // depend on them). Most scalar OP ExtVector cases are handled by the
7454 // splat path anyway, which does what we want (convert, not bitcast).
7455 // What this rules out for ExtVectors is crazy things like char4*float.
7456 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
97
Assuming the condition is false
7457 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
98
Assuming the condition is false
7458
7459 return areVectorTypesSameSize(srcTy, destTy);
99
Calling 'Sema::areVectorTypesSameSize'
116
Returning from 'Sema::areVectorTypesSameSize'
117
Returning the value 1, which participates in a condition later
7460}
7461
7462/// Is this a legal conversion between two types, one of which is
7463/// known to be a vector type?
7464bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7465 assert(destTy->isVectorType() || srcTy->isVectorType())((void)0);
7466
7467 switch (Context.getLangOpts().getLaxVectorConversions()) {
94
Control jumps to 'case All:' at line 7485
7468 case LangOptions::LaxVectorConversionKind::None:
7469 return false;
7470
7471 case LangOptions::LaxVectorConversionKind::Integer:
7472 if (!srcTy->isIntegralOrEnumerationType()) {
7473 auto *Vec = srcTy->getAs<VectorType>();
7474 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7475 return false;
7476 }
7477 if (!destTy->isIntegralOrEnumerationType()) {
7478 auto *Vec = destTy->getAs<VectorType>();
7479 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7480 return false;
7481 }
7482 // OK, integer (vector) -> integer (vector) bitcast.
7483 break;
7484
7485 case LangOptions::LaxVectorConversionKind::All:
7486 break;
95
Execution continues on line 7489
7487 }
7488
7489 return areLaxCompatibleVectorTypes(srcTy, destTy);
96
Calling 'Sema::areLaxCompatibleVectorTypes'
118
Returning from 'Sema::areLaxCompatibleVectorTypes'
119
Returning the value 1, which participates in a condition later
7490}
7491
7492bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7493 CastKind &Kind) {
7494 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7495 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7496 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7497 << DestTy << SrcTy << R;
7498 }
7499 } else if (SrcTy->isMatrixType()) {
7500 return Diag(R.getBegin(),
7501 diag::err_invalid_conversion_between_matrix_and_type)
7502 << SrcTy << DestTy << R;
7503 } else if (DestTy->isMatrixType()) {
7504 return Diag(R.getBegin(),
7505 diag::err_invalid_conversion_between_matrix_and_type)
7506 << DestTy << SrcTy << R;
7507 }
7508
7509 Kind = CK_MatrixCast;
7510 return false;
7511}
7512
7513bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7514 CastKind &Kind) {
7515 assert(VectorTy->isVectorType() && "Not a vector type!")((void)0);
7516
7517 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7518 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7519 return Diag(R.getBegin(),
7520 Ty->isVectorType() ?
7521 diag::err_invalid_conversion_between_vectors :
7522 diag::err_invalid_conversion_between_vector_and_integer)
7523 << VectorTy << Ty << R;
7524 } else
7525 return Diag(R.getBegin(),
7526 diag::err_invalid_conversion_between_vector_and_scalar)
7527 << VectorTy << Ty << R;
7528
7529 Kind = CK_BitCast;
7530 return false;
7531}
7532
7533ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7534 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7535
7536 if (DestElemTy == SplattedExpr->getType())
7537 return SplattedExpr;
7538
7539 assert(DestElemTy->isFloatingType() ||((void)0)
7540 DestElemTy->isIntegralOrEnumerationType())((void)0);
7541
7542 CastKind CK;
7543 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7544 // OpenCL requires that we convert `true` boolean expressions to -1, but
7545 // only when splatting vectors.
7546 if (DestElemTy->isFloatingType()) {
7547 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7548 // in two steps: boolean to signed integral, then to floating.
7549 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7550 CK_BooleanToSignedIntegral);
7551 SplattedExpr = CastExprRes.get();
7552 CK = CK_IntegralToFloating;
7553 } else {
7554 CK = CK_BooleanToSignedIntegral;
7555 }
7556 } else {
7557 ExprResult CastExprRes = SplattedExpr;
7558 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7559 if (CastExprRes.isInvalid())
7560 return ExprError();
7561 SplattedExpr = CastExprRes.get();
7562 }
7563 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7564}
7565
7566ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7567 Expr *CastExpr, CastKind &Kind) {
7568 assert(DestTy->isExtVectorType() && "Not an extended vector type!")((void)0);
7569
7570 QualType SrcTy = CastExpr->getType();
7571
7572 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7573 // an ExtVectorType.
7574 // In OpenCL, casts between vectors of different types are not allowed.
7575 // (See OpenCL 6.2).
7576 if (SrcTy->isVectorType()) {
7577 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7578 (getLangOpts().OpenCL &&
7579 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7580 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7581 << DestTy << SrcTy << R;
7582 return ExprError();
7583 }
7584 Kind = CK_BitCast;
7585 return CastExpr;
7586 }
7587
7588 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7589 // conversion will take place first from scalar to elt type, and then
7590 // splat from elt type to vector.
7591 if (SrcTy->isPointerType())
7592 return Diag(R.getBegin(),
7593 diag::err_invalid_conversion_between_vector_and_scalar)
7594 << DestTy << SrcTy << R;
7595
7596 Kind = CK_VectorSplat;
7597 return prepareVectorSplat(DestTy, CastExpr);
7598}
7599
7600ExprResult
7601Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7602 Declarator &D, ParsedType &Ty,
7603 SourceLocation RParenLoc, Expr *CastExpr) {
7604 assert(!D.isInvalidType() && (CastExpr != nullptr) &&((void)0)
7605 "ActOnCastExpr(): missing type or expr")((void)0);
7606
7607 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7608 if (D.isInvalidType())
7609 return ExprError();
7610
7611 if (getLangOpts().CPlusPlus) {
7612 // Check that there are no default arguments (C++ only).
7613 CheckExtraCXXDefaultArguments(D);
7614 } else {
7615 // Make sure any TypoExprs have been dealt with.
7616 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7617 if (!Res.isUsable())
7618 return ExprError();
7619 CastExpr = Res.get();
7620 }
7621
7622 checkUnusedDeclAttributes(D);
7623
7624 QualType castType = castTInfo->getType();
7625 Ty = CreateParsedType(castType, castTInfo);
7626
7627 bool isVectorLiteral = false;
7628
7629 // Check for an altivec or OpenCL literal,
7630 // i.e. all the elements are integer constants.
7631 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7632 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7633 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7634 && castType->isVectorType() && (PE || PLE)) {
7635 if (PLE && PLE->getNumExprs() == 0) {
7636 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7637 return ExprError();
7638 }
7639 if (PE || PLE->getNumExprs() == 1) {
7640 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7641 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7642 isVectorLiteral = true;
7643 }
7644 else
7645 isVectorLiteral = true;
7646 }
7647
7648 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7649 // then handle it as such.
7650 if (isVectorLiteral)
7651 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7652
7653 // If the Expr being casted is a ParenListExpr, handle it specially.
7654 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7655 // sequence of BinOp comma operators.
7656 if (isa<ParenListExpr>(CastExpr)) {
7657 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7658 if (Result.isInvalid()) return ExprError();
7659 CastExpr = Result.get();
7660 }
7661
7662 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7663 !getSourceManager().isInSystemMacro(LParenLoc))
7664 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7665
7666 CheckTollFreeBridgeCast(castType, CastExpr);
7667
7668 CheckObjCBridgeRelatedCast(castType, CastExpr);
7669
7670 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7671
7672 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7673}
7674
7675ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7676 SourceLocation RParenLoc, Expr *E,
7677 TypeSourceInfo *TInfo) {
7678 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&((void)0)
7679 "Expected paren or paren list expression")((void)0);
7680
7681 Expr **exprs;
7682 unsigned numExprs;
7683 Expr *subExpr;
7684 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7685 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7686 LiteralLParenLoc = PE->getLParenLoc();
7687 LiteralRParenLoc = PE->getRParenLoc();
7688 exprs = PE->getExprs();
7689 numExprs = PE->getNumExprs();
7690 } else { // isa<ParenExpr> by assertion at function entrance
7691 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7692 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7693 subExpr = cast<ParenExpr>(E)->getSubExpr();
7694 exprs = &subExpr;
7695 numExprs = 1;
7696 }
7697
7698 QualType Ty = TInfo->getType();
7699 assert(Ty->isVectorType() && "Expected vector type")((void)0);
7700
7701 SmallVector<Expr *, 8> initExprs;
7702 const VectorType *VTy = Ty->castAs<VectorType>();
7703 unsigned numElems = VTy->getNumElements();
7704
7705 // '(...)' form of vector initialization in AltiVec: the number of
7706 // initializers must be one or must match the size of the vector.
7707 // If a single value is specified in the initializer then it will be
7708 // replicated to all the components of the vector
7709 if (ShouldSplatAltivecScalarInCast(VTy)) {
7710 // The number of initializers must be one or must match the size of the
7711 // vector. If a single value is specified in the initializer then it will
7712 // be replicated to all the components of the vector
7713 if (numExprs == 1) {
7714 QualType ElemTy = VTy->getElementType();
7715 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7716 if (Literal.isInvalid())
7717 return ExprError();
7718 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7719 PrepareScalarCast(Literal, ElemTy));
7720 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7721 }
7722 else if (numExprs < numElems) {
7723 Diag(E->getExprLoc(),
7724 diag::err_incorrect_number_of_vector_initializers);
7725 return ExprError();
7726 }
7727 else
7728 initExprs.append(exprs, exprs + numExprs);
7729 }
7730 else {
7731 // For OpenCL, when the number of initializers is a single value,
7732 // it will be replicated to all components of the vector.
7733 if (getLangOpts().OpenCL &&
7734 VTy->getVectorKind() == VectorType::GenericVector &&
7735 numExprs == 1) {
7736 QualType ElemTy = VTy->getElementType();
7737 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7738 if (Literal.isInvalid())
7739 return ExprError();
7740 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7741 PrepareScalarCast(Literal, ElemTy));
7742 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7743 }
7744
7745 initExprs.append(exprs, exprs + numExprs);
7746 }
7747 // FIXME: This means that pretty-printing the final AST will produce curly
7748 // braces instead of the original commas.
7749 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7750 initExprs, LiteralRParenLoc);
7751 initE->setType(Ty);
7752 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7753}
7754
7755/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7756/// the ParenListExpr into a sequence of comma binary operators.
7757ExprResult
7758Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7759 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7760 if (!E)
7761 return OrigExpr;
7762
7763 ExprResult Result(E->getExpr(0));
7764
7765 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7766 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7767 E->getExpr(i));
7768
7769 if (Result.isInvalid()) return ExprError();
7770
7771 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7772}
7773
7774ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7775 SourceLocation R,
7776 MultiExprArg Val) {
7777 return ParenListExpr::Create(Context, L, Val, R);
7778}
7779
7780/// Emit a specialized diagnostic when one expression is a null pointer
7781/// constant and the other is not a pointer. Returns true if a diagnostic is
7782/// emitted.
7783bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7784 SourceLocation QuestionLoc) {
7785 Expr *NullExpr = LHSExpr;
7786 Expr *NonPointerExpr = RHSExpr;
7787 Expr::NullPointerConstantKind NullKind =
7788 NullExpr->isNullPointerConstant(Context,
7789 Expr::NPC_ValueDependentIsNotNull);
7790
7791 if (NullKind == Expr::NPCK_NotNull) {
7792 NullExpr = RHSExpr;
7793 NonPointerExpr = LHSExpr;
7794 NullKind =
7795 NullExpr->isNullPointerConstant(Context,
7796 Expr::NPC_ValueDependentIsNotNull);
7797 }
7798
7799 if (NullKind == Expr::NPCK_NotNull)
7800 return false;
7801
7802 if (NullKind == Expr::NPCK_ZeroExpression)
7803 return false;
7804
7805 if (NullKind == Expr::NPCK_ZeroLiteral) {
7806 // In this case, check to make sure that we got here from a "NULL"
7807 // string in the source code.
7808 NullExpr = NullExpr->IgnoreParenImpCasts();
7809 SourceLocation loc = NullExpr->getExprLoc();
7810 if (!findMacroSpelling(loc, "NULL"))
7811 return false;
7812 }
7813
7814 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7815 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7816 << NonPointerExpr->getType() << DiagType
7817 << NonPointerExpr->getSourceRange();
7818 return true;
7819}
7820
7821/// Return false if the condition expression is valid, true otherwise.
7822static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7823 QualType CondTy = Cond->getType();
7824
7825 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7826 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7827 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7828 << CondTy << Cond->getSourceRange();
7829 return true;
7830 }
7831
7832 // C99 6.5.15p2
7833 if (CondTy->isScalarType()) return false;
7834
7835 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7836 << CondTy << Cond->getSourceRange();
7837 return true;
7838}
7839
7840/// Handle when one or both operands are void type.
7841static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7842 ExprResult &RHS) {
7843 Expr *LHSExpr = LHS.get();
7844 Expr *RHSExpr = RHS.get();
7845
7846 if (!LHSExpr->getType()->isVoidType())
7847 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7848 << RHSExpr->getSourceRange();
7849 if (!RHSExpr->getType()->isVoidType())
7850 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7851 << LHSExpr->getSourceRange();
7852 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7853 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7854 return S.Context.VoidTy;
7855}
7856
7857/// Return false if the NullExpr can be promoted to PointerTy,
7858/// true otherwise.
7859static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7860 QualType PointerTy) {
7861 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7862 !NullExpr.get()->isNullPointerConstant(S.Context,
7863 Expr::NPC_ValueDependentIsNull))
7864 return true;
7865
7866 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7867 return false;
7868}
7869
7870/// Checks compatibility between two pointers and return the resulting
7871/// type.
7872static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7873 ExprResult &RHS,
7874 SourceLocation Loc) {
7875 QualType LHSTy = LHS.get()->getType();
7876 QualType RHSTy = RHS.get()->getType();
7877
7878 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7879 // Two identical pointers types are always compatible.
7880 return LHSTy;
7881 }
7882
7883 QualType lhptee, rhptee;
7884
7885 // Get the pointee types.
7886 bool IsBlockPointer = false;
7887 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7888 lhptee = LHSBTy->getPointeeType();
7889 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7890 IsBlockPointer = true;
7891 } else {
7892 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7893 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7894 }
7895
7896 // C99 6.5.15p6: If both operands are pointers to compatible types or to
7897 // differently qualified versions of compatible types, the result type is
7898 // a pointer to an appropriately qualified version of the composite
7899 // type.
7900
7901 // Only CVR-qualifiers exist in the standard, and the differently-qualified
7902 // clause doesn't make sense for our extensions. E.g. address space 2 should
7903 // be incompatible with address space 3: they may live on different devices or
7904 // anything.
7905 Qualifiers lhQual = lhptee.getQualifiers();
7906 Qualifiers rhQual = rhptee.getQualifiers();
7907
7908 LangAS ResultAddrSpace = LangAS::Default;
7909 LangAS LAddrSpace = lhQual.getAddressSpace();
7910 LangAS RAddrSpace = rhQual.getAddressSpace();
7911
7912 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7913 // spaces is disallowed.
7914 if (lhQual.isAddressSpaceSupersetOf(rhQual))
7915 ResultAddrSpace = LAddrSpace;
7916 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7917 ResultAddrSpace = RAddrSpace;
7918 else {
7919 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7920 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7921 << RHS.get()->getSourceRange();
7922 return QualType();
7923 }
7924
7925 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7926 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7927 lhQual.removeCVRQualifiers();
7928 rhQual.removeCVRQualifiers();
7929
7930 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7931 // (C99 6.7.3) for address spaces. We assume that the check should behave in
7932 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7933 // qual types are compatible iff
7934 // * corresponded types are compatible
7935 // * CVR qualifiers are equal
7936 // * address spaces are equal
7937 // Thus for conditional operator we merge CVR and address space unqualified
7938 // pointees and if there is a composite type we return a pointer to it with
7939 // merged qualifiers.
7940 LHSCastKind =
7941 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7942 RHSCastKind =
7943 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7944 lhQual.removeAddressSpace();
7945 rhQual.removeAddressSpace();
7946
7947 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7948 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7949
7950 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7951
7952 if (CompositeTy.isNull()) {
7953 // In this situation, we assume void* type. No especially good
7954 // reason, but this is what gcc does, and we do have to pick
7955 // to get a consistent AST.
7956 QualType incompatTy;
7957 incompatTy = S.Context.getPointerType(
7958 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7959 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7960 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7961
7962 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7963 // for casts between types with incompatible address space qualifiers.
7964 // For the following code the compiler produces casts between global and
7965 // local address spaces of the corresponded innermost pointees:
7966 // local int *global *a;
7967 // global int *global *b;
7968 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7969 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7970 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7971 << RHS.get()->getSourceRange();
7972
7973 return incompatTy;
7974 }
7975
7976 // The pointer types are compatible.
7977 // In case of OpenCL ResultTy should have the address space qualifier
7978 // which is a superset of address spaces of both the 2nd and the 3rd
7979 // operands of the conditional operator.
7980 QualType ResultTy = [&, ResultAddrSpace]() {
7981 if (S.getLangOpts().OpenCL) {
7982 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7983 CompositeQuals.setAddressSpace(ResultAddrSpace);
7984 return S.Context
7985 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7986 .withCVRQualifiers(MergedCVRQual);
7987 }
7988 return CompositeTy.withCVRQualifiers(MergedCVRQual);
7989 }();
7990 if (IsBlockPointer)
7991 ResultTy = S.Context.getBlockPointerType(ResultTy);
7992 else
7993 ResultTy = S.Context.getPointerType(ResultTy);
7994
7995 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7996 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7997 return ResultTy;
7998}
7999
8000/// Return the resulting type when the operands are both block pointers.
8001static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8002 ExprResult &LHS,
8003 ExprResult &RHS,
8004 SourceLocation Loc) {
8005 QualType LHSTy = LHS.get()->getType();
8006 QualType RHSTy = RHS.get()->getType();
8007
8008 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8009 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8010 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8011 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8012 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8013 return destType;
8014 }
8015 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8016 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8017 << RHS.get()->getSourceRange();
8018 return QualType();
8019 }
8020
8021 // We have 2 block pointer types.
8022 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8023}
8024
8025/// Return the resulting type when the operands are both pointers.
8026static QualType
8027checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8028 ExprResult &RHS,
8029 SourceLocation Loc) {
8030 // get the pointer types
8031 QualType LHSTy = LHS.get()->getType();
8032 QualType RHSTy = RHS.get()->getType();
8033
8034 // get the "pointed to" types
8035 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8036 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8037
8038 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8039 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8040 // Figure out necessary qualifiers (C99 6.5.15p6)
8041 QualType destPointee
8042 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8043 QualType destType = S.Context.getPointerType(destPointee);
8044 // Add qualifiers if necessary.
8045 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8046 // Promote to void*.
8047 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8048 return destType;
8049 }
8050 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8051 QualType destPointee
8052 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8053 QualType destType = S.Context.getPointerType(destPointee);
8054 // Add qualifiers if necessary.
8055 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8056 // Promote to void*.
8057 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8058 return destType;
8059 }
8060
8061 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8062}
8063
8064/// Return false if the first expression is not an integer and the second
8065/// expression is not a pointer, true otherwise.
8066static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8067 Expr* PointerExpr, SourceLocation Loc,
8068 bool IsIntFirstExpr) {
8069 if (!PointerExpr->getType()->isPointerType() ||
8070 !Int.get()->getType()->isIntegerType())
8071 return false;
8072
8073 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8074 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8075
8076 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8077 << Expr1->getType() << Expr2->getType()
8078 << Expr1->getSourceRange() << Expr2->getSourceRange();
8079 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8080 CK_IntegralToPointer);
8081 return true;
8082}
8083
8084/// Simple conversion between integer and floating point types.
8085///
8086/// Used when handling the OpenCL conditional operator where the
8087/// condition is a vector while the other operands are scalar.
8088///
8089/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8090/// types are either integer or floating type. Between the two
8091/// operands, the type with the higher rank is defined as the "result
8092/// type". The other operand needs to be promoted to the same type. No
8093/// other type promotion is allowed. We cannot use
8094/// UsualArithmeticConversions() for this purpose, since it always
8095/// promotes promotable types.
8096static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8097 ExprResult &RHS,
8098 SourceLocation QuestionLoc) {
8099 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8100 if (LHS.isInvalid())
8101 return QualType();
8102 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8103 if (RHS.isInvalid())
8104 return QualType();
8105
8106 // For conversion purposes, we ignore any qualifiers.
8107 // For example, "const float" and "float" are equivalent.
8108 QualType LHSType =
8109 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8110 QualType RHSType =
8111 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8112
8113 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8114 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8115 << LHSType << LHS.get()->getSourceRange();
8116 return QualType();
8117 }
8118
8119 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8120 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8121 << RHSType << RHS.get()->getSourceRange();
8122 return QualType();
8123 }
8124
8125 // If both types are identical, no conversion is needed.
8126 if (LHSType == RHSType)
8127 return LHSType;
8128
8129 // Now handle "real" floating types (i.e. float, double, long double).
8130 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8131 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8132 /*IsCompAssign = */ false);
8133
8134 // Finally, we have two differing integer types.
8135 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8136 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8137}
8138
8139/// Convert scalar operands to a vector that matches the
8140/// condition in length.
8141///
8142/// Used when handling the OpenCL conditional operator where the
8143/// condition is a vector while the other operands are scalar.
8144///
8145/// We first compute the "result type" for the scalar operands
8146/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8147/// into a vector of that type where the length matches the condition
8148/// vector type. s6.11.6 requires that the element types of the result
8149/// and the condition must have the same number of bits.
8150static QualType
8151OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8152 QualType CondTy, SourceLocation QuestionLoc) {
8153 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8154 if (ResTy.isNull()) return QualType();
8155
8156 const VectorType *CV = CondTy->getAs<VectorType>();
8157 assert(CV)((void)0);
8158
8159 // Determine the vector result type
8160 unsigned NumElements = CV->getNumElements();
8161 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8162
8163 // Ensure that all types have the same number of bits
8164 if (S.Context.getTypeSize(CV->getElementType())
8165 != S.Context.getTypeSize(ResTy)) {
8166 // Since VectorTy is created internally, it does not pretty print
8167 // with an OpenCL name. Instead, we just print a description.
8168 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8169 SmallString<64> Str;
8170 llvm::raw_svector_ostream OS(Str);
8171 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8172 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8173 << CondTy << OS.str();
8174 return QualType();
8175 }
8176
8177 // Convert operands to the vector result type
8178 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8179 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8180
8181 return VectorTy;
8182}
8183
8184/// Return false if this is a valid OpenCL condition vector
8185static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8186 SourceLocation QuestionLoc) {
8187 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8188 // integral type.
8189 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8190 assert(CondTy)((void)0);
8191 QualType EleTy = CondTy->getElementType();
8192 if (EleTy->isIntegerType()) return false;
8193
8194 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8195 << Cond->getType() << Cond->getSourceRange();
8196 return true;
8197}
8198
8199/// Return false if the vector condition type and the vector
8200/// result type are compatible.
8201///
8202/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8203/// number of elements, and their element types have the same number
8204/// of bits.
8205static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8206 SourceLocation QuestionLoc) {
8207 const VectorType *CV = CondTy->getAs<VectorType>();
8208 const VectorType *RV = VecResTy->getAs<VectorType>();
8209 assert(CV && RV)((void)0);
8210
8211 if (CV->getNumElements() != RV->getNumElements()) {
8212 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8213 << CondTy << VecResTy;
8214 return true;
8215 }
8216
8217 QualType CVE = CV->getElementType();
8218 QualType RVE = RV->getElementType();
8219
8220 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8221 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8222 << CondTy << VecResTy;
8223 return true;
8224 }
8225
8226 return false;
8227}
8228
8229/// Return the resulting type for the conditional operator in
8230/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8231/// s6.3.i) when the condition is a vector type.
8232static QualType
8233OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8234 ExprResult &LHS, ExprResult &RHS,
8235 SourceLocation QuestionLoc) {
8236 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8237 if (Cond.isInvalid())
8238 return QualType();
8239 QualType CondTy = Cond.get()->getType();
8240
8241 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8242 return QualType();
8243
8244 // If either operand is a vector then find the vector type of the
8245 // result as specified in OpenCL v1.1 s6.3.i.
8246 if (LHS.get()->getType()->isVectorType() ||
8247 RHS.get()->getType()->isVectorType()) {
8248 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8249 /*isCompAssign*/false,
8250 /*AllowBothBool*/true,
8251 /*AllowBoolConversions*/false);
8252 if (VecResTy.isNull()) return QualType();
8253 // The result type must match the condition type as specified in
8254 // OpenCL v1.1 s6.11.6.
8255 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8256 return QualType();
8257 return VecResTy;
8258 }
8259
8260 // Both operands are scalar.
8261 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8262}
8263
8264/// Return true if the Expr is block type
8265static bool checkBlockType(Sema &S, const Expr *E) {
8266 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8267 QualType Ty = CE->getCallee()->getType();
8268 if (Ty->isBlockPointerType()) {
8269 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8270 return true;
8271 }
8272 }
8273 return false;
8274}
8275
8276/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8277/// In that case, LHS = cond.
8278/// C99 6.5.15
8279QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8280 ExprResult &RHS, ExprValueKind &VK,
8281 ExprObjectKind &OK,
8282 SourceLocation QuestionLoc) {
8283
8284 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8285 if (!LHSResult.isUsable()) return QualType();
8286 LHS = LHSResult;
8287
8288 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8289 if (!RHSResult.isUsable()) return QualType();
8290 RHS = RHSResult;
8291
8292 // C++ is sufficiently different to merit its own checker.
8293 if (getLangOpts().CPlusPlus)
8294 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8295
8296 VK = VK_PRValue;
8297 OK = OK_Ordinary;
8298
8299 if (Context.isDependenceAllowed() &&
8300 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8301 RHS.get()->isTypeDependent())) {
8302 assert(!getLangOpts().CPlusPlus)((void)0);
8303 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||((void)0)
8304 RHS.get()->containsErrors()) &&((void)0)
8305 "should only occur in error-recovery path.")((void)0);
8306 return Context.DependentTy;
8307 }
8308
8309 // The OpenCL operator with a vector condition is sufficiently
8310 // different to merit its own checker.
8311 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8312 Cond.get()->getType()->isExtVectorType())
8313 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8314
8315 // First, check the condition.
8316 Cond = UsualUnaryConversions(Cond.get());
8317 if (Cond.isInvalid())
8318 return QualType();
8319 if (checkCondition(*this, Cond.get(), QuestionLoc))
8320 return QualType();
8321
8322 // Now check the two expressions.
8323 if (LHS.get()->getType()->isVectorType() ||
8324 RHS.get()->getType()->isVectorType())
8325 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8326 /*AllowBothBool*/true,
8327 /*AllowBoolConversions*/false);
8328
8329 QualType ResTy =
8330 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8331 if (LHS.isInvalid() || RHS.isInvalid())
8332 return QualType();
8333
8334 QualType LHSTy = LHS.get()->getType();
8335 QualType RHSTy = RHS.get()->getType();
8336
8337 // Diagnose attempts to convert between __float128 and long double where
8338 // such conversions currently can't be handled.
8339 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8340 Diag(QuestionLoc,
8341 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8342 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8343 return QualType();
8344 }
8345
8346 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8347 // selection operator (?:).
8348 if (getLangOpts().OpenCL &&
8349 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8350 return QualType();
8351 }
8352
8353 // If both operands have arithmetic type, do the usual arithmetic conversions
8354 // to find a common type: C99 6.5.15p3,5.
8355 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8356 // Disallow invalid arithmetic conversions, such as those between ExtInts of
8357 // different sizes, or between ExtInts and other types.
8358 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8359 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8360 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8361 << RHS.get()->getSourceRange();
8362 return QualType();
8363 }
8364
8365 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8366 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8367
8368 return ResTy;
8369 }
8370
8371 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8372 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8373 return LHSTy;
8374 }
8375
8376 // If both operands are the same structure or union type, the result is that
8377 // type.
8378 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8379 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8380 if (LHSRT->getDecl() == RHSRT->getDecl())
8381 // "If both the operands have structure or union type, the result has
8382 // that type." This implies that CV qualifiers are dropped.
8383 return LHSTy.getUnqualifiedType();
8384 // FIXME: Type of conditional expression must be complete in C mode.
8385 }
8386
8387 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8388 // The following || allows only one side to be void (a GCC-ism).
8389 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8390 return checkConditionalVoidType(*this, LHS, RHS);
8391 }
8392
8393 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8394 // the type of the other operand."
8395 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8396 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8397
8398 // All objective-c pointer type analysis is done here.
8399 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8400 QuestionLoc);
8401 if (LHS.isInvalid() || RHS.isInvalid())
8402 return QualType();
8403 if (!compositeType.isNull())
8404 return compositeType;
8405
8406
8407 // Handle block pointer types.
8408 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8409 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8410 QuestionLoc);
8411
8412 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8413 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8414 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8415 QuestionLoc);
8416
8417 // GCC compatibility: soften pointer/integer mismatch. Note that
8418 // null pointers have been filtered out by this point.
8419 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8420 /*IsIntFirstExpr=*/true))
8421 return RHSTy;
8422 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8423 /*IsIntFirstExpr=*/false))
8424 return LHSTy;
8425
8426 // Allow ?: operations in which both operands have the same
8427 // built-in sizeless type.
8428 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8429 return LHSTy;
8430
8431 // Emit a better diagnostic if one of the expressions is a null pointer
8432 // constant and the other is not a pointer type. In this case, the user most
8433 // likely forgot to take the address of the other expression.
8434 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8435 return QualType();
8436
8437 // Otherwise, the operands are not compatible.
8438 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8439 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8440 << RHS.get()->getSourceRange();
8441 return QualType();
8442}
8443
8444/// FindCompositeObjCPointerType - Helper method to find composite type of
8445/// two objective-c pointer types of the two input expressions.
8446QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8447 SourceLocation QuestionLoc) {
8448 QualType LHSTy = LHS.get()->getType();
8449 QualType RHSTy = RHS.get()->getType();
8450
8451 // Handle things like Class and struct objc_class*. Here we case the result
8452 // to the pseudo-builtin, because that will be implicitly cast back to the
8453 // redefinition type if an attempt is made to access its fields.
8454 if (LHSTy->isObjCClassType() &&
8455 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8456 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8457 return LHSTy;
8458 }
8459 if (RHSTy->isObjCClassType() &&
8460 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8461 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8462 return RHSTy;
8463 }
8464 // And the same for struct objc_object* / id
8465 if (LHSTy->isObjCIdType() &&
8466 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8467 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8468 return LHSTy;
8469 }
8470 if (RHSTy->isObjCIdType() &&
8471 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8472 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8473 return RHSTy;
8474 }
8475 // And the same for struct objc_selector* / SEL
8476 if (Context.isObjCSelType(LHSTy) &&
8477 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8478 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8479 return LHSTy;
8480 }
8481 if (Context.isObjCSelType(RHSTy) &&
8482 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8483 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8484 return RHSTy;
8485 }
8486 // Check constraints for Objective-C object pointers types.
8487 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8488
8489 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8490 // Two identical object pointer types are always compatible.
8491 return LHSTy;
8492 }
8493 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8494 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8495 QualType compositeType = LHSTy;
8496
8497 // If both operands are interfaces and either operand can be
8498 // assigned to the other, use that type as the composite
8499 // type. This allows
8500 // xxx ? (A*) a : (B*) b
8501 // where B is a subclass of A.
8502 //
8503 // Additionally, as for assignment, if either type is 'id'
8504 // allow silent coercion. Finally, if the types are
8505 // incompatible then make sure to use 'id' as the composite
8506 // type so the result is acceptable for sending messages to.
8507
8508 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8509 // It could return the composite type.
8510 if (!(compositeType =
8511 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8512 // Nothing more to do.
8513 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8514 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8515 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8516 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8517 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8518 RHSOPT->isObjCQualifiedIdType()) &&
8519 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8520 true)) {
8521 // Need to handle "id<xx>" explicitly.
8522 // GCC allows qualified id and any Objective-C type to devolve to
8523 // id. Currently localizing to here until clear this should be
8524 // part of ObjCQualifiedIdTypesAreCompatible.
8525 compositeType = Context.getObjCIdType();
8526 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8527 compositeType = Context.getObjCIdType();
8528 } else {
8529 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8530 << LHSTy << RHSTy
8531 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8532 QualType incompatTy = Context.getObjCIdType();
8533 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8534 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8535 return incompatTy;
8536 }
8537 // The object pointer types are compatible.
8538 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8539 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8540 return compositeType;
8541 }
8542 // Check Objective-C object pointer types and 'void *'
8543 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8544 if (getLangOpts().ObjCAutoRefCount) {
8545 // ARC forbids the implicit conversion of object pointers to 'void *',
8546 // so these types are not compatible.
8547 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8548 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8549 LHS = RHS = true;
8550 return QualType();
8551 }
8552 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8553 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8554 QualType destPointee
8555 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8556 QualType destType = Context.getPointerType(destPointee);
8557 // Add qualifiers if necessary.
8558 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8559 // Promote to void*.
8560 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8561 return destType;
8562 }
8563 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8564 if (getLangOpts().ObjCAutoRefCount) {
8565 // ARC forbids the implicit conversion of object pointers to 'void *',
8566 // so these types are not compatible.
8567 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8568 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8569 LHS = RHS = true;
8570 return QualType();
8571 }
8572 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8573 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8574 QualType destPointee
8575 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8576 QualType destType = Context.getPointerType(destPointee);
8577 // Add qualifiers if necessary.
8578 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8579 // Promote to void*.
8580 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8581 return destType;
8582 }
8583 return QualType();
8584}
8585
8586/// SuggestParentheses - Emit a note with a fixit hint that wraps
8587/// ParenRange in parentheses.
8588static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8589 const PartialDiagnostic &Note,
8590 SourceRange ParenRange) {
8591 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8592 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8593 EndLoc.isValid()) {
8594 Self.Diag(Loc, Note)
8595 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8596 << FixItHint::CreateInsertion(EndLoc, ")");
8597 } else {
8598 // We can't display the parentheses, so just show the bare note.
8599 Self.Diag(Loc, Note) << ParenRange;
8600 }
8601}
8602
8603static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8604 return BinaryOperator::isAdditiveOp(Opc) ||
8605 BinaryOperator::isMultiplicativeOp(Opc) ||
8606 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8607 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8608 // not any of the logical operators. Bitwise-xor is commonly used as a
8609 // logical-xor because there is no logical-xor operator. The logical
8610 // operators, including uses of xor, have a high false positive rate for
8611 // precedence warnings.
8612}
8613
8614/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8615/// expression, either using a built-in or overloaded operator,
8616/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8617/// expression.
8618static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8619 Expr **RHSExprs) {
8620 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8621 E = E->IgnoreImpCasts();
8622 E = E->IgnoreConversionOperatorSingleStep();
8623 E = E->IgnoreImpCasts();
8624 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8625 E = MTE->getSubExpr();
8626 E = E->IgnoreImpCasts();
8627 }
8628
8629 // Built-in binary operator.
8630 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8631 if (IsArithmeticOp(OP->getOpcode())) {
8632 *Opcode = OP->getOpcode();
8633 *RHSExprs = OP->getRHS();
8634 return true;
8635 }
8636 }
8637
8638 // Overloaded operator.
8639 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8640 if (Call->getNumArgs() != 2)
8641 return false;
8642
8643 // Make sure this is really a binary operator that is safe to pass into
8644 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8645 OverloadedOperatorKind OO = Call->getOperator();
8646 if (OO < OO_Plus || OO > OO_Arrow ||
8647 OO == OO_PlusPlus || OO == OO_MinusMinus)
8648 return false;
8649
8650 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8651 if (IsArithmeticOp(OpKind)) {
8652 *Opcode = OpKind;
8653 *RHSExprs = Call->getArg(1);
8654 return true;
8655 }
8656 }
8657
8658 return false;
8659}
8660
8661/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8662/// or is a logical expression such as (x==y) which has int type, but is
8663/// commonly interpreted as boolean.
8664static bool ExprLooksBoolean(Expr *E) {
8665 E = E->IgnoreParenImpCasts();
8666
8667 if (E->getType()->isBooleanType())
8668 return true;
8669 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8670 return OP->isComparisonOp() || OP->isLogicalOp();
8671 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8672 return OP->getOpcode() == UO_LNot;
8673 if (E->getType()->isPointerType())
8674 return true;
8675 // FIXME: What about overloaded operator calls returning "unspecified boolean
8676 // type"s (commonly pointer-to-members)?
8677
8678 return false;
8679}
8680
8681/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8682/// and binary operator are mixed in a way that suggests the programmer assumed
8683/// the conditional operator has higher precedence, for example:
8684/// "int x = a + someBinaryCondition ? 1 : 2".
8685static void DiagnoseConditionalPrecedence(Sema &Self,
8686 SourceLocation OpLoc,
8687 Expr *Condition,
8688 Expr *LHSExpr,
8689 Expr *RHSExpr) {
8690 BinaryOperatorKind CondOpcode;
8691 Expr *CondRHS;
8692
8693 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8694 return;
8695 if (!ExprLooksBoolean(CondRHS))
8696 return;
8697
8698 // The condition is an arithmetic binary expression, with a right-
8699 // hand side that looks boolean, so warn.
8700
8701 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8702 ? diag::warn_precedence_bitwise_conditional
8703 : diag::warn_precedence_conditional;
8704
8705 Self.Diag(OpLoc, DiagID)
8706 << Condition->getSourceRange()
8707 << BinaryOperator::getOpcodeStr(CondOpcode);
8708
8709 SuggestParentheses(
8710 Self, OpLoc,
8711 Self.PDiag(diag::note_precedence_silence)
8712 << BinaryOperator::getOpcodeStr(CondOpcode),
8713 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8714
8715 SuggestParentheses(Self, OpLoc,
8716 Self.PDiag(diag::note_precedence_conditional_first),
8717 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8718}
8719
8720/// Compute the nullability of a conditional expression.
8721static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8722 QualType LHSTy, QualType RHSTy,
8723 ASTContext &Ctx) {
8724 if (!ResTy->isAnyPointerType())
8725 return ResTy;
8726
8727 auto GetNullability = [&Ctx](QualType Ty) {
8728 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8729 if (Kind) {
8730 // For our purposes, treat _Nullable_result as _Nullable.
8731 if (*Kind == NullabilityKind::NullableResult)
8732 return NullabilityKind::Nullable;
8733 return *Kind;
8734 }
8735 return NullabilityKind::Unspecified;
8736 };
8737
8738 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8739 NullabilityKind MergedKind;
8740
8741 // Compute nullability of a binary conditional expression.
8742 if (IsBin) {
8743 if (LHSKind == NullabilityKind::NonNull)
8744 MergedKind = NullabilityKind::NonNull;
8745 else
8746 MergedKind = RHSKind;
8747 // Compute nullability of a normal conditional expression.
8748 } else {
8749 if (LHSKind == NullabilityKind::Nullable ||
8750 RHSKind == NullabilityKind::Nullable)
8751 MergedKind = NullabilityKind::Nullable;
8752 else if (LHSKind == NullabilityKind::NonNull)
8753 MergedKind = RHSKind;
8754 else if (RHSKind == NullabilityKind::NonNull)
8755 MergedKind = LHSKind;
8756 else
8757 MergedKind = NullabilityKind::Unspecified;
8758 }
8759
8760 // Return if ResTy already has the correct nullability.
8761 if (GetNullability(ResTy) == MergedKind)
8762 return ResTy;
8763
8764 // Strip all nullability from ResTy.
8765 while (ResTy->getNullability(Ctx))
8766 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8767
8768 // Create a new AttributedType with the new nullability kind.
8769 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8770 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8771}
8772
8773/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
8774/// in the case of a the GNU conditional expr extension.
8775ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8776 SourceLocation ColonLoc,
8777 Expr *CondExpr, Expr *LHSExpr,
8778 Expr *RHSExpr) {
8779 if (!Context.isDependenceAllowed()) {
8780 // C cannot handle TypoExpr nodes in the condition because it
8781 // doesn't handle dependent types properly, so make sure any TypoExprs have
8782 // been dealt with before checking the operands.
8783 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8784 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8785 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8786
8787 if (!CondResult.isUsable())
8788 return ExprError();
8789
8790 if (LHSExpr) {
8791 if (!LHSResult.isUsable())
8792 return ExprError();
8793 }
8794
8795 if (!RHSResult.isUsable())
8796 return ExprError();
8797
8798 CondExpr = CondResult.get();
8799 LHSExpr = LHSResult.get();
8800 RHSExpr = RHSResult.get();
8801 }
8802
8803 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8804 // was the condition.
8805 OpaqueValueExpr *opaqueValue = nullptr;
8806 Expr *commonExpr = nullptr;
8807 if (!LHSExpr) {
8808 commonExpr = CondExpr;
8809 // Lower out placeholder types first. This is important so that we don't
8810 // try to capture a placeholder. This happens in few cases in C++; such
8811 // as Objective-C++'s dictionary subscripting syntax.
8812 if (commonExpr->hasPlaceholderType()) {
8813 ExprResult result = CheckPlaceholderExpr(commonExpr);
8814 if (!result.isUsable()) return ExprError();
8815 commonExpr = result.get();
8816 }
8817 // We usually want to apply unary conversions *before* saving, except
8818 // in the special case of a C++ l-value conditional.
8819 if (!(getLangOpts().CPlusPlus
8820 && !commonExpr->isTypeDependent()
8821 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8822 && commonExpr->isGLValue()
8823 && commonExpr->isOrdinaryOrBitFieldObject()
8824 && RHSExpr->isOrdinaryOrBitFieldObject()
8825 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8826 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8827 if (commonRes.isInvalid())
8828 return ExprError();
8829 commonExpr = commonRes.get();
8830 }
8831
8832 // If the common expression is a class or array prvalue, materialize it
8833 // so that we can safely refer to it multiple times.
8834 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8835 commonExpr->getType()->isArrayType())) {
8836 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8837 if (MatExpr.isInvalid())
8838 return ExprError();
8839 commonExpr = MatExpr.get();
8840 }
8841
8842 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8843 commonExpr->getType(),
8844 commonExpr->getValueKind(),
8845 commonExpr->getObjectKind(),
8846 commonExpr);
8847 LHSExpr = CondExpr = opaqueValue;
8848 }
8849
8850 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8851 ExprValueKind VK = VK_PRValue;
8852 ExprObjectKind OK = OK_Ordinary;
8853 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8854 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8855 VK, OK, QuestionLoc);
8856 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8857 RHS.isInvalid())
8858 return ExprError();
8859
8860 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8861 RHS.get());
8862
8863 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8864
8865 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8866 Context);
8867
8868 if (!commonExpr)
8869 return new (Context)
8870 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8871 RHS.get(), result, VK, OK);
8872
8873 return new (Context) BinaryConditionalOperator(
8874 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8875 ColonLoc, result, VK, OK);
8876}
8877
8878// Check if we have a conversion between incompatible cmse function pointer
8879// types, that is, a conversion between a function pointer with the
8880// cmse_nonsecure_call attribute and one without.
8881static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8882 QualType ToType) {
8883 if (const auto *ToFn =
8884 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8885 if (const auto *FromFn =
8886 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8887 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8888 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8889
8890 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8891 }
8892 }
8893 return false;
8894}
8895
8896// checkPointerTypesForAssignment - This is a very tricky routine (despite
8897// being closely modeled after the C99 spec:-). The odd characteristic of this
8898// routine is it effectively iqnores the qualifiers on the top level pointee.
8899// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8900// FIXME: add a couple examples in this comment.
8901static Sema::AssignConvertType
8902checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8903 assert(LHSType.isCanonical() && "LHS not canonicalized!")((void)0);
8904 assert(RHSType.isCanonical() && "RHS not canonicalized!")((void)0);
8905
8906 // get the "pointed to" type (ignoring qualifiers at the top level)
8907 const Type *lhptee, *rhptee;
8908 Qualifiers lhq, rhq;
8909 std::tie(lhptee, lhq) =
8910 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8911 std::tie(rhptee, rhq) =
8912 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8913
8914 Sema::AssignConvertType ConvTy = Sema::Compatible;
8915
8916 // C99 6.5.16.1p1: This following citation is common to constraints
8917 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8918 // qualifiers of the type *pointed to* by the right;
8919
8920 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8921 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8922 lhq.compatiblyIncludesObjCLifetime(rhq)) {
8923 // Ignore lifetime for further calculation.
8924 lhq.removeObjCLifetime();
8925 rhq.removeObjCLifetime();
8926 }
8927
8928 if (!lhq.compatiblyIncludes(rhq)) {
8929 // Treat address-space mismatches as fatal.
8930 if (!lhq.isAddressSpaceSupersetOf(rhq))
8931 return Sema::IncompatiblePointerDiscardsQualifiers;
8932
8933 // It's okay to add or remove GC or lifetime qualifiers when converting to
8934 // and from void*.
8935 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8936 .compatiblyIncludes(
8937 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8938 && (lhptee->isVoidType() || rhptee->isVoidType()))
8939 ; // keep old
8940
8941 // Treat lifetime mismatches as fatal.
8942 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8943 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8944
8945 // For GCC/MS compatibility, other qualifier mismatches are treated
8946 // as still compatible in C.
8947 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8948 }
8949
8950 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8951 // incomplete type and the other is a pointer to a qualified or unqualified
8952 // version of void...
8953 if (lhptee->isVoidType()) {
8954 if (rhptee->isIncompleteOrObjectType())
8955 return ConvTy;
8956
8957 // As an extension, we allow cast to/from void* to function pointer.
8958 assert(rhptee->isFunctionType())((void)0);
8959 return Sema::FunctionVoidPointer;
8960 }
8961
8962 if (rhptee->isVoidType()) {
8963 if (lhptee->isIncompleteOrObjectType())
8964 return ConvTy;
8965
8966 // As an extension, we allow cast to/from void* to function pointer.
8967 assert(lhptee->isFunctionType())((void)0);
8968 return Sema::FunctionVoidPointer;
8969 }
8970
8971 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8972 // unqualified versions of compatible types, ...
8973 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8974 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8975 // Check if the pointee types are compatible ignoring the sign.
8976 // We explicitly check for char so that we catch "char" vs
8977 // "unsigned char" on systems where "char" is unsigned.
8978 if (lhptee->isCharType())
8979 ltrans = S.Context.UnsignedCharTy;
8980 else if (lhptee->hasSignedIntegerRepresentation())
8981 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8982
8983 if (rhptee->isCharType())
8984 rtrans = S.Context.UnsignedCharTy;
8985 else if (rhptee->hasSignedIntegerRepresentation())
8986 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8987
8988 if (ltrans == rtrans) {
8989 // Types are compatible ignoring the sign. Qualifier incompatibility
8990 // takes priority over sign incompatibility because the sign
8991 // warning can be disabled.
8992 if (ConvTy != Sema::Compatible)
8993 return ConvTy;
8994
8995 return Sema::IncompatiblePointerSign;
8996 }
8997
8998 // If we are a multi-level pointer, it's possible that our issue is simply
8999 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9000 // the eventual target type is the same and the pointers have the same
9001 // level of indirection, this must be the issue.
9002 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9003 do {
9004 std::tie(lhptee, lhq) =
9005 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9006 std::tie(rhptee, rhq) =
9007 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9008
9009 // Inconsistent address spaces at this point is invalid, even if the
9010 // address spaces would be compatible.
9011 // FIXME: This doesn't catch address space mismatches for pointers of
9012 // different nesting levels, like:
9013 // __local int *** a;
9014 // int ** b = a;
9015 // It's not clear how to actually determine when such pointers are
9016 // invalidly incompatible.
9017 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9018 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9019
9020 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9021
9022 if (lhptee == rhptee)
9023 return Sema::IncompatibleNestedPointerQualifiers;
9024 }
9025
9026 // General pointer incompatibility takes priority over qualifiers.
9027 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9028 return Sema::IncompatibleFunctionPointer;
9029 return Sema::IncompatiblePointer;
9030 }
9031 if (!S.getLangOpts().CPlusPlus &&
9032 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9033 return Sema::IncompatibleFunctionPointer;
9034 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9035 return Sema::IncompatibleFunctionPointer;
9036 return ConvTy;
9037}
9038
9039/// checkBlockPointerTypesForAssignment - This routine determines whether two
9040/// block pointer types are compatible or whether a block and normal pointer
9041/// are compatible. It is more restrict than comparing two function pointer
9042// types.
9043static Sema::AssignConvertType
9044checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9045 QualType RHSType) {
9046 assert(LHSType.isCanonical() && "LHS not canonicalized!")((void)0);
9047 assert(RHSType.isCanonical() && "RHS not canonicalized!")((void)0);
9048
9049 QualType lhptee, rhptee;
9050
9051 // get the "pointed to" type (ignoring qualifiers at the top level)
9052 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9053 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9054
9055 // In C++, the types have to match exactly.
9056 if (S.getLangOpts().CPlusPlus)
9057 return Sema::IncompatibleBlockPointer;
9058
9059 Sema::AssignConvertType ConvTy = Sema::Compatible;
9060
9061 // For blocks we enforce that qualifiers are identical.
9062 Qualifiers LQuals = lhptee.getLocalQualifiers();
9063 Qualifiers RQuals = rhptee.getLocalQualifiers();
9064 if (S.getLangOpts().OpenCL) {
9065 LQuals.removeAddressSpace();
9066 RQuals.removeAddressSpace();
9067 }
9068 if (LQuals != RQuals)
9069 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9070
9071 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9072 // assignment.
9073 // The current behavior is similar to C++ lambdas. A block might be
9074 // assigned to a variable iff its return type and parameters are compatible
9075 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9076 // an assignment. Presumably it should behave in way that a function pointer
9077 // assignment does in C, so for each parameter and return type:
9078 // * CVR and address space of LHS should be a superset of CVR and address
9079 // space of RHS.
9080 // * unqualified types should be compatible.
9081 if (S.getLangOpts().OpenCL) {
9082 if (!S.Context.typesAreBlockPointerCompatible(
9083 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9084 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9085 return Sema::IncompatibleBlockPointer;
9086 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9087 return Sema::IncompatibleBlockPointer;
9088
9089 return ConvTy;
9090}
9091
9092/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9093/// for assignment compatibility.
9094static Sema::AssignConvertType
9095checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9096 QualType RHSType) {
9097 assert(LHSType.isCanonical() && "LHS was not canonicalized!")((void)0);
9098 assert(RHSType.isCanonical() && "RHS was not canonicalized!")((void)0);
9099
9100 if (LHSType->isObjCBuiltinType()) {
9101 // Class is not compatible with ObjC object pointers.
9102 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9103 !RHSType->isObjCQualifiedClassType())
9104 return Sema::IncompatiblePointer;
9105 return Sema::Compatible;
9106 }
9107 if (RHSType->isObjCBuiltinType()) {
9108 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9109 !LHSType->isObjCQualifiedClassType())
9110 return Sema::IncompatiblePointer;
9111 return Sema::Compatible;
9112 }
9113 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9114 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9115
9116 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9117 // make an exception for id<P>
9118 !LHSType->isObjCQualifiedIdType())
9119 return Sema::CompatiblePointerDiscardsQualifiers;
9120
9121 if (S.Context.typesAreCompatible(LHSType, RHSType))
9122 return Sema::Compatible;
9123 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9124 return Sema::IncompatibleObjCQualifiedId;
9125 return Sema::IncompatiblePointer;
9126}
9127
9128Sema::AssignConvertType
9129Sema::CheckAssignmentConstraints(SourceLocation Loc,
9130 QualType LHSType, QualType RHSType) {
9131 // Fake up an opaque expression. We don't actually care about what
9132 // cast operations are required, so if CheckAssignmentConstraints
9133 // adds casts to this they'll be wasted, but fortunately that doesn't
9134 // usually happen on valid code.
9135 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9136 ExprResult RHSPtr = &RHSExpr;
9137 CastKind K;
9138
9139 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9140}
9141
9142/// This helper function returns true if QT is a vector type that has element
9143/// type ElementType.
9144static bool isVector(QualType QT, QualType ElementType) {
9145 if (const VectorType *VT = QT->getAs<VectorType>())
9146 return VT->getElementType().getCanonicalType() == ElementType;
9147 return false;
9148}
9149
9150/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9151/// has code to accommodate several GCC extensions when type checking
9152/// pointers. Here are some objectionable examples that GCC considers warnings:
9153///
9154/// int a, *pint;
9155/// short *pshort;
9156/// struct foo *pfoo;
9157///
9158/// pint = pshort; // warning: assignment from incompatible pointer type
9159/// a = pint; // warning: assignment makes integer from pointer without a cast
9160/// pint = a; // warning: assignment makes pointer from integer without a cast
9161/// pint = pfoo; // warning: assignment from incompatible pointer type
9162///
9163/// As a result, the code for dealing with pointers is more complex than the
9164/// C99 spec dictates.
9165///
9166/// Sets 'Kind' for any result kind except Incompatible.
9167Sema::AssignConvertType
9168Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9169 CastKind &Kind, bool ConvertRHS) {
9170 QualType RHSType = RHS.get()->getType();
9171 QualType OrigLHSType = LHSType;
9172
9173 // Get canonical types. We're not formatting these types, just comparing
9174 // them.
9175 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9176 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9177
9178 // Common case: no conversion required.
9179 if (LHSType == RHSType) {
9180 Kind = CK_NoOp;
9181 return Compatible;
9182 }
9183
9184 // If we have an atomic type, try a non-atomic assignment, then just add an
9185 // atomic qualification step.
9186 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9187 Sema::AssignConvertType result =
9188 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9189 if (result != Compatible)
9190 return result;
9191 if (Kind != CK_NoOp && ConvertRHS)
9192 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9193 Kind = CK_NonAtomicToAtomic;
9194 return Compatible;
9195 }
9196
9197 // If the left-hand side is a reference type, then we are in a
9198 // (rare!) case where we've allowed the use of references in C,
9199 // e.g., as a parameter type in a built-in function. In this case,
9200 // just make sure that the type referenced is compatible with the
9201 // right-hand side type. The caller is responsible for adjusting
9202 // LHSType so that the resulting expression does not have reference
9203 // type.
9204 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9205 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9206 Kind = CK_LValueBitCast;
9207 return Compatible;
9208 }
9209 return Incompatible;
9210 }
9211
9212 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9213 // to the same ExtVector type.
9214 if (LHSType->isExtVectorType()) {
9215 if (RHSType->isExtVectorType())
9216 return Incompatible;
9217 if (RHSType->isArithmeticType()) {
9218 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9219 if (ConvertRHS)
9220 RHS = prepareVectorSplat(LHSType, RHS.get());
9221 Kind = CK_VectorSplat;
9222 return Compatible;
9223 }
9224 }
9225
9226 // Conversions to or from vector type.
9227 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9228 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9229 // Allow assignments of an AltiVec vector type to an equivalent GCC
9230 // vector type and vice versa
9231 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9232 Kind = CK_BitCast;
9233 return Compatible;
9234 }
9235
9236 // If we are allowing lax vector conversions, and LHS and RHS are both
9237 // vectors, the total size only needs to be the same. This is a bitcast;
9238 // no bits are changed but the result type is different.
9239 if (isLaxVectorConversion(RHSType, LHSType)) {
9240 Kind = CK_BitCast;
9241 return IncompatibleVectors;
9242 }
9243 }
9244
9245 // When the RHS comes from another lax conversion (e.g. binops between
9246 // scalars and vectors) the result is canonicalized as a vector. When the
9247 // LHS is also a vector, the lax is allowed by the condition above. Handle
9248 // the case where LHS is a scalar.
9249 if (LHSType->isScalarType()) {
9250 const VectorType *VecType = RHSType->getAs<VectorType>();
9251 if (VecType && VecType->getNumElements() == 1 &&
9252 isLaxVectorConversion(RHSType, LHSType)) {
9253 ExprResult *VecExpr = &RHS;
9254 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9255 Kind = CK_BitCast;
9256 return Compatible;
9257 }
9258 }
9259
9260 // Allow assignments between fixed-length and sizeless SVE vectors.
9261 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9262 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9263 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9264 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9265 Kind = CK_BitCast;
9266 return Compatible;
9267 }
9268
9269 return Incompatible;
9270 }
9271
9272 // Diagnose attempts to convert between __float128 and long double where
9273 // such conversions currently can't be handled.
9274 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9275 return Incompatible;
9276
9277 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9278 // discards the imaginary part.
9279 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9280 !LHSType->getAs<ComplexType>())
9281 return Incompatible;
9282
9283 // Arithmetic conversions.
9284 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9285 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9286 if (ConvertRHS)
9287 Kind = PrepareScalarCast(RHS, LHSType);
9288 return Compatible;
9289 }
9290
9291 // Conversions to normal pointers.
9292 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9293 // U* -> T*
9294 if (isa<PointerType>(RHSType)) {
9295 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9296 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9297 if (AddrSpaceL != AddrSpaceR)
9298 Kind = CK_AddressSpaceConversion;
9299 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9300 Kind = CK_NoOp;
9301 else
9302 Kind = CK_BitCast;
9303 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9304 }
9305
9306 // int -> T*
9307 if (RHSType->isIntegerType()) {
9308 Kind = CK_IntegralToPointer; // FIXME: null?
9309 return IntToPointer;
9310 }
9311
9312 // C pointers are not compatible with ObjC object pointers,
9313 // with two exceptions:
9314 if (isa<ObjCObjectPointerType>(RHSType)) {
9315 // - conversions to void*
9316 if (LHSPointer->getPointeeType()->isVoidType()) {
9317 Kind = CK_BitCast;
9318 return Compatible;
9319 }
9320
9321 // - conversions from 'Class' to the redefinition type
9322 if (RHSType->isObjCClassType() &&
9323 Context.hasSameType(LHSType,
9324 Context.getObjCClassRedefinitionType())) {
9325 Kind = CK_BitCast;
9326 return Compatible;
9327 }
9328
9329 Kind = CK_BitCast;
9330 return IncompatiblePointer;
9331 }
9332
9333 // U^ -> void*
9334 if (RHSType->getAs<BlockPointerType>()) {
9335 if (LHSPointer->getPointeeType()->isVoidType()) {
9336 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9337 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9338 ->getPointeeType()
9339 .getAddressSpace();
9340 Kind =
9341 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9342 return Compatible;
9343 }
9344 }
9345
9346 return Incompatible;
9347 }
9348
9349 // Conversions to block pointers.
9350 if (isa<BlockPointerType>(LHSType)) {
9351 // U^ -> T^
9352 if (RHSType->isBlockPointerType()) {
9353 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9354 ->getPointeeType()
9355 .getAddressSpace();
9356 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9357 ->getPointeeType()
9358 .getAddressSpace();
9359 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9360 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9361 }
9362
9363 // int or null -> T^
9364 if (RHSType->isIntegerType()) {
9365 Kind = CK_IntegralToPointer; // FIXME: null
9366 return IntToBlockPointer;
9367 }
9368
9369 // id -> T^
9370 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9371 Kind = CK_AnyPointerToBlockPointerCast;
9372 return Compatible;
9373 }
9374
9375 // void* -> T^
9376 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9377 if (RHSPT->getPointeeType()->isVoidType()) {
9378 Kind = CK_AnyPointerToBlockPointerCast;
9379 return Compatible;
9380 }
9381
9382 return Incompatible;
9383 }
9384
9385 // Conversions to Objective-C pointers.
9386 if (isa<ObjCObjectPointerType>(LHSType)) {
9387 // A* -> B*
9388 if (RHSType->isObjCObjectPointerType()) {
9389 Kind = CK_BitCast;
9390 Sema::AssignConvertType result =
9391 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9392 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9393 result == Compatible &&
9394 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9395 result = IncompatibleObjCWeakRef;
9396 return result;
9397 }
9398
9399 // int or null -> A*
9400 if (RHSType->isIntegerType()) {
9401 Kind = CK_IntegralToPointer; // FIXME: null
9402 return IntToPointer;
9403 }
9404
9405 // In general, C pointers are not compatible with ObjC object pointers,
9406 // with two exceptions:
9407 if (isa<PointerType>(RHSType)) {
9408 Kind = CK_CPointerToObjCPointerCast;
9409
9410 // - conversions from 'void*'
9411 if (RHSType->isVoidPointerType()) {
9412 return Compatible;
9413 }
9414
9415 // - conversions to 'Class' from its redefinition type
9416 if (LHSType->isObjCClassType() &&
9417 Context.hasSameType(RHSType,
9418 Context.getObjCClassRedefinitionType())) {
9419 return Compatible;
9420 }
9421
9422 return IncompatiblePointer;
9423 }
9424
9425 // Only under strict condition T^ is compatible with an Objective-C pointer.
9426 if (RHSType->isBlockPointerType() &&
9427 LHSType->isBlockCompatibleObjCPointerType(Context)) {
9428 if (ConvertRHS)
9429 maybeExtendBlockObject(RHS);
9430 Kind = CK_BlockPointerToObjCPointerCast;
9431 return Compatible;
9432 }
9433
9434 return Incompatible;
9435 }
9436
9437 // Conversions from pointers that are not covered by the above.
9438 if (isa<PointerType>(RHSType)) {
9439 // T* -> _Bool
9440 if (LHSType == Context.BoolTy) {
9441 Kind = CK_PointerToBoolean;
9442 return Compatible;
9443 }
9444
9445 // T* -> int
9446 if (LHSType->isIntegerType()) {
9447 Kind = CK_PointerToIntegral;
9448 return PointerToInt;
9449 }
9450
9451 return Incompatible;
9452 }
9453
9454 // Conversions from Objective-C pointers that are not covered by the above.
9455 if (isa<ObjCObjectPointerType>(RHSType)) {
9456 // T* -> _Bool
9457 if (LHSType == Context.BoolTy) {
9458 Kind = CK_PointerToBoolean;
9459 return Compatible;
9460 }
9461
9462 // T* -> int
9463 if (LHSType->isIntegerType()) {
9464 Kind = CK_PointerToIntegral;
9465 return PointerToInt;
9466 }
9467
9468 return Incompatible;
9469 }
9470
9471 // struct A -> struct B
9472 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9473 if (Context.typesAreCompatible(LHSType, RHSType)) {
9474 Kind = CK_NoOp;
9475 return Compatible;
9476 }
9477 }
9478
9479 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9480 Kind = CK_IntToOCLSampler;
9481 return Compatible;
9482 }
9483
9484 return Incompatible;
9485}
9486
9487/// Constructs a transparent union from an expression that is
9488/// used to initialize the transparent union.
9489static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9490 ExprResult &EResult, QualType UnionType,
9491 FieldDecl *Field) {
9492 // Build an initializer list that designates the appropriate member
9493 // of the transparent union.
9494 Expr *E = EResult.get();
9495 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9496 E, SourceLocation());
9497 Initializer->setType(UnionType);
9498 Initializer->setInitializedFieldInUnion(Field);
9499
9500 // Build a compound literal constructing a value of the transparent
9501 // union type from this initializer list.
9502 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9503 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9504 VK_PRValue, Initializer, false);
9505}
9506
9507Sema::AssignConvertType
9508Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9509 ExprResult &RHS) {
9510 QualType RHSType = RHS.get()->getType();
9511
9512 // If the ArgType is a Union type, we want to handle a potential
9513 // transparent_union GCC extension.
9514 const RecordType *UT = ArgType->getAsUnionType();
9515 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9516 return Incompatible;
9517
9518 // The field to initialize within the transparent union.
9519 RecordDecl *UD = UT->getDecl();
9520 FieldDecl *InitField = nullptr;
9521 // It's compatible if the expression matches any of the fields.
9522 for (auto *it : UD->fields()) {
9523 if (it->getType()->isPointerType()) {
9524 // If the transparent union contains a pointer type, we allow:
9525 // 1) void pointer
9526 // 2) null pointer constant
9527 if (RHSType->isPointerType())
9528 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9529 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9530 InitField = it;
9531 break;
9532 }
9533
9534 if (RHS.get()->isNullPointerConstant(Context,
9535 Expr::NPC_ValueDependentIsNull)) {
9536 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9537 CK_NullToPointer);
9538 InitField = it;
9539 break;
9540 }
9541 }
9542
9543 CastKind Kind;
9544 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9545 == Compatible) {
9546 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9547 InitField = it;
9548 break;
9549 }
9550 }
9551
9552 if (!InitField)
9553 return Incompatible;
9554
9555 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9556 return Compatible;
9557}
9558
9559Sema::AssignConvertType
9560Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9561 bool Diagnose,
9562 bool DiagnoseCFAudited,
9563 bool ConvertRHS) {
9564 // We need to be able to tell the caller whether we diagnosed a problem, if
9565 // they ask us to issue diagnostics.
9566 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")((void)0);
9567
9568 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9569 // we can't avoid *all* modifications at the moment, so we need some somewhere
9570 // to put the updated value.
9571 ExprResult LocalRHS = CallerRHS;
9572 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9573
9574 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9575 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9576 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9577 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9578 Diag(RHS.get()->getExprLoc(),
9579 diag::warn_noderef_to_dereferenceable_pointer)
9580 << RHS.get()->getSourceRange();
9581 }
9582 }
9583 }
9584
9585 if (getLangOpts().CPlusPlus) {
9586 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9587 // C++ 5.17p3: If the left operand is not of class type, the
9588 // expression is implicitly converted (C++ 4) to the
9589 // cv-unqualified type of the left operand.
9590 QualType RHSType = RHS.get()->getType();
9591 if (Diagnose) {
9592 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9593 AA_Assigning);
9594 } else {
9595 ImplicitConversionSequence ICS =
9596 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9597 /*SuppressUserConversions=*/false,
9598 AllowedExplicit::None,
9599 /*InOverloadResolution=*/false,
9600 /*CStyle=*/false,
9601 /*AllowObjCWritebackConversion=*/false);
9602 if (ICS.isFailure())
9603 return Incompatible;
9604 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9605 ICS, AA_Assigning);
9606 }
9607 if (RHS.isInvalid())
9608 return Incompatible;
9609 Sema::AssignConvertType result = Compatible;
9610 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9611 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9612 result = IncompatibleObjCWeakRef;
9613 return result;
9614 }
9615
9616 // FIXME: Currently, we fall through and treat C++ classes like C
9617 // structures.
9618 // FIXME: We also fall through for atomics; not sure what should
9619 // happen there, though.
9620 } else if (RHS.get()->getType() == Context.OverloadTy) {
9621 // As a set of extensions to C, we support overloading on functions. These
9622 // functions need to be resolved here.
9623 DeclAccessPair DAP;
9624 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9625 RHS.get(), LHSType, /*Complain=*/false, DAP))
9626 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9627 else
9628 return Incompatible;
9629 }
9630
9631 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9632 // a null pointer constant.
9633 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9634 LHSType->isBlockPointerType()) &&
9635 RHS.get()->isNullPointerConstant(Context,
9636 Expr::NPC_ValueDependentIsNull)) {
9637 if (Diagnose || ConvertRHS) {
9638 CastKind Kind;
9639 CXXCastPath Path;
9640 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9641 /*IgnoreBaseAccess=*/false, Diagnose);
9642 if (ConvertRHS)
9643 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9644 }
9645 return Compatible;
9646 }
9647
9648 // OpenCL queue_t type assignment.
9649 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9650 Context, Expr::NPC_ValueDependentIsNull)) {
9651 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9652 return Compatible;
9653 }
9654
9655 // This check seems unnatural, however it is necessary to ensure the proper
9656 // conversion of functions/arrays. If the conversion were done for all
9657 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9658 // expressions that suppress this implicit conversion (&, sizeof).
9659 //
9660 // Suppress this for references: C++ 8.5.3p5.
9661 if (!LHSType->isReferenceType()) {
9662 // FIXME: We potentially allocate here even if ConvertRHS is false.
9663 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9664 if (RHS.isInvalid())
9665 return Incompatible;
9666 }
9667 CastKind Kind;
9668 Sema::AssignConvertType result =
9669 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9670
9671 // C99 6.5.16.1p2: The value of the right operand is converted to the
9672 // type of the assignment expression.
9673 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9674 // so that we can use references in built-in functions even in C.
9675 // The getNonReferenceType() call makes sure that the resulting expression
9676 // does not have reference type.
9677 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9678 QualType Ty = LHSType.getNonLValueExprType(Context);
9679 Expr *E = RHS.get();
9680
9681 // Check for various Objective-C errors. If we are not reporting
9682 // diagnostics and just checking for errors, e.g., during overload
9683 // resolution, return Incompatible to indicate the failure.
9684 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9685 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9686 Diagnose, DiagnoseCFAudited) != ACR_okay) {
9687 if (!Diagnose)
9688 return Incompatible;
9689 }
9690 if (getLangOpts().ObjC &&
9691 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9692 E->getType(), E, Diagnose) ||
9693 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9694 if (!Diagnose)
9695 return Incompatible;
9696 // Replace the expression with a corrected version and continue so we
9697 // can find further errors.
9698 RHS = E;
9699 return Compatible;
9700 }
9701
9702 if (ConvertRHS)
9703 RHS = ImpCastExprToType(E, Ty, Kind);
9704 }
9705
9706 return result;
9707}
9708
9709namespace {
9710/// The original operand to an operator, prior to the application of the usual
9711/// arithmetic conversions and converting the arguments of a builtin operator
9712/// candidate.
9713struct OriginalOperand {
9714 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9715 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9716 Op = MTE->getSubExpr();
9717 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9718 Op = BTE->getSubExpr();
9719 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9720 Orig = ICE->getSubExprAsWritten();
9721 Conversion = ICE->getConversionFunction();
9722 }
9723 }
9724
9725 QualType getType() const { return Orig->getType(); }
9726
9727 Expr *Orig;
9728 NamedDecl *Conversion;
9729};
9730}
9731
9732QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9733 ExprResult &RHS) {
9734 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9735
9736 Diag(Loc, diag::err_typecheck_invalid_operands)
9737 << OrigLHS.getType() << OrigRHS.getType()
9738 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9739
9740 // If a user-defined conversion was applied to either of the operands prior
9741 // to applying the built-in operator rules, tell the user about it.
9742 if (OrigLHS.Conversion) {
9743 Diag(OrigLHS.Conversion->getLocation(),
9744 diag::note_typecheck_invalid_operands_converted)
9745 << 0 << LHS.get()->getType();
9746 }
9747 if (OrigRHS.Conversion) {
9748 Diag(OrigRHS.Conversion->getLocation(),
9749 diag::note_typecheck_invalid_operands_converted)
9750 << 1 << RHS.get()->getType();
9751 }
9752
9753 return QualType();
9754}
9755
9756// Diagnose cases where a scalar was implicitly converted to a vector and
9757// diagnose the underlying types. Otherwise, diagnose the error
9758// as invalid vector logical operands for non-C++ cases.
9759QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9760 ExprResult &RHS) {
9761 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9762 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9763
9764 bool LHSNatVec = LHSType->isVectorType();
9765 bool RHSNatVec = RHSType->isVectorType();
9766
9767 if (!(LHSNatVec && RHSNatVec)) {
9768 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9769 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9770 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9771 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9772 << Vector->getSourceRange();
9773 return QualType();
9774 }
9775
9776 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9777 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9778 << RHS.get()->getSourceRange();
9779
9780 return QualType();
9781}
9782
9783/// Try to convert a value of non-vector type to a vector type by converting
9784/// the type to the element type of the vector and then performing a splat.
9785/// If the language is OpenCL, we only use conversions that promote scalar
9786/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9787/// for float->int.
9788///
9789/// OpenCL V2.0 6.2.6.p2:
9790/// An error shall occur if any scalar operand type has greater rank
9791/// than the type of the vector element.
9792///
9793/// \param scalar - if non-null, actually perform the conversions
9794/// \return true if the operation fails (but without diagnosing the failure)
9795static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9796 QualType scalarTy,
9797 QualType vectorEltTy,
9798 QualType vectorTy,
9799 unsigned &DiagID) {
9800 // The conversion to apply to the scalar before splatting it,
9801 // if necessary.
9802 CastKind scalarCast = CK_NoOp;
9803
9804 if (vectorEltTy->isIntegralType(S.Context)) {
9805 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9806 (scalarTy->isIntegerType() &&
9807 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9808 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9809 return true;
9810 }
9811 if (!scalarTy->isIntegralType(S.Context))
9812 return true;
9813 scalarCast = CK_IntegralCast;
9814 } else if (vectorEltTy->isRealFloatingType()) {
9815 if (scalarTy->isRealFloatingType()) {
9816 if (S.getLangOpts().OpenCL &&
9817 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9818 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9819 return true;
9820 }
9821 scalarCast = CK_FloatingCast;
9822 }
9823 else if (scalarTy->isIntegralType(S.Context))
9824 scalarCast = CK_IntegralToFloating;
9825 else
9826 return true;
9827 } else {
9828 return true;
9829 }
9830
9831 // Adjust scalar if desired.
9832 if (scalar) {
9833 if (scalarCast != CK_NoOp)
9834 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9835 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9836 }
9837 return false;
9838}
9839
9840/// Convert vector E to a vector with the same number of elements but different
9841/// element type.
9842static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9843 const auto *VecTy = E->getType()->getAs<VectorType>();
9844 assert(VecTy && "Expression E must be a vector")((void)0);
9845 QualType NewVecTy = S.Context.getVectorType(ElementType,
9846 VecTy->getNumElements(),
9847 VecTy->getVectorKind());
9848
9849 // Look through the implicit cast. Return the subexpression if its type is
9850 // NewVecTy.
9851 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9852 if (ICE->getSubExpr()->getType() == NewVecTy)
9853 return ICE->getSubExpr();
9854
9855 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9856 return S.ImpCastExprToType(E, NewVecTy, Cast);
9857}
9858
9859/// Test if a (constant) integer Int can be casted to another integer type
9860/// IntTy without losing precision.
9861static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9862 QualType OtherIntTy) {
9863 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9864
9865 // Reject cases where the value of the Int is unknown as that would
9866 // possibly cause truncation, but accept cases where the scalar can be
9867 // demoted without loss of precision.
9868 Expr::EvalResult EVResult;
9869 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9870 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9871 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9872 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9873
9874 if (CstInt) {
9875 // If the scalar is constant and is of a higher order and has more active
9876 // bits that the vector element type, reject it.
9877 llvm::APSInt Result = EVResult.Val.getInt();
9878 unsigned NumBits = IntSigned
9879 ? (Result.isNegative() ? Result.getMinSignedBits()
9880 : Result.getActiveBits())
9881 : Result.getActiveBits();
9882 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9883 return true;
9884
9885 // If the signedness of the scalar type and the vector element type
9886 // differs and the number of bits is greater than that of the vector
9887 // element reject it.
9888 return (IntSigned != OtherIntSigned &&
9889 NumBits > S.Context.getIntWidth(OtherIntTy));
9890 }
9891
9892 // Reject cases where the value of the scalar is not constant and it's
9893 // order is greater than that of the vector element type.
9894 return (Order < 0);
9895}
9896
9897/// Test if a (constant) integer Int can be casted to floating point type
9898/// FloatTy without losing precision.
9899static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9900 QualType FloatTy) {
9901 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9902
9903 // Determine if the integer constant can be expressed as a floating point
9904 // number of the appropriate type.
9905 Expr::EvalResult EVResult;
9906 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9907
9908 uint64_t Bits = 0;
9909 if (CstInt) {
9910 // Reject constants that would be truncated if they were converted to
9911 // the floating point type. Test by simple to/from conversion.
9912 // FIXME: Ideally the conversion to an APFloat and from an APFloat
9913 // could be avoided if there was a convertFromAPInt method
9914 // which could signal back if implicit truncation occurred.
9915 llvm::APSInt Result = EVResult.Val.getInt();
9916 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9917 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9918 llvm::APFloat::rmTowardZero);
9919 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9920 !IntTy->hasSignedIntegerRepresentation());
9921 bool Ignored = false;
9922 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9923 &Ignored);
9924 if (Result != ConvertBack)
9925 return true;
9926 } else {
9927 // Reject types that cannot be fully encoded into the mantissa of
9928 // the float.
9929 Bits = S.Context.getTypeSize(IntTy);
9930 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9931 S.Context.getFloatTypeSemantics(FloatTy));
9932 if (Bits > FloatPrec)
9933 return true;
9934 }
9935
9936 return false;
9937}
9938
9939/// Attempt to convert and splat Scalar into a vector whose types matches
9940/// Vector following GCC conversion rules. The rule is that implicit
9941/// conversion can occur when Scalar can be casted to match Vector's element
9942/// type without causing truncation of Scalar.
9943static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9944 ExprResult *Vector) {
9945 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9946 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9947 const VectorType *VT = VectorTy->getAs<VectorType>();
48
Assuming the object is a 'VectorType'
72
Assuming the object is a 'VectorType'
9948
9949 assert(!isa<ExtVectorType>(VT) &&((void)0)
9950 "ExtVectorTypes should not be handled here!")((void)0);
9951
9952 QualType VectorEltTy = VT->getElementType();
9953
9954 // Reject cases where the vector element type or the scalar element type are
9955 // not integral or floating point types.
9956 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
49
Assuming the condition is false
50
Assuming the condition is false
51
Taking false branch
73
Assuming the condition is false
74
Assuming the condition is false
75
Taking false branch
9957 return true;
9958
9959 // The conversion to apply to the scalar before splatting it,
9960 // if necessary.
9961 CastKind ScalarCast = CK_NoOp;
9962
9963 // Accept cases where the vector elements are integers and the scalar is
9964 // an integer.
9965 // FIXME: Notionally if the scalar was a floating point value with a precise
9966 // integral representation, we could cast it to an appropriate integer
9967 // type and then perform the rest of the checks here. GCC will perform
9968 // this conversion in some cases as determined by the input language.
9969 // We should accept it on a language independent basis.
9970 if (VectorEltTy->isIntegralType(S.Context) &&
52
Assuming the condition is false
76
Assuming the condition is false
9971 ScalarTy->isIntegralType(S.Context) &&
9972 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9973
9974 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9975 return true;
9976
9977 ScalarCast = CK_IntegralCast;
9978 } else if (VectorEltTy->isIntegralType(S.Context) &&
53
Assuming the condition is false
77
Assuming the condition is false
9979 ScalarTy->isRealFloatingType()) {
9980 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9981 ScalarCast = CK_FloatingToIntegral;
9982 else
9983 return true;
9984 } else if (VectorEltTy->isRealFloatingType()) {
54
Assuming the condition is false
55
Taking false branch
78
Assuming the condition is false
79
Taking false branch
9985 if (ScalarTy->isRealFloatingType()) {
9986
9987 // Reject cases where the scalar type is not a constant and has a higher
9988 // Order than the vector element type.
9989 llvm::APFloat Result(0.0);
9990
9991 // Determine whether this is a constant scalar. In the event that the
9992 // value is dependent (and thus cannot be evaluated by the constant
9993 // evaluator), skip the evaluation. This will then diagnose once the
9994 // expression is instantiated.
9995 bool CstScalar = Scalar->get()->isValueDependent() ||
9996 Scalar->get()->EvaluateAsFloat(Result, S.Context);
9997 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9998 if (!CstScalar && Order < 0)
9999 return true;
10000
10001 // If the scalar cannot be safely casted to the vector element type,
10002 // reject it.
10003 if (CstScalar) {
10004 bool Truncated = false;
10005 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10006 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10007 if (Truncated)
10008 return true;
10009 }
10010
10011 ScalarCast = CK_FloatingCast;
10012 } else if (ScalarTy->isIntegralType(S.Context)) {
10013 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10014 return true;
10015
10016 ScalarCast = CK_IntegralToFloating;
10017 } else
10018 return true;
10019 } else if (ScalarTy->isEnumeralType())
56
Calling 'Type::isEnumeralType'
59
Returning from 'Type::isEnumeralType'
60
Taking true branch
80
Calling 'Type::isEnumeralType'
83
Returning from 'Type::isEnumeralType'
84
Taking true branch
10020 return true;
61
Returning the value 1, which participates in a condition later
85
Returning the value 1, which participates in a condition later
10021
10022 // Adjust scalar if desired.
10023 if (Scalar) {
10024 if (ScalarCast != CK_NoOp)
10025 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10026 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10027 }
10028 return false;
10029}
10030
10031QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10032 SourceLocation Loc, bool IsCompAssign,
10033 bool AllowBothBool,
10034 bool AllowBoolConversions) {
10035 if (!IsCompAssign) {
1
Assuming 'IsCompAssign' is true
2
Taking false branch
10036 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10037 if (LHS.isInvalid())
10038 return QualType();
10039 }
10040 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10041 if (RHS.isInvalid())
3
Assuming the condition is false
4
Taking false branch
10042 return QualType();
10043
10044 // For conversion purposes, we ignore any qualifiers.
10045 // For example, "const float" and "float" are equivalent.
10046 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10047 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10048
10049 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
5
Assuming the object is not a 'VectorType'
10050 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
6
Assuming the object is not a 'VectorType'
7
'RHSVecType' initialized to a null pointer value
10051 assert(LHSVecType || RHSVecType)((void)0);
10052
10053 if ((LHSVecType
7.1
'LHSVecType' is null
7.1
'LHSVecType' is null
7.1
'LHSVecType' is null
&& LHSVecType->getElementType()->isBFloat16Type()) ||
8
Taking false branch
10054 (RHSVecType
7.2
'RHSVecType' is null
7.2
'RHSVecType' is null
7.2
'RHSVecType' is null
&& RHSVecType->getElementType()->isBFloat16Type()))
10055 return InvalidOperands(Loc, LHS, RHS);
10056
10057 // AltiVec-style "vector bool op vector bool" combinations are allowed
10058 // for some operators but not others.
10059 if (!AllowBothBool &&
9
Assuming 'AllowBothBool' is true
10060 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10061 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10062 return InvalidOperands(Loc, LHS, RHS);
10063
10064 // If the vector types are identical, return.
10065 if (Context.hasSameType(LHSType, RHSType))
10
Assuming the condition is false
11
Taking false branch
10066 return LHSType;
10067
10068 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10069 if (LHSVecType
11.1
'LHSVecType' is null
11.1
'LHSVecType' is null
11.1
'LHSVecType' is null
&& RHSVecType &&
10070 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10071 if (isa<ExtVectorType>(LHSVecType)) {
10072 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10073 return LHSType;
10074 }
10075
10076 if (!IsCompAssign)
10077 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10078 return RHSType;
10079 }
10080
10081 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10082 // can be mixed, with the result being the non-bool type. The non-bool
10083 // operand must have integer element type.
10084 if (AllowBoolConversions && LHSVecType && RHSVecType &&
12
Assuming 'AllowBoolConversions' is false
13
Taking false branch
10085 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10086 (Context.getTypeSize(LHSVecType->getElementType()) ==
10087 Context.getTypeSize(RHSVecType->getElementType()))) {
10088 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10089 LHSVecType->getElementType()->isIntegerType() &&
10090 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10091 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10092 return LHSType;
10093 }
10094 if (!IsCompAssign &&
10095 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10096 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10097 RHSVecType->getElementType()->isIntegerType()) {
10098 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10099 return RHSType;
10100 }
10101 }
10102
10103 // Expressions containing fixed-length and sizeless SVE vectors are invalid
10104 // since the ambiguity can affect the ABI.
10105 auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10106 const VectorType *VecType = SecondType->getAs<VectorType>();
15
Assuming the object is not a 'VectorType'
20
Assuming the object is not a 'VectorType'
10107 return FirstType->isSizelessBuiltinType() && VecType &&
16
Assuming the condition is false
17
Returning zero, which participates in a condition later
21
Assuming the condition is false
22
Returning zero, which participates in a condition later
10108 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10109 VecType->getVectorKind() ==
10110 VectorType::SveFixedLengthPredicateVector);
10111 };
10112
10113 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
14
Calling 'operator()'
18
Returning from 'operator()'
19
Calling 'operator()'
23
Returning from 'operator()'
24
Taking false branch
10114 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10115 return QualType();
10116 }
10117
10118 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10119 // since the ambiguity can affect the ABI.
10120 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10121 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
26
Assuming the object is a 'VectorType'
35
Assuming the object is a 'VectorType'
10122 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
27
Assuming the object is a 'VectorType'
36
Assuming the object is a 'VectorType'
10123
10124 if (FirstVecType && SecondVecType)
28
Assuming 'FirstVecType' is non-null
29
Assuming 'SecondVecType' is non-null
30
Taking true branch
37
Assuming 'FirstVecType' is non-null
38
Assuming 'SecondVecType' is non-null
39
Taking true branch
10125 return FirstVecType->getVectorKind() == VectorType::GenericVector &&
31
Assuming the condition is false
32
Returning zero, which participates in a condition later
40
Assuming the condition is false
41
Returning zero, which participates in a condition later
10126 (SecondVecType->getVectorKind() ==
10127 VectorType::SveFixedLengthDataVector ||
10128 SecondVecType->getVectorKind() ==
10129 VectorType::SveFixedLengthPredicateVector);
10130
10131 return FirstType->isSizelessBuiltinType() && SecondVecType &&
10132 SecondVecType->getVectorKind() == VectorType::GenericVector;
10133 };
10134
10135 if (IsSveGnuConversion(LHSType, RHSType) ||
25
Calling 'operator()'
33
Returning from 'operator()'
43
Taking false branch
10136 IsSveGnuConversion(RHSType, LHSType)) {
34
Calling 'operator()'
42
Returning from 'operator()'
10137 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10138 return QualType();
10139 }
10140
10141 // If there's a vector type and a scalar, try to convert the scalar to
10142 // the vector element type and splat.
10143 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10144 if (!RHSVecType
43.1
'RHSVecType' is null
43.1
'RHSVecType' is null
43.1
'RHSVecType' is null
) {
44
Taking true branch
10145 if (isa<ExtVectorType>(LHSVecType)) {
45
Assuming 'LHSVecType' is not a 'ExtVectorType'
46
Taking false branch
10146 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10147 LHSVecType->getElementType(), LHSType,
10148 DiagID))
10149 return LHSType;
10150 } else {
10151 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
47
Calling 'tryGCCVectorConvertAndSplat'
62
Returning from 'tryGCCVectorConvertAndSplat'
63
Taking false branch
10152 return LHSType;
10153 }
10154 }
10155 if (!LHSVecType
63.1
'LHSVecType' is null
63.1
'LHSVecType' is null
63.1
'LHSVecType' is null
) {
64
Taking true branch
10156 if (isa<ExtVectorType>(RHSVecType)) {
65
Assuming 'RHSVecType' is not a 'ExtVectorType'
66
Taking false branch
10157 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10158 LHSType, RHSVecType->getElementType(),
10159 RHSType, DiagID))
10160 return RHSType;
10161 } else {
10162 if (LHS.get()->isLValue() ||
67
Calling 'Expr::isLValue'
70
Returning from 'Expr::isLValue'
87
Taking false branch
10163 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
71
Calling 'tryGCCVectorConvertAndSplat'
86
Returning from 'tryGCCVectorConvertAndSplat'
10164 return RHSType;
10165 }
10166 }
10167
10168 // FIXME: The code below also handles conversion between vectors and
10169 // non-scalars, we should break this down into fine grained specific checks
10170 // and emit proper diagnostics.
10171 QualType VecType = LHSVecType
87.1
'LHSVecType' is null
87.1
'LHSVecType' is null
87.1
'LHSVecType' is null
? LHSType : RHSType;
88
'?' condition is false
10172 const VectorType *VT = LHSVecType
88.1
'LHSVecType' is null
88.1
'LHSVecType' is null
88.1
'LHSVecType' is null
? LHSVecType : RHSVecType;
89
'?' condition is false
90
'VT' initialized to a null pointer value
10173 QualType OtherType = LHSVecType
90.1
'LHSVecType' is null
90.1
'LHSVecType' is null
90.1
'LHSVecType' is null
? RHSType : LHSType;
91
'?' condition is false
10174 ExprResult *OtherExpr = LHSVecType
91.1
'LHSVecType' is null
91.1
'LHSVecType' is null
91.1
'LHSVecType' is null
? &RHS : &LHS;
92
'?' condition is false
10175 if (isLaxVectorConversion(OtherType, VecType)) {
93
Calling 'Sema::isLaxVectorConversion'
120
Returning from 'Sema::isLaxVectorConversion'
121
Taking true branch
10176 // If we're allowing lax vector conversions, only the total (data) size
10177 // needs to be the same. For non compound assignment, if one of the types is
10178 // scalar, the result is always the vector type.
10179 if (!IsCompAssign
121.1
'IsCompAssign' is true
121.1
'IsCompAssign' is true
121.1
'IsCompAssign' is true
) {
122
Taking false branch
10180 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10181 return VecType;
10182 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10183 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10184 // type. Note that this is already done by non-compound assignments in
10185 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10186 // <1 x T> -> T. The result is also a vector type.
10187 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
123
Calling 'Type::isExtVectorType'
126
Returning from 'Type::isExtVectorType'
127
Calling 'Type::isVectorType'
130
Returning from 'Type::isVectorType'
10188 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
131
Assuming the condition is true
132
Called C++ object pointer is null
10189 ExprResult *RHSExpr = &RHS;
10190 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10191 return VecType;
10192 }
10193 }
10194
10195 // Okay, the expression is invalid.
10196
10197 // If there's a non-vector, non-real operand, diagnose that.
10198 if ((!RHSVecType && !RHSType->isRealType()) ||
10199 (!LHSVecType && !LHSType->isRealType())) {
10200 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10201 << LHSType << RHSType
10202 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10203 return QualType();
10204 }
10205
10206 // OpenCL V1.1 6.2.6.p1:
10207 // If the operands are of more than one vector type, then an error shall
10208 // occur. Implicit conversions between vector types are not permitted, per
10209 // section 6.2.1.
10210 if (getLangOpts().OpenCL &&
10211 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10212 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10213 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10214 << RHSType;
10215 return QualType();
10216 }
10217
10218
10219 // If there is a vector type that is not a ExtVector and a scalar, we reach
10220 // this point if scalar could not be converted to the vector's element type
10221 // without truncation.
10222 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10223 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10224 QualType Scalar = LHSVecType ? RHSType : LHSType;
10225 QualType Vector = LHSVecType ? LHSType : RHSType;
10226 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10227 Diag(Loc,
10228 diag::err_typecheck_vector_not_convertable_implict_truncation)
10229 << ScalarOrVector << Scalar << Vector;
10230
10231 return QualType();
10232 }
10233
10234 // Otherwise, use the generic diagnostic.
10235 Diag(Loc, DiagID)
10236 << LHSType << RHSType
10237 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10238 return QualType();
10239}
10240
10241// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10242// expression. These are mainly cases where the null pointer is used as an
10243// integer instead of a pointer.
10244static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10245 SourceLocation Loc, bool IsCompare) {
10246 // The canonical way to check for a GNU null is with isNullPointerConstant,
10247 // but we use a bit of a hack here for speed; this is a relatively
10248 // hot path, and isNullPointerConstant is slow.
10249 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10250 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10251
10252 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10253
10254 // Avoid analyzing cases where the result will either be invalid (and
10255 // diagnosed as such) or entirely valid and not something to warn about.
10256 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10257 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10258 return;
10259
10260 // Comparison operations would not make sense with a null pointer no matter
10261 // what the other expression is.
10262 if (!IsCompare) {
10263 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10264 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10265 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10266 return;
10267 }
10268
10269 // The rest of the operations only make sense with a null pointer
10270 // if the other expression is a pointer.
10271 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10272 NonNullType->canDecayToPointerType())
10273 return;
10274
10275 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10276 << LHSNull /* LHS is NULL */ << NonNullType
10277 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10278}
10279
10280static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10281 SourceLocation Loc) {
10282 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10283 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10284 if (!LUE || !RUE)
10285 return;
10286 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10287 RUE->getKind() != UETT_SizeOf)
10288 return;
10289
10290 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10291 QualType LHSTy = LHSArg->getType();
10292 QualType RHSTy;
10293
10294 if (RUE->isArgumentType())
10295 RHSTy = RUE->getArgumentType().getNonReferenceType();
10296 else
10297 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10298
10299 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10300 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10301 return;
10302
10303 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10304 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10305 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10306 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10307 << LHSArgDecl;
10308 }
10309 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10310 QualType ArrayElemTy = ArrayTy->getElementType();
10311 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10312 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10313 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10314 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10315 return;
10316 S.Diag(Loc, diag::warn_division_sizeof_array)
10317 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10318 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10319 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10320 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10321 << LHSArgDecl;
10322 }
10323
10324 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10325 }
10326}
10327
10328static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10329 ExprResult &RHS,
10330 SourceLocation Loc, bool IsDiv) {
10331 // Check for division/remainder by zero.
10332 Expr::EvalResult RHSValue;
10333 if (!RHS.get()->isValueDependent() &&
10334 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10335 RHSValue.Val.getInt() == 0)
10336 S.DiagRuntimeBehavior(Loc, RHS.get(),
10337 S.PDiag(diag::warn_remainder_division_by_zero)
10338 << IsDiv << RHS.get()->getSourceRange());
10339}
10340
10341QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10342 SourceLocation Loc,
10343 bool IsCompAssign, bool IsDiv) {
10344 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10345
10346 QualType LHSTy = LHS.get()->getType();
10347 QualType RHSTy = RHS.get()->getType();
10348 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10349 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10350 /*AllowBothBool*/getLangOpts().AltiVec,
10351 /*AllowBoolConversions*/false);
10352 if (!IsDiv &&
10353 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10354 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10355 // For division, only matrix-by-scalar is supported. Other combinations with
10356 // matrix types are invalid.
10357 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10358 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10359
10360 QualType compType = UsualArithmeticConversions(
10361 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10362 if (LHS.isInvalid() || RHS.isInvalid())
10363 return QualType();
10364
10365
10366 if (compType.isNull() || !compType->isArithmeticType())
10367 return InvalidOperands(Loc, LHS, RHS);
10368 if (IsDiv) {
10369 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10370 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10371 }
10372 return compType;
10373}
10374
10375QualType Sema::CheckRemainderOperands(
10376 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10377 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10378
10379 if (LHS.get()->getType()->isVectorType() ||
10380 RHS.get()->getType()->isVectorType()) {
10381 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10382 RHS.get()->getType()->hasIntegerRepresentation())
10383 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10384 /*AllowBothBool*/getLangOpts().AltiVec,
10385 /*AllowBoolConversions*/false);
10386 return InvalidOperands(Loc, LHS, RHS);
10387 }
10388
10389 QualType compType = UsualArithmeticConversions(
10390 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10391 if (LHS.isInvalid() || RHS.isInvalid())
10392 return QualType();
10393
10394 if (compType.isNull() || !compType->isIntegerType())
10395 return InvalidOperands(Loc, LHS, RHS);
10396 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10397 return compType;
10398}
10399
10400/// Diagnose invalid arithmetic on two void pointers.
10401static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10402 Expr *LHSExpr, Expr *RHSExpr) {
10403 S.Diag(Loc, S.getLangOpts().CPlusPlus
10404 ? diag::err_typecheck_pointer_arith_void_type
10405 : diag::ext_gnu_void_ptr)
10406 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10407 << RHSExpr->getSourceRange();
10408}
10409
10410/// Diagnose invalid arithmetic on a void pointer.
10411static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10412 Expr *Pointer) {
10413 S.Diag(Loc, S.getLangOpts().CPlusPlus
10414 ? diag::err_typecheck_pointer_arith_void_type
10415 : diag::ext_gnu_void_ptr)
10416 << 0 /* one pointer */ << Pointer->getSourceRange();
10417}
10418
10419/// Diagnose invalid arithmetic on a null pointer.
10420///
10421/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10422/// idiom, which we recognize as a GNU extension.
10423///
10424static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10425 Expr *Pointer, bool IsGNUIdiom) {
10426 if (IsGNUIdiom)
10427 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10428 << Pointer->getSourceRange();
10429 else
10430 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10431 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10432}
10433
10434/// Diagnose invalid subraction on a null pointer.
10435///
10436static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10437 Expr *Pointer, bool BothNull) {
10438 // Null - null is valid in C++ [expr.add]p7
10439 if (BothNull && S.getLangOpts().CPlusPlus)
10440 return;
10441
10442 // Is this s a macro from a system header?
10443 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10444 return;
10445
10446 S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10447 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10448}
10449
10450/// Diagnose invalid arithmetic on two function pointers.
10451static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10452 Expr *LHS, Expr *RHS) {
10453 assert(LHS->getType()->isAnyPointerType())((void)0);
10454 assert(RHS->getType()->isAnyPointerType())((void)0);
10455 S.Diag(Loc, S.getLangOpts().CPlusPlus
10456 ? diag::err_typecheck_pointer_arith_function_type
10457 : diag::ext_gnu_ptr_func_arith)
10458 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10459 // We only show the second type if it differs from the first.
10460 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10461 RHS->getType())
10462 << RHS->getType()->getPointeeType()
10463 << LHS->getSourceRange() << RHS->getSourceRange();
10464}
10465
10466/// Diagnose invalid arithmetic on a function pointer.
10467static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10468 Expr *Pointer) {
10469 assert(Pointer->getType()->isAnyPointerType())((void)0);
10470 S.Diag(Loc, S.getLangOpts().CPlusPlus
10471 ? diag::err_typecheck_pointer_arith_function_type
10472 : diag::ext_gnu_ptr_func_arith)
10473 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10474 << 0 /* one pointer, so only one type */
10475 << Pointer->getSourceRange();
10476}
10477
10478/// Emit error if Operand is incomplete pointer type
10479///
10480/// \returns True if pointer has incomplete type
10481static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10482 Expr *Operand) {
10483 QualType ResType = Operand->getType();
10484 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10485 ResType = ResAtomicType->getValueType();
10486
10487 assert(ResType->isAnyPointerType() && !ResType->isDependentType())((void)0);
10488 QualType PointeeTy = ResType->getPointeeType();
10489 return S.RequireCompleteSizedType(
10490 Loc, PointeeTy,
10491 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10492 Operand->getSourceRange());
10493}
10494
10495/// Check the validity of an arithmetic pointer operand.
10496///
10497/// If the operand has pointer type, this code will check for pointer types
10498/// which are invalid in arithmetic operations. These will be diagnosed
10499/// appropriately, including whether or not the use is supported as an
10500/// extension.
10501///
10502/// \returns True when the operand is valid to use (even if as an extension).
10503static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10504 Expr *Operand) {
10505 QualType ResType = Operand->getType();
10506 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10507 ResType = ResAtomicType->getValueType();
10508
10509 if (!ResType->isAnyPointerType()) return true;
10510
10511 QualType PointeeTy = ResType->getPointeeType();
10512 if (PointeeTy->isVoidType()) {
10513 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10514 return !S.getLangOpts().CPlusPlus;
10515 }
10516 if (PointeeTy->isFunctionType()) {
10517 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10518 return !S.getLangOpts().CPlusPlus;
10519 }
10520
10521 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10522
10523 return true;
10524}
10525
10526/// Check the validity of a binary arithmetic operation w.r.t. pointer
10527/// operands.
10528///
10529/// This routine will diagnose any invalid arithmetic on pointer operands much
10530/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10531/// for emitting a single diagnostic even for operations where both LHS and RHS
10532/// are (potentially problematic) pointers.
10533///
10534/// \returns True when the operand is valid to use (even if as an extension).
10535static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10536 Expr *LHSExpr, Expr *RHSExpr) {
10537 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10538 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10539 if (!isLHSPointer && !isRHSPointer) return true;
10540
10541 QualType LHSPointeeTy, RHSPointeeTy;
10542 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10543 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10544
10545 // if both are pointers check if operation is valid wrt address spaces
10546 if (isLHSPointer && isRHSPointer) {
10547 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10548 S.Diag(Loc,
10549 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10550 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10551 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10552 return false;
10553 }
10554 }
10555
10556 // Check for arithmetic on pointers to incomplete types.
10557 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10558 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10559 if (isLHSVoidPtr || isRHSVoidPtr) {
10560 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10561 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10562 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10563
10564 return !S.getLangOpts().CPlusPlus;
10565 }
10566
10567 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10568 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10569 if (isLHSFuncPtr || isRHSFuncPtr) {
10570 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10571 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10572 RHSExpr);
10573 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10574
10575 return !S.getLangOpts().CPlusPlus;
10576 }
10577
10578 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10579 return false;
10580 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10581 return false;
10582
10583 return true;
10584}
10585
10586/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10587/// literal.
10588static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10589 Expr *LHSExpr, Expr *RHSExpr) {
10590 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10591 Expr* IndexExpr = RHSExpr;
10592 if (!StrExpr) {
10593 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10594 IndexExpr = LHSExpr;
10595 }
10596
10597 bool IsStringPlusInt = StrExpr &&
10598 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10599 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10600 return;
10601
10602 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10603 Self.Diag(OpLoc, diag::warn_string_plus_int)
10604 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10605
10606 // Only print a fixit for "str" + int, not for int + "str".
10607 if (IndexExpr == RHSExpr) {
10608 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10609 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10610 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10611 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10612 << FixItHint::CreateInsertion(EndLoc, "]");
10613 } else
10614 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10615}
10616
10617/// Emit a warning when adding a char literal to a string.
10618static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10619 Expr *LHSExpr, Expr *RHSExpr) {
10620 const Expr *StringRefExpr = LHSExpr;
10621 const CharacterLiteral *CharExpr =
10622 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10623
10624 if (!CharExpr) {
10625 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10626 StringRefExpr = RHSExpr;
10627 }
10628
10629 if (!CharExpr || !StringRefExpr)
10630 return;
10631
10632 const QualType StringType = StringRefExpr->getType();
10633
10634 // Return if not a PointerType.
10635 if (!StringType->isAnyPointerType())
10636 return;
10637
10638 // Return if not a CharacterType.
10639 if (!StringType->getPointeeType()->isAnyCharacterType())
10640 return;
10641
10642 ASTContext &Ctx = Self.getASTContext();
10643 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10644
10645 const QualType CharType = CharExpr->getType();
10646 if (!CharType->isAnyCharacterType() &&
10647 CharType->isIntegerType() &&
10648 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10649 Self.Diag(OpLoc, diag::warn_string_plus_char)
10650 << DiagRange << Ctx.CharTy;
10651 } else {
10652 Self.Diag(OpLoc, diag::warn_string_plus_char)
10653 << DiagRange << CharExpr->getType();
10654 }
10655
10656 // Only print a fixit for str + char, not for char + str.
10657 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10658 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10659 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10660 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10661 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10662 << FixItHint::CreateInsertion(EndLoc, "]");
10663 } else {
10664 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10665 }
10666}
10667
10668/// Emit error when two pointers are incompatible.
10669static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10670 Expr *LHSExpr, Expr *RHSExpr) {
10671 assert(LHSExpr->getType()->isAnyPointerType())((void)0);
10672 assert(RHSExpr->getType()->isAnyPointerType())((void)0);
10673 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10674 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10675 << RHSExpr->getSourceRange();
10676}
10677
10678// C99 6.5.6
10679QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10680 SourceLocation Loc, BinaryOperatorKind Opc,
10681 QualType* CompLHSTy) {
10682 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10683
10684 if (LHS.get()->getType()->isVectorType() ||
10685 RHS.get()->getType()->isVectorType()) {
10686 QualType compType = CheckVectorOperands(
10687 LHS, RHS, Loc, CompLHSTy,
10688 /*AllowBothBool*/getLangOpts().AltiVec,
10689 /*AllowBoolConversions*/getLangOpts().ZVector);
10690 if (CompLHSTy) *CompLHSTy = compType;
10691 return compType;
10692 }
10693
10694 if (LHS.get()->getType()->isConstantMatrixType() ||
10695 RHS.get()->getType()->isConstantMatrixType()) {
10696 QualType compType =
10697 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10698 if (CompLHSTy)
10699 *CompLHSTy = compType;
10700 return compType;
10701 }
10702
10703 QualType compType = UsualArithmeticConversions(
10704 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10705 if (LHS.isInvalid() || RHS.isInvalid())
10706 return QualType();
10707
10708 // Diagnose "string literal" '+' int and string '+' "char literal".
10709 if (Opc == BO_Add) {
10710 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10711 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10712 }
10713
10714 // handle the common case first (both operands are arithmetic).
10715 if (!compType.isNull() && compType->isArithmeticType()) {
10716 if (CompLHSTy) *CompLHSTy = compType;
10717 return compType;
10718 }
10719
10720 // Type-checking. Ultimately the pointer's going to be in PExp;
10721 // note that we bias towards the LHS being the pointer.
10722 Expr *PExp = LHS.get(), *IExp = RHS.get();
10723
10724 bool isObjCPointer;
10725 if (PExp->getType()->isPointerType()) {
10726 isObjCPointer = false;
10727 } else if (PExp->getType()->isObjCObjectPointerType()) {
10728 isObjCPointer = true;
10729 } else {
10730 std::swap(PExp, IExp);
10731 if (PExp->getType()->isPointerType()) {
10732 isObjCPointer = false;
10733 } else if (PExp->getType()->isObjCObjectPointerType()) {
10734 isObjCPointer = true;
10735 } else {
10736 return InvalidOperands(Loc, LHS, RHS);
10737 }
10738 }
10739 assert(PExp->getType()->isAnyPointerType())((void)0);
10740
10741 if (!IExp->getType()->isIntegerType())
10742 return InvalidOperands(Loc, LHS, RHS);
10743
10744 // Adding to a null pointer results in undefined behavior.
10745 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10746 Context, Expr::NPC_ValueDependentIsNotNull)) {
10747 // In C++ adding zero to a null pointer is defined.
10748 Expr::EvalResult KnownVal;
10749 if (!getLangOpts().CPlusPlus ||
10750 (!IExp->isValueDependent() &&
10751 (!IExp->EvaluateAsInt(KnownVal, Context) ||
10752 KnownVal.Val.getInt() != 0))) {
10753 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10754 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10755 Context, BO_Add, PExp, IExp);
10756 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10757 }
10758 }
10759
10760 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10761 return QualType();
10762
10763 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10764 return QualType();
10765
10766 // Check array bounds for pointer arithemtic
10767 CheckArrayAccess(PExp, IExp);
10768
10769 if (CompLHSTy) {
10770 QualType LHSTy = Context.isPromotableBitField(LHS.get());
10771 if (LHSTy.isNull()) {
10772 LHSTy = LHS.get()->getType();
10773 if (LHSTy->isPromotableIntegerType())
10774 LHSTy = Context.getPromotedIntegerType(LHSTy);
10775 }
10776 *CompLHSTy = LHSTy;
10777 }
10778
10779 return PExp->getType();
10780}
10781
10782// C99 6.5.6
10783QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10784 SourceLocation Loc,
10785 QualType* CompLHSTy) {
10786 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10787
10788 if (LHS.get()->getType()->isVectorType() ||
10789 RHS.get()->getType()->isVectorType()) {
10790 QualType compType = CheckVectorOperands(
10791 LHS, RHS, Loc, CompLHSTy,
10792 /*AllowBothBool*/getLangOpts().AltiVec,
10793 /*AllowBoolConversions*/getLangOpts().ZVector);
10794 if (CompLHSTy) *CompLHSTy = compType;
10795 return compType;
10796 }
10797
10798 if (LHS.get()->getType()->isConstantMatrixType() ||
10799 RHS.get()->getType()->isConstantMatrixType()) {
10800 QualType compType =
10801 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10802 if (CompLHSTy)
10803 *CompLHSTy = compType;
10804 return compType;
10805 }
10806
10807 QualType compType = UsualArithmeticConversions(
10808 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10809 if (LHS.isInvalid() || RHS.isInvalid())
10810 return QualType();
10811
10812 // Enforce type constraints: C99 6.5.6p3.
10813
10814 // Handle the common case first (both operands are arithmetic).
10815 if (!compType.isNull() && compType->isArithmeticType()) {
10816 if (CompLHSTy) *CompLHSTy = compType;
10817 return compType;
10818 }
10819
10820 // Either ptr - int or ptr - ptr.
10821 if (LHS.get()->getType()->isAnyPointerType()) {
10822 QualType lpointee = LHS.get()->getType()->getPointeeType();
10823
10824 // Diagnose bad cases where we step over interface counts.
10825 if (LHS.get()->getType()->isObjCObjectPointerType() &&
10826 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10827 return QualType();
10828
10829 // The result type of a pointer-int computation is the pointer type.
10830 if (RHS.get()->getType()->isIntegerType()) {
10831 // Subtracting from a null pointer should produce a warning.
10832 // The last argument to the diagnose call says this doesn't match the
10833 // GNU int-to-pointer idiom.
10834 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10835 Expr::NPC_ValueDependentIsNotNull)) {
10836 // In C++ adding zero to a null pointer is defined.
10837 Expr::EvalResult KnownVal;
10838 if (!getLangOpts().CPlusPlus ||
10839 (!RHS.get()->isValueDependent() &&
10840 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10841 KnownVal.Val.getInt() != 0))) {
10842 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10843 }
10844 }
10845
10846 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10847 return QualType();
10848
10849 // Check array bounds for pointer arithemtic
10850 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10851 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10852
10853 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10854 return LHS.get()->getType();
10855 }
10856
10857 // Handle pointer-pointer subtractions.
10858 if (const PointerType *RHSPTy
10859 = RHS.get()->getType()->getAs<PointerType>()) {
10860 QualType rpointee = RHSPTy->getPointeeType();
10861
10862 if (getLangOpts().CPlusPlus) {
10863 // Pointee types must be the same: C++ [expr.add]
10864 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10865 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10866 }
10867 } else {
10868 // Pointee types must be compatible C99 6.5.6p3
10869 if (!Context.typesAreCompatible(
10870 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10871 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10872 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10873 return QualType();
10874 }
10875 }
10876
10877 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10878 LHS.get(), RHS.get()))
10879 return QualType();
10880
10881 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
10882 Context, Expr::NPC_ValueDependentIsNotNull);
10883 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
10884 Context, Expr::NPC_ValueDependentIsNotNull);
10885
10886 // Subtracting nullptr or from nullptr is suspect
10887 if (LHSIsNullPtr)
10888 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
10889 if (RHSIsNullPtr)
10890 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
10891
10892 // The pointee type may have zero size. As an extension, a structure or
10893 // union may have zero size or an array may have zero length. In this
10894 // case subtraction does not make sense.
10895 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10896 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10897 if (ElementSize.isZero()) {
10898 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10899 << rpointee.getUnqualifiedType()
10900 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10901 }
10902 }
10903
10904 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10905 return Context.getPointerDiffType();
10906 }
10907 }
10908
10909 return InvalidOperands(Loc, LHS, RHS);
10910}
10911
10912static bool isScopedEnumerationType(QualType T) {
10913 if (const EnumType *ET = T->getAs<EnumType>())
10914 return ET->getDecl()->isScoped();
10915 return false;
10916}
10917
10918static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10919 SourceLocation Loc, BinaryOperatorKind Opc,
10920 QualType LHSType) {
10921 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10922 // so skip remaining warnings as we don't want to modify values within Sema.
10923 if (S.getLangOpts().OpenCL)
10924 return;
10925
10926 // Check right/shifter operand
10927 Expr::EvalResult RHSResult;
10928 if (RHS.get()->isValueDependent() ||
10929 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10930 return;
10931 llvm::APSInt Right = RHSResult.Val.getInt();
10932
10933 if (Right.isNegative()) {
10934 S.DiagRuntimeBehavior(Loc, RHS.get(),
10935 S.PDiag(diag::warn_shift_negative)
10936 << RHS.get()->getSourceRange());
10937 return;
10938 }
10939
10940 QualType LHSExprType = LHS.get()->getType();
10941 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10942 if (LHSExprType->isExtIntType())
10943 LeftSize = S.Context.getIntWidth(LHSExprType);
10944 else if (LHSExprType->isFixedPointType()) {
10945 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10946 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10947 }
10948 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10949 if (Right.uge(LeftBits)) {
10950 S.DiagRuntimeBehavior(Loc, RHS.get(),
10951 S.PDiag(diag::warn_shift_gt_typewidth)
10952 << RHS.get()->getSourceRange());
10953 return;
10954 }
10955
10956 // FIXME: We probably need to handle fixed point types specially here.
10957 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10958 return;
10959
10960 // When left shifting an ICE which is signed, we can check for overflow which
10961 // according to C++ standards prior to C++2a has undefined behavior
10962 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10963 // more than the maximum value representable in the result type, so never
10964 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10965 // expression is still probably a bug.)
10966 Expr::EvalResult LHSResult;
10967 if (LHS.get()->isValueDependent() ||
10968 LHSType->hasUnsignedIntegerRepresentation() ||
10969 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10970 return;
10971 llvm::APSInt Left = LHSResult.Val.getInt();
10972
10973 // If LHS does not have a signed type and non-negative value
10974 // then, the behavior is undefined before C++2a. Warn about it.
10975 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10976 !S.getLangOpts().CPlusPlus20) {
10977 S.DiagRuntimeBehavior(Loc, LHS.get(),
10978 S.PDiag(diag::warn_shift_lhs_negative)
10979 << LHS.get()->getSourceRange());
10980 return;
10981 }
10982
10983 llvm::APInt ResultBits =
10984 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10985 if (LeftBits.uge(ResultBits))
10986 return;
10987 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10988 Result = Result.shl(Right);
10989
10990 // Print the bit representation of the signed integer as an unsigned
10991 // hexadecimal number.
10992 SmallString<40> HexResult;
10993 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10994
10995 // If we are only missing a sign bit, this is less likely to result in actual
10996 // bugs -- if the result is cast back to an unsigned type, it will have the
10997 // expected value. Thus we place this behind a different warning that can be
10998 // turned off separately if needed.
10999 if (LeftBits == ResultBits - 1) {
11000 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11001 << HexResult << LHSType
11002 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11003 return;
11004 }
11005
11006 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11007 << HexResult.str() << Result.getMinSignedBits() << LHSType
11008 << Left.getBitWidth() << LHS.get()->getSourceRange()
11009 << RHS.get()->getSourceRange();
11010}
11011
11012/// Return the resulting type when a vector is shifted
11013/// by a scalar or vector shift amount.
11014static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11015 SourceLocation Loc, bool IsCompAssign) {
11016 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11017 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11018 !LHS.get()->getType()->isVectorType()) {
11019 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11020 << RHS.get()->getType() << LHS.get()->getType()
11021 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11022 return QualType();
11023 }
11024
11025 if (!IsCompAssign) {
11026 LHS = S.UsualUnaryConversions(LHS.get());
11027 if (LHS.isInvalid()) return QualType();
11028 }
11029
11030 RHS = S.UsualUnaryConversions(RHS.get());
11031 if (RHS.isInvalid()) return QualType();
11032
11033 QualType LHSType = LHS.get()->getType();
11034 // Note that LHS might be a scalar because the routine calls not only in
11035 // OpenCL case.
11036 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11037 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11038
11039 // Note that RHS might not be a vector.
11040 QualType RHSType = RHS.get()->getType();
11041 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11042 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11043
11044 // The operands need to be integers.
11045 if (!LHSEleType->isIntegerType()) {
11046 S.Diag(Loc, diag::err_typecheck_expect_int)
11047 << LHS.get()->getType() << LHS.get()->getSourceRange();
11048 return QualType();
11049 }
11050
11051 if (!RHSEleType->isIntegerType()) {
11052 S.Diag(Loc, diag::err_typecheck_expect_int)
11053 << RHS.get()->getType() << RHS.get()->getSourceRange();
11054 return QualType();
11055 }
11056
11057 if (!LHSVecTy) {
11058 assert(RHSVecTy)((void)0);
11059 if (IsCompAssign)
11060 return RHSType;
11061 if (LHSEleType != RHSEleType) {
11062 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11063 LHSEleType = RHSEleType;
11064 }
11065 QualType VecTy =
11066 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11067 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11068 LHSType = VecTy;
11069 } else if (RHSVecTy) {
11070 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11071 // are applied component-wise. So if RHS is a vector, then ensure
11072 // that the number of elements is the same as LHS...
11073 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11074 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11075 << LHS.get()->getType() << RHS.get()->getType()
11076 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11077 return QualType();
11078 }
11079 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11080 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11081 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11082 if (LHSBT != RHSBT &&
11083 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11084 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11085 << LHS.get()->getType() << RHS.get()->getType()
11086 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11087 }
11088 }
11089 } else {
11090 // ...else expand RHS to match the number of elements in LHS.
11091 QualType VecTy =
11092 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11093 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11094 }
11095
11096 return LHSType;
11097}
11098
11099// C99 6.5.7
11100QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11101 SourceLocation Loc, BinaryOperatorKind Opc,
11102 bool IsCompAssign) {
11103 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11104
11105 // Vector shifts promote their scalar inputs to vector type.
11106 if (LHS.get()->getType()->isVectorType() ||
11107 RHS.get()->getType()->isVectorType()) {
11108 if (LangOpts.ZVector) {
11109 // The shift operators for the z vector extensions work basically
11110 // like general shifts, except that neither the LHS nor the RHS is
11111 // allowed to be a "vector bool".
11112 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11113 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11114 return InvalidOperands(Loc, LHS, RHS);
11115 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11116 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11117 return InvalidOperands(Loc, LHS, RHS);
11118 }
11119 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11120 }
11121
11122 // Shifts don't perform usual arithmetic conversions, they just do integer
11123 // promotions on each operand. C99 6.5.7p3
11124
11125 // For the LHS, do usual unary conversions, but then reset them away
11126 // if this is a compound assignment.
11127 ExprResult OldLHS = LHS;
11128 LHS = UsualUnaryConversions(LHS.get());
11129 if (LHS.isInvalid())
11130 return QualType();
11131 QualType LHSType = LHS.get()->getType();
11132 if (IsCompAssign) LHS = OldLHS;
11133
11134 // The RHS is simpler.
11135 RHS = UsualUnaryConversions(RHS.get());
11136 if (RHS.isInvalid())
11137 return QualType();
11138 QualType RHSType = RHS.get()->getType();
11139
11140 // C99 6.5.7p2: Each of the operands shall have integer type.
11141 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11142 if ((!LHSType->isFixedPointOrIntegerType() &&
11143 !LHSType->hasIntegerRepresentation()) ||
11144 !RHSType->hasIntegerRepresentation())
11145 return InvalidOperands(Loc, LHS, RHS);
11146
11147 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11148 // hasIntegerRepresentation() above instead of this.
11149 if (isScopedEnumerationType(LHSType) ||
11150 isScopedEnumerationType(RHSType)) {
11151 return InvalidOperands(Loc, LHS, RHS);
11152 }
11153 // Sanity-check shift operands
11154 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11155
11156 // "The type of the result is that of the promoted left operand."
11157 return LHSType;
11158}
11159
11160/// Diagnose bad pointer comparisons.
11161static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11162 ExprResult &LHS, ExprResult &RHS,
11163 bool IsError) {
11164 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11165 : diag::ext_typecheck_comparison_of_distinct_pointers)
11166 << LHS.get()->getType() << RHS.get()->getType()
11167 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11168}
11169
11170/// Returns false if the pointers are converted to a composite type,
11171/// true otherwise.
11172static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11173 ExprResult &LHS, ExprResult &RHS) {
11174 // C++ [expr.rel]p2:
11175 // [...] Pointer conversions (4.10) and qualification
11176 // conversions (4.4) are performed on pointer operands (or on
11177 // a pointer operand and a null pointer constant) to bring
11178 // them to their composite pointer type. [...]
11179 //
11180 // C++ [expr.eq]p1 uses the same notion for (in)equality
11181 // comparisons of pointers.
11182
11183 QualType LHSType = LHS.get()->getType();
11184 QualType RHSType = RHS.get()->getType();
11185 assert(LHSType->isPointerType() || RHSType->isPointerType() ||((void)0)
11186 LHSType->isMemberPointerType() || RHSType->isMemberPointerType())((void)0);
11187
11188 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11189 if (T.isNull()) {
11190 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11191 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11192 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11193 else
11194 S.InvalidOperands(Loc, LHS, RHS);
11195 return true;
11196 }
11197
11198 return false;
11199}
11200
11201static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11202 ExprResult &LHS,
11203 ExprResult &RHS,
11204 bool IsError) {
11205 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11206 : diag::ext_typecheck_comparison_of_fptr_to_void)
11207 << LHS.get()->getType() << RHS.get()->getType()
11208 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11209}
11210
11211static bool isObjCObjectLiteral(ExprResult &E) {
11212 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11213 case Stmt::ObjCArrayLiteralClass:
11214 case Stmt::ObjCDictionaryLiteralClass:
11215 case Stmt::ObjCStringLiteralClass:
11216 case Stmt::ObjCBoxedExprClass:
11217 return true;
11218 default:
11219 // Note that ObjCBoolLiteral is NOT an object literal!
11220 return false;
11221 }
11222}
11223
11224static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11225 const ObjCObjectPointerType *Type =
11226 LHS->getType()->getAs<ObjCObjectPointerType>();
11227
11228 // If this is not actually an Objective-C object, bail out.
11229 if (!Type)
11230 return false;
11231
11232 // Get the LHS object's interface type.
11233 QualType InterfaceType = Type->getPointeeType();
11234
11235 // If the RHS isn't an Objective-C object, bail out.
11236 if (!RHS->getType()->isObjCObjectPointerType())
11237 return false;
11238
11239 // Try to find the -isEqual: method.
11240 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11241 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11242 InterfaceType,
11243 /*IsInstance=*/true);
11244 if (!Method) {
11245 if (Type->isObjCIdType()) {
11246 // For 'id', just check the global pool.
11247 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11248 /*receiverId=*/true);
11249 } else {
11250 // Check protocols.
11251 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11252 /*IsInstance=*/true);
11253 }
11254 }
11255
11256 if (!Method)
11257 return false;
11258
11259 QualType T = Method->parameters()[0]->getType();
11260 if (!T->isObjCObjectPointerType())
11261 return false;
11262
11263 QualType R = Method->getReturnType();
11264 if (!R->isScalarType())
11265 return false;
11266
11267 return true;
11268}
11269
11270Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11271 FromE = FromE->IgnoreParenImpCasts();
11272 switch (FromE->getStmtClass()) {
11273 default:
11274 break;
11275 case Stmt::ObjCStringLiteralClass:
11276 // "string literal"
11277 return LK_String;
11278 case Stmt::ObjCArrayLiteralClass:
11279 // "array literal"
11280 return LK_Array;
11281 case Stmt::ObjCDictionaryLiteralClass:
11282 // "dictionary literal"
11283 return LK_Dictionary;
11284 case Stmt::BlockExprClass:
11285 return LK_Block;
11286 case Stmt::ObjCBoxedExprClass: {
11287 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11288 switch (Inner->getStmtClass()) {
11289 case Stmt::IntegerLiteralClass:
11290 case Stmt::FloatingLiteralClass:
11291 case Stmt::CharacterLiteralClass:
11292 case Stmt::ObjCBoolLiteralExprClass:
11293 case Stmt::CXXBoolLiteralExprClass:
11294 // "numeric literal"
11295 return LK_Numeric;
11296 case Stmt::ImplicitCastExprClass: {
11297 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11298 // Boolean literals can be represented by implicit casts.
11299 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11300 return LK_Numeric;
11301 break;
11302 }
11303 default:
11304 break;
11305 }
11306 return LK_Boxed;
11307 }
11308 }
11309 return LK_None;
11310}
11311
11312static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11313 ExprResult &LHS, ExprResult &RHS,
11314 BinaryOperator::Opcode Opc){
11315 Expr *Literal;
11316 Expr *Other;
11317 if (isObjCObjectLiteral(LHS)) {
11318 Literal = LHS.get();
11319 Other = RHS.get();
11320 } else {
11321 Literal = RHS.get();
11322 Other = LHS.get();
11323 }
11324
11325 // Don't warn on comparisons against nil.
11326 Other = Other->IgnoreParenCasts();
11327 if (Other->isNullPointerConstant(S.getASTContext(),
11328 Expr::NPC_ValueDependentIsNotNull))
11329 return;
11330
11331 // This should be kept in sync with warn_objc_literal_comparison.
11332 // LK_String should always be after the other literals, since it has its own
11333 // warning flag.
11334 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11335 assert(LiteralKind != Sema::LK_Block)((void)0);
11336 if (LiteralKind == Sema::LK_None) {
11337 llvm_unreachable("Unknown Objective-C object literal kind")__builtin_unreachable();
11338 }
11339
11340 if (LiteralKind == Sema::LK_String)
11341 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11342 << Literal->getSourceRange();
11343 else
11344 S.Diag(Loc, diag::warn_objc_literal_comparison)
11345 << LiteralKind << Literal->getSourceRange();
11346
11347 if (BinaryOperator::isEqualityOp(Opc) &&
11348 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11349 SourceLocation Start = LHS.get()->getBeginLoc();
11350 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11351 CharSourceRange OpRange =
11352 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11353
11354 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11355 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11356 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11357 << FixItHint::CreateInsertion(End, "]");
11358 }
11359}
11360
11361/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11362static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11363 ExprResult &RHS, SourceLocation Loc,
11364 BinaryOperatorKind Opc) {
11365 // Check that left hand side is !something.
11366 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11367 if (!UO || UO->getOpcode() != UO_LNot) return;
11368
11369 // Only check if the right hand side is non-bool arithmetic type.
11370 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11371
11372 // Make sure that the something in !something is not bool.
11373 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11374 if (SubExpr->isKnownToHaveBooleanValue()) return;
11375
11376 // Emit warning.
11377 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11378 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11379 << Loc << IsBitwiseOp;
11380
11381 // First note suggest !(x < y)
11382 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11383 SourceLocation FirstClose = RHS.get()->getEndLoc();
11384 FirstClose = S.getLocForEndOfToken(FirstClose);
11385 if (FirstClose.isInvalid())
11386 FirstOpen = SourceLocation();
11387 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11388 << IsBitwiseOp
11389 << FixItHint::CreateInsertion(FirstOpen, "(")
11390 << FixItHint::CreateInsertion(FirstClose, ")");
11391
11392 // Second note suggests (!x) < y
11393 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11394 SourceLocation SecondClose = LHS.get()->getEndLoc();
11395 SecondClose = S.getLocForEndOfToken(SecondClose);
11396 if (SecondClose.isInvalid())
11397 SecondOpen = SourceLocation();
11398 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11399 << FixItHint::CreateInsertion(SecondOpen, "(")
11400 << FixItHint::CreateInsertion(SecondClose, ")");
11401}
11402
11403// Returns true if E refers to a non-weak array.
11404static bool checkForArray(const Expr *E) {
11405 const ValueDecl *D = nullptr;
11406 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11407 D = DR->getDecl();
11408 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11409 if (Mem->isImplicitAccess())
11410 D = Mem->getMemberDecl();
11411 }
11412 if (!D)
11413 return false;
11414 return D->getType()->isArrayType() && !D->isWeak();
11415}
11416
11417/// Diagnose some forms of syntactically-obvious tautological comparison.
11418static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11419 Expr *LHS, Expr *RHS,
11420 BinaryOperatorKind Opc) {
11421 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11422 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11423
11424 QualType LHSType = LHS->getType();
11425 QualType RHSType = RHS->getType();
11426 if (LHSType->hasFloatingRepresentation() ||
11427 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11428 S.inTemplateInstantiation())
11429 return;
11430
11431 // Comparisons between two array types are ill-formed for operator<=>, so
11432 // we shouldn't emit any additional warnings about it.
11433 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11434 return;
11435
11436 // For non-floating point types, check for self-comparisons of the form
11437 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11438 // often indicate logic errors in the program.
11439 //
11440 // NOTE: Don't warn about comparison expressions resulting from macro
11441 // expansion. Also don't warn about comparisons which are only self
11442 // comparisons within a template instantiation. The warnings should catch
11443 // obvious cases in the definition of the template anyways. The idea is to
11444 // warn when the typed comparison operator will always evaluate to the same
11445 // result.
11446
11447 // Used for indexing into %select in warn_comparison_always
11448 enum {
11449 AlwaysConstant,
11450 AlwaysTrue,
11451 AlwaysFalse,
11452 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11453 };
11454
11455 // C++2a [depr.array.comp]:
11456 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11457 // operands of array type are deprecated.
11458 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11459 RHSStripped->getType()->isArrayType()) {
11460 S.Diag(Loc, diag::warn_depr_array_comparison)
11461 << LHS->getSourceRange() << RHS->getSourceRange()
11462 << LHSStripped->getType() << RHSStripped->getType();
11463 // Carry on to produce the tautological comparison warning, if this
11464 // expression is potentially-evaluated, we can resolve the array to a
11465 // non-weak declaration, and so on.
11466 }
11467
11468 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11469 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11470 unsigned Result;
11471 switch (Opc) {
11472 case BO_EQ:
11473 case BO_LE:
11474 case BO_GE:
11475 Result = AlwaysTrue;
11476 break;
11477 case BO_NE:
11478 case BO_LT:
11479 case BO_GT:
11480 Result = AlwaysFalse;
11481 break;
11482 case BO_Cmp:
11483 Result = AlwaysEqual;
11484 break;
11485 default:
11486 Result = AlwaysConstant;
11487 break;
11488 }
11489 S.DiagRuntimeBehavior(Loc, nullptr,
11490 S.PDiag(diag::warn_comparison_always)
11491 << 0 /*self-comparison*/
11492 << Result);
11493 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11494 // What is it always going to evaluate to?
11495 unsigned Result;
11496 switch (Opc) {
11497 case BO_EQ: // e.g. array1 == array2
11498 Result = AlwaysFalse;
11499 break;
11500 case BO_NE: // e.g. array1 != array2
11501 Result = AlwaysTrue;
11502 break;
11503 default: // e.g. array1 <= array2
11504 // The best we can say is 'a constant'
11505 Result = AlwaysConstant;
11506 break;
11507 }
11508 S.DiagRuntimeBehavior(Loc, nullptr,
11509 S.PDiag(diag::warn_comparison_always)
11510 << 1 /*array comparison*/
11511 << Result);
11512 }
11513 }
11514
11515 if (isa<CastExpr>(LHSStripped))
11516 LHSStripped = LHSStripped->IgnoreParenCasts();
11517 if (isa<CastExpr>(RHSStripped))
11518 RHSStripped = RHSStripped->IgnoreParenCasts();
11519
11520 // Warn about comparisons against a string constant (unless the other
11521 // operand is null); the user probably wants string comparison function.
11522 Expr *LiteralString = nullptr;
11523 Expr *LiteralStringStripped = nullptr;
11524 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11525 !RHSStripped->isNullPointerConstant(S.Context,
11526 Expr::NPC_ValueDependentIsNull)) {
11527 LiteralString = LHS;
11528 LiteralStringStripped = LHSStripped;
11529 } else if ((isa<StringLiteral>(RHSStripped) ||
11530 isa<ObjCEncodeExpr>(RHSStripped)) &&
11531 !LHSStripped->isNullPointerConstant(S.Context,
11532 Expr::NPC_ValueDependentIsNull)) {
11533 LiteralString = RHS;
11534 LiteralStringStripped = RHSStripped;
11535 }
11536
11537 if (LiteralString) {
11538 S.DiagRuntimeBehavior(Loc, nullptr,
11539 S.PDiag(diag::warn_stringcompare)
11540 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11541 << LiteralString->getSourceRange());
11542 }
11543}
11544
11545static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11546 switch (CK) {
11547 default: {
11548#ifndef NDEBUG1
11549 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11550 << "\n";
11551#endif
11552 llvm_unreachable("unhandled cast kind")__builtin_unreachable();
11553 }
11554 case CK_UserDefinedConversion:
11555 return ICK_Identity;
11556 case CK_LValueToRValue:
11557 return ICK_Lvalue_To_Rvalue;
11558 case CK_ArrayToPointerDecay:
11559 return ICK_Array_To_Pointer;
11560 case CK_FunctionToPointerDecay:
11561 return ICK_Function_To_Pointer;
11562 case CK_IntegralCast:
11563 return ICK_Integral_Conversion;
11564 case CK_FloatingCast:
11565 return ICK_Floating_Conversion;
11566 case CK_IntegralToFloating:
11567 case CK_FloatingToIntegral:
11568 return ICK_Floating_Integral;
11569 case CK_IntegralComplexCast:
11570 case CK_FloatingComplexCast:
11571 case CK_FloatingComplexToIntegralComplex:
11572 case CK_IntegralComplexToFloatingComplex:
11573 return ICK_Complex_Conversion;
11574 case CK_FloatingComplexToReal:
11575 case CK_FloatingRealToComplex:
11576 case CK_IntegralComplexToReal:
11577 case CK_IntegralRealToComplex:
11578 return ICK_Complex_Real;
11579 }
11580}
11581
11582static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11583 QualType FromType,
11584 SourceLocation Loc) {
11585 // Check for a narrowing implicit conversion.
11586 StandardConversionSequence SCS;
11587 SCS.setAsIdentityConversion();
11588 SCS.setToType(0, FromType);
11589 SCS.setToType(1, ToType);
11590 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11591 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11592
11593 APValue PreNarrowingValue;
11594 QualType PreNarrowingType;
11595 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11596 PreNarrowingType,
11597 /*IgnoreFloatToIntegralConversion*/ true)) {
11598 case NK_Dependent_Narrowing:
11599 // Implicit conversion to a narrower type, but the expression is
11600 // value-dependent so we can't tell whether it's actually narrowing.
11601 case NK_Not_Narrowing:
11602 return false;
11603
11604 case NK_Constant_Narrowing:
11605 // Implicit conversion to a narrower type, and the value is not a constant
11606 // expression.
11607 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11608 << /*Constant*/ 1
11609 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11610 return true;
11611
11612 case NK_Variable_Narrowing:
11613 // Implicit conversion to a narrower type, and the value is not a constant
11614 // expression.
11615 case NK_Type_Narrowing:
11616 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11617 << /*Constant*/ 0 << FromType << ToType;
11618 // TODO: It's not a constant expression, but what if the user intended it
11619 // to be? Can we produce notes to help them figure out why it isn't?
11620 return true;
11621 }
11622 llvm_unreachable("unhandled case in switch")__builtin_unreachable();
11623}
11624
11625static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11626 ExprResult &LHS,
11627 ExprResult &RHS,
11628 SourceLocation Loc) {
11629 QualType LHSType = LHS.get()->getType();
11630 QualType RHSType = RHS.get()->getType();
11631 // Dig out the original argument type and expression before implicit casts
11632 // were applied. These are the types/expressions we need to check the
11633 // [expr.spaceship] requirements against.
11634 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11635 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11636 QualType LHSStrippedType = LHSStripped.get()->getType();
11637 QualType RHSStrippedType = RHSStripped.get()->getType();
11638
11639 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11640 // other is not, the program is ill-formed.
11641 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11642 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11643 return QualType();
11644 }
11645
11646 // FIXME: Consider combining this with checkEnumArithmeticConversions.
11647 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11648 RHSStrippedType->isEnumeralType();
11649 if (NumEnumArgs == 1) {
11650 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11651 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11652 if (OtherTy->hasFloatingRepresentation()) {
11653 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11654 return QualType();
11655 }
11656 }
11657 if (NumEnumArgs == 2) {
11658 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11659 // type E, the operator yields the result of converting the operands
11660 // to the underlying type of E and applying <=> to the converted operands.
11661 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11662 S.InvalidOperands(Loc, LHS, RHS);
11663 return QualType();
11664 }
11665 QualType IntType =
11666 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11667 assert(IntType->isArithmeticType())((void)0);
11668
11669 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11670 // promote the boolean type, and all other promotable integer types, to
11671 // avoid this.
11672 if (IntType->isPromotableIntegerType())
11673 IntType = S.Context.getPromotedIntegerType(IntType);
11674
11675 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11676 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11677 LHSType = RHSType = IntType;
11678 }
11679
11680 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11681 // usual arithmetic conversions are applied to the operands.
11682 QualType Type =
11683 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11684 if (LHS.isInvalid() || RHS.isInvalid())
11685 return QualType();
11686 if (Type.isNull())
11687 return S.InvalidOperands(Loc, LHS, RHS);
11688
11689 Optional<ComparisonCategoryType> CCT =
11690 getComparisonCategoryForBuiltinCmp(Type);
11691 if (!CCT)
11692 return S.InvalidOperands(Loc, LHS, RHS);
11693
11694 bool HasNarrowing = checkThreeWayNarrowingConversion(
11695 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11696 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11697 RHS.get()->getBeginLoc());
11698 if (HasNarrowing)
11699 return QualType();
11700
11701 assert(!Type.isNull() && "composite type for <=> has not been set")((void)0);
11702
11703 return S.CheckComparisonCategoryType(
11704 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11705}
11706
11707static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11708 ExprResult &RHS,
11709 SourceLocation Loc,
11710 BinaryOperatorKind Opc) {
11711 if (Opc == BO_Cmp)
11712 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11713
11714 // C99 6.5.8p3 / C99 6.5.9p4
11715 QualType Type =
11716 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11717 if (LHS.isInvalid() || RHS.isInvalid())
11718 return QualType();
11719 if (Type.isNull())
11720 return S.InvalidOperands(Loc, LHS, RHS);
11721 assert(Type->isArithmeticType() || Type->isEnumeralType())((void)0);
11722
11723 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11724 return S.InvalidOperands(Loc, LHS, RHS);
11725
11726 // Check for comparisons of floating point operands using != and ==.
11727 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11728 S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11729
11730 // The result of comparisons is 'bool' in C++, 'int' in C.
11731 return S.Context.getLogicalOperationType();
11732}
11733
11734void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11735 if (!NullE.get()->getType()->isAnyPointerType())
11736 return;
11737 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11738 if (!E.get()->getType()->isAnyPointerType() &&
11739 E.get()->isNullPointerConstant(Context,
11740 Expr::NPC_ValueDependentIsNotNull) ==
11741 Expr::NPCK_ZeroExpression) {
11742 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11743 if (CL->getValue() == 0)
11744 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11745 << NullValue
11746 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11747 NullValue ? "NULL" : "(void *)0");
11748 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11749 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11750 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11751 if (T == Context.CharTy)
11752 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11753 << NullValue
11754 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11755 NullValue ? "NULL" : "(void *)0");
11756 }
11757 }
11758}
11759
11760// C99 6.5.8, C++ [expr.rel]
11761QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11762 SourceLocation Loc,
11763 BinaryOperatorKind Opc) {
11764 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11765 bool IsThreeWay = Opc == BO_Cmp;
11766 bool IsOrdered = IsRelational || IsThreeWay;
11767 auto IsAnyPointerType = [](ExprResult E) {
11768 QualType Ty = E.get()->getType();
11769 return Ty->isPointerType() || Ty->isMemberPointerType();
11770 };
11771
11772 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11773 // type, array-to-pointer, ..., conversions are performed on both operands to
11774 // bring them to their composite type.
11775 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11776 // any type-related checks.
11777 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11778 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11779 if (LHS.isInvalid())
11780 return QualType();
11781 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11782 if (RHS.isInvalid())
11783 return QualType();
11784 } else {
11785 LHS = DefaultLvalueConversion(LHS.get());
11786 if (LHS.isInvalid())
11787 return QualType();
11788 RHS = DefaultLvalueConversion(RHS.get());
11789 if (RHS.isInvalid())
11790 return QualType();
11791 }
11792
11793 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11794 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11795 CheckPtrComparisonWithNullChar(LHS, RHS);
11796 CheckPtrComparisonWithNullChar(RHS, LHS);
11797 }
11798
11799 // Handle vector comparisons separately.
11800 if (LHS.get()->getType()->isVectorType() ||
11801 RHS.get()->getType()->isVectorType())
11802 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11803
11804 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11805 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11806
11807 QualType LHSType = LHS.get()->getType();
11808 QualType RHSType = RHS.get()->getType();
11809 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11810 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11811 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11812
11813 const Expr::NullPointerConstantKind LHSNullKind =
11814 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11815 const Expr::NullPointerConstantKind RHSNullKind =
11816 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11817 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11818 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11819
11820 auto computeResultTy = [&]() {
11821 if (Opc != BO_Cmp)
11822 return Context.getLogicalOperationType();
11823 assert(getLangOpts().CPlusPlus)((void)0);
11824 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))((void)0);
11825
11826 QualType CompositeTy = LHS.get()->getType();
11827 assert(!CompositeTy->isReferenceType())((void)0);
11828
11829 Optional<ComparisonCategoryType> CCT =
11830 getComparisonCategoryForBuiltinCmp(CompositeTy);
11831 if (!CCT)
11832 return InvalidOperands(Loc, LHS, RHS);
11833
11834 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11835 // P0946R0: Comparisons between a null pointer constant and an object
11836 // pointer result in std::strong_equality, which is ill-formed under
11837 // P1959R0.
11838 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11839 << (LHSIsNull ? LHS.get()->getSourceRange()
11840 : RHS.get()->getSourceRange());
11841 return QualType();
11842 }
11843
11844 return CheckComparisonCategoryType(
11845 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11846 };
11847
11848 if (!IsOrdered && LHSIsNull != RHSIsNull) {
11849 bool IsEquality = Opc == BO_EQ;
11850 if (RHSIsNull)
11851 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11852 RHS.get()->getSourceRange());
11853 else
11854 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11855 LHS.get()->getSourceRange());
11856 }
11857
11858 if (IsOrdered && LHSType->isFunctionPointerType() &&
11859 RHSType->isFunctionPointerType()) {
11860 // Valid unless a relational comparison of function pointers
11861 bool IsError = Opc == BO_Cmp;
11862 auto DiagID =
11863 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
11864 : getLangOpts().CPlusPlus
11865 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
11866 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
11867 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11868 << RHS.get()->getSourceRange();
11869 if (IsError)
11870 return QualType();
11871 }
11872
11873 if ((LHSType->isIntegerType() && !LHSIsNull) ||
11874 (RHSType->isIntegerType() && !RHSIsNull)) {
11875 // Skip normal pointer conversion checks in this case; we have better
11876 // diagnostics for this below.
11877 } else if (getLangOpts().CPlusPlus) {
11878 // Equality comparison of a function pointer to a void pointer is invalid,
11879 // but we allow it as an extension.
11880 // FIXME: If we really want to allow this, should it be part of composite
11881 // pointer type computation so it works in conditionals too?
11882 if (!IsOrdered &&
11883 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11884 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11885 // This is a gcc extension compatibility comparison.
11886 // In a SFINAE context, we treat this as a hard error to maintain
11887 // conformance with the C++ standard.
11888 diagnoseFunctionPointerToVoidComparison(
11889 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11890
11891 if (isSFINAEContext())
11892 return QualType();
11893
11894 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11895 return computeResultTy();
11896 }
11897
11898 // C++ [expr.eq]p2:
11899 // If at least one operand is a pointer [...] bring them to their
11900 // composite pointer type.
11901 // C++ [expr.spaceship]p6
11902 // If at least one of the operands is of pointer type, [...] bring them
11903 // to their composite pointer type.
11904 // C++ [expr.rel]p2:
11905 // If both operands are pointers, [...] bring them to their composite
11906 // pointer type.
11907 // For <=>, the only valid non-pointer types are arrays and functions, and
11908 // we already decayed those, so this is really the same as the relational
11909 // comparison rule.
11910 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11911 (IsOrdered ? 2 : 1) &&
11912 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11913 RHSType->isObjCObjectPointerType()))) {
11914 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11915 return QualType();
11916 return computeResultTy();
11917 }
11918 } else if (LHSType->isPointerType() &&
11919 RHSType->isPointerType()) { // C99 6.5.8p2
11920 // All of the following pointer-related warnings are GCC extensions, except
11921 // when handling null pointer constants.
11922 QualType LCanPointeeTy =
11923 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11924 QualType RCanPointeeTy =
11925 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11926
11927 // C99 6.5.9p2 and C99 6.5.8p2
11928 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11929 RCanPointeeTy.getUnqualifiedType())) {
11930 if (IsRelational) {
11931 // Pointers both need to point to complete or incomplete types
11932 if ((LCanPointeeTy->isIncompleteType() !=
11933 RCanPointeeTy->isIncompleteType()) &&
11934 !getLangOpts().C11) {
11935 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11936 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11937 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11938 << RCanPointeeTy->isIncompleteType();
11939 }
11940 }
11941 } else if (!IsRelational &&
11942 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11943 // Valid unless comparison between non-null pointer and function pointer
11944 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11945 && !LHSIsNull && !RHSIsNull)
11946 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11947 /*isError*/false);
11948 } else {
11949 // Invalid
11950 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11951 }
11952 if (LCanPointeeTy != RCanPointeeTy) {
11953 // Treat NULL constant as a special case in OpenCL.
11954 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11955 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11956 Diag(Loc,
11957 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11958 << LHSType << RHSType << 0 /* comparison */
11959 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11960 }
11961 }
11962 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11963 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11964 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11965 : CK_BitCast;
11966 if (LHSIsNull && !RHSIsNull)
11967 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11968 else
11969 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11970 }
11971 return computeResultTy();
11972 }
11973
11974 if (getLangOpts().CPlusPlus) {
11975 // C++ [expr.eq]p4:
11976 // Two operands of type std::nullptr_t or one operand of type
11977 // std::nullptr_t and the other a null pointer constant compare equal.
11978 if (!IsOrdered && LHSIsNull && RHSIsNull) {
11979 if (LHSType->isNullPtrType()) {
11980 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11981 return computeResultTy();
11982 }
11983 if (RHSType->isNullPtrType()) {
11984 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11985 return computeResultTy();
11986 }
11987 }
11988
11989 // Comparison of Objective-C pointers and block pointers against nullptr_t.
11990 // These aren't covered by the composite pointer type rules.
11991 if (!IsOrdered && RHSType->isNullPtrType() &&
11992 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11993 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11994 return computeResultTy();
11995 }
11996 if (!IsOrdered && LHSType->isNullPtrType() &&
11997 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11998 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11999 return computeResultTy();
12000 }
12001
12002 if (IsRelational &&
12003 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12004 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12005 // HACK: Relational comparison of nullptr_t against a pointer type is
12006 // invalid per DR583, but we allow it within std::less<> and friends,
12007 // since otherwise common uses of it break.
12008 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12009 // friends to have std::nullptr_t overload candidates.
12010 DeclContext *DC = CurContext;
12011 if (isa<FunctionDecl>(DC))
12012 DC = DC->getParent();
12013 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12014 if (CTSD->isInStdNamespace() &&
12015 llvm::StringSwitch<bool>(CTSD->getName())
12016 .Cases("less", "less_equal", "greater", "greater_equal", true)
12017 .Default(false)) {
12018 if (RHSType->isNullPtrType())
12019 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12020 else
12021 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12022 return computeResultTy();
12023 }
12024 }
12025 }
12026
12027 // C++ [expr.eq]p2:
12028 // If at least one operand is a pointer to member, [...] bring them to
12029 // their composite pointer type.
12030 if (!IsOrdered &&
12031 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12032 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12033 return QualType();
12034 else
12035 return computeResultTy();
12036 }
12037 }
12038
12039 // Handle block pointer types.
12040 if (!IsOrdered && LHSType->isBlockPointerType() &&
12041 RHSType->isBlockPointerType()) {
12042 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12043 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12044
12045 if (!LHSIsNull && !RHSIsNull &&
12046 !Context.typesAreCompatible(lpointee, rpointee)) {
12047 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12048 << LHSType << RHSType << LHS.get()->getSourceRange()
12049 << RHS.get()->getSourceRange();
12050 }
12051 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12052 return computeResultTy();
12053 }
12054
12055 // Allow block pointers to be compared with null pointer constants.
12056 if (!IsOrdered
12057 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12058 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12059 if (!LHSIsNull && !RHSIsNull) {
12060 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12061 ->getPointeeType()->isVoidType())
12062 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12063 ->getPointeeType()->isVoidType())))
12064 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12065 << LHSType << RHSType << LHS.get()->getSourceRange()
12066 << RHS.get()->getSourceRange();
12067 }
12068 if (LHSIsNull && !RHSIsNull)
12069 LHS = ImpCastExprToType(LHS.get(), RHSType,
12070 RHSType->isPointerType() ? CK_BitCast
12071 : CK_AnyPointerToBlockPointerCast);
12072 else
12073 RHS = ImpCastExprToType(RHS.get(), LHSType,
12074 LHSType->isPointerType() ? CK_BitCast
12075 : CK_AnyPointerToBlockPointerCast);
12076 return computeResultTy();
12077 }
12078
12079 if (LHSType->isObjCObjectPointerType() ||
12080 RHSType->isObjCObjectPointerType()) {
12081 const PointerType *LPT = LHSType->getAs<PointerType>();
12082 const PointerType *RPT = RHSType->getAs<PointerType>();
12083 if (LPT || RPT) {
12084 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12085 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12086
12087 if (!LPtrToVoid && !RPtrToVoid &&
12088 !Context.typesAreCompatible(LHSType, RHSType)) {
12089 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12090 /*isError*/false);
12091 }
12092 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12093 // the RHS, but we have test coverage for this behavior.
12094 // FIXME: Consider using convertPointersToCompositeType in C++.
12095 if (LHSIsNull && !RHSIsNull) {
12096 Expr *E = LHS.get();
12097 if (getLangOpts().ObjCAutoRefCount)
12098 CheckObjCConversion(SourceRange(), RHSType, E,
12099 CCK_ImplicitConversion);
12100 LHS = ImpCastExprToType(E, RHSType,
12101 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12102 }
12103 else {
12104 Expr *E = RHS.get();
12105 if (getLangOpts().ObjCAutoRefCount)
12106 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12107 /*Diagnose=*/true,
12108 /*DiagnoseCFAudited=*/false, Opc);
12109 RHS = ImpCastExprToType(E, LHSType,
12110 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12111 }
12112 return computeResultTy();
12113 }
12114 if (LHSType->isObjCObjectPointerType() &&
12115 RHSType->isObjCObjectPointerType()) {
12116 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12117 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12118 /*isError*/false);
12119 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12120 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12121
12122 if (LHSIsNull && !RHSIsNull)
12123 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12124 else
12125 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12126 return computeResultTy();
12127 }
12128
12129 if (!IsOrdered && LHSType->isBlockPointerType() &&
12130 RHSType->isBlockCompatibleObjCPointerType(Context)) {
12131 LHS = ImpCastExprToType(LHS.get(), RHSType,
12132 CK_BlockPointerToObjCPointerCast);
12133 return computeResultTy();
12134 } else if (!IsOrdered &&
12135 LHSType->isBlockCompatibleObjCPointerType(Context) &&
12136 RHSType->isBlockPointerType()) {
12137 RHS = ImpCastExprToType(RHS.get(), LHSType,
12138 CK_BlockPointerToObjCPointerCast);
12139 return computeResultTy();
12140 }
12141 }
12142 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12143 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12144 unsigned DiagID = 0;
12145 bool isError = false;
12146 if (LangOpts.DebuggerSupport) {
12147 // Under a debugger, allow the comparison of pointers to integers,
12148 // since users tend to want to compare addresses.
12149 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12150 (RHSIsNull && RHSType->isIntegerType())) {
12151 if (IsOrdered) {
12152 isError = getLangOpts().CPlusPlus;
12153 DiagID =
12154 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12155 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12156 }
12157 } else if (getLangOpts().CPlusPlus) {
12158 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12159 isError = true;
12160 } else if (IsOrdered)
12161 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12162 else
12163 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12164
12165 if (DiagID) {
12166 Diag(Loc, DiagID)
12167 << LHSType << RHSType << LHS.get()->getSourceRange()
12168 << RHS.get()->getSourceRange();
12169 if (isError)
12170 return QualType();
12171 }
12172
12173 if (LHSType->isIntegerType())
12174 LHS = ImpCastExprToType(LHS.get(), RHSType,
12175 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12176 else
12177 RHS = ImpCastExprToType(RHS.get(), LHSType,
12178 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12179 return computeResultTy();
12180 }
12181
12182 // Handle block pointers.
12183 if (!IsOrdered && RHSIsNull
12184 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12185 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12186 return computeResultTy();
12187 }
12188 if (!IsOrdered && LHSIsNull
12189 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12190 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12191 return computeResultTy();
12192 }
12193
12194 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
12195 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12196 return computeResultTy();
12197 }
12198
12199 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12200 return computeResultTy();
12201 }
12202
12203 if (LHSIsNull && RHSType->isQueueT()) {
12204 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12205 return computeResultTy();
12206 }
12207
12208 if (LHSType->isQueueT() && RHSIsNull) {
12209 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12210 return computeResultTy();
12211 }
12212 }
12213
12214 return InvalidOperands(Loc, LHS, RHS);
12215}
12216
12217// Return a signed ext_vector_type that is of identical size and number of
12218// elements. For floating point vectors, return an integer type of identical
12219// size and number of elements. In the non ext_vector_type case, search from
12220// the largest type to the smallest type to avoid cases where long long == long,
12221// where long gets picked over long long.
12222QualType Sema::GetSignedVectorType(QualType V) {
12223 const VectorType *VTy = V->castAs<VectorType>();
12224 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12225
12226 if (isa<ExtVectorType>(VTy)) {
12227 if (TypeSize == Context.getTypeSize(Context.CharTy))
12228 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12229 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12230 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12231 else if (TypeSize == Context.getTypeSize(Context.IntTy))
12232 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12233 else if (TypeSize == Context.getTypeSize(Context.LongTy))
12234 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12235 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&((void)0)
12236 "Unhandled vector element size in vector compare")((void)0);
12237 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12238 }
12239
12240 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12241 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12242 VectorType::GenericVector);
12243 else if (TypeSize == Context.getTypeSize(Context.LongTy))
12244 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12245 VectorType::GenericVector);
12246 else if (TypeSize == Context.getTypeSize(Context.IntTy))
12247 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12248 VectorType::GenericVector);
12249 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12250 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12251 VectorType::GenericVector);
12252 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&((void)0)
12253 "Unhandled vector element size in vector compare")((void)0);
12254 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12255 VectorType::GenericVector);
12256}
12257
12258/// CheckVectorCompareOperands - vector comparisons are a clang extension that
12259/// operates on extended vector types. Instead of producing an IntTy result,
12260/// like a scalar comparison, a vector comparison produces a vector of integer
12261/// types.
12262QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12263 SourceLocation Loc,
12264 BinaryOperatorKind Opc) {
12265 if (Opc == BO_Cmp) {
12266 Diag(Loc, diag::err_three_way_vector_comparison);
12267 return QualType();
12268 }
12269
12270 // Check to make sure we're operating on vectors of the same type and width,
12271 // Allowing one side to be a scalar of element type.
12272 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12273 /*AllowBothBool*/true,
12274 /*AllowBoolConversions*/getLangOpts().ZVector);
12275 if (vType.isNull())
12276 return vType;
12277
12278 QualType LHSType = LHS.get()->getType();
12279
12280 // Determine the return type of a vector compare. By default clang will return
12281 // a scalar for all vector compares except vector bool and vector pixel.
12282 // With the gcc compiler we will always return a vector type and with the xl
12283 // compiler we will always return a scalar type. This switch allows choosing
12284 // which behavior is prefered.
12285 if (getLangOpts().AltiVec) {
12286 switch (getLangOpts().getAltivecSrcCompat()) {
12287 case LangOptions::AltivecSrcCompatKind::Mixed:
12288 // If AltiVec, the comparison results in a numeric type, i.e.
12289 // bool for C++, int for C
12290 if (vType->castAs<VectorType>()->getVectorKind() ==
12291 VectorType::AltiVecVector)
12292 return Context.getLogicalOperationType();
12293 else
12294 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12295 break;
12296 case LangOptions::AltivecSrcCompatKind::GCC:
12297 // For GCC we always return the vector type.
12298 break;
12299 case LangOptions::AltivecSrcCompatKind::XL:
12300 return Context.getLogicalOperationType();
12301 break;
12302 }
12303 }
12304
12305 // For non-floating point types, check for self-comparisons of the form
12306 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12307 // often indicate logic errors in the program.
12308 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12309
12310 // Check for comparisons of floating point operands using != and ==.
12311 if (BinaryOperator::isEqualityOp(Opc) &&
12312 LHSType->hasFloatingRepresentation()) {
12313 assert(RHS.get()->getType()->hasFloatingRepresentation())((void)0);
12314 CheckFloatComparison(Loc, LHS.get(), RHS.get());
12315 }
12316
12317 // Return a signed type for the vector.
12318 return GetSignedVectorType(vType);
12319}
12320
12321static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12322 const ExprResult &XorRHS,
12323 const SourceLocation Loc) {
12324 // Do not diagnose macros.
12325 if (Loc.isMacroID())
12326 return;
12327
12328 // Do not diagnose if both LHS and RHS are macros.
12329 if (XorLHS.get()->getExprLoc().isMacroID() &&
12330 XorRHS.get()->getExprLoc().isMacroID())
12331 return;
12332
12333 bool Negative = false;
12334 bool ExplicitPlus = false;
12335 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12336 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12337
12338 if (!LHSInt)
12339 return;
12340 if (!RHSInt) {
12341 // Check negative literals.
12342 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12343 UnaryOperatorKind Opc = UO->getOpcode();
12344 if (Opc != UO_Minus && Opc != UO_Plus)
12345 return;
12346 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12347 if (!RHSInt)
12348 return;
12349 Negative = (Opc == UO_Minus);
12350 ExplicitPlus = !Negative;
12351 } else {
12352 return;
12353 }
12354 }
12355
12356 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12357 llvm::APInt RightSideValue = RHSInt->getValue();
12358 if (LeftSideValue != 2 && LeftSideValue != 10)
12359 return;
12360
12361 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12362 return;
12363
12364 CharSourceRange ExprRange = CharSourceRange::getCharRange(
12365 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12366 llvm::StringRef ExprStr =
12367 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12368
12369 CharSourceRange XorRange =
12370 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12371 llvm::StringRef XorStr =
12372 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12373 // Do not diagnose if xor keyword/macro is used.
12374 if (XorStr == "xor")
12375 return;
12376
12377 std::string LHSStr = std::string(Lexer::getSourceText(
12378 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12379 S.getSourceManager(), S.getLangOpts()));
12380 std::string RHSStr = std::string(Lexer::getSourceText(
12381 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12382 S.getSourceManager(), S.getLangOpts()));
12383
12384 if (Negative) {
12385 RightSideValue = -RightSideValue;
12386 RHSStr = "-" + RHSStr;
12387 } else if (ExplicitPlus) {
12388 RHSStr = "+" + RHSStr;
12389 }
12390
12391 StringRef LHSStrRef = LHSStr;
12392 StringRef RHSStrRef = RHSStr;
12393 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12394 // literals.
12395 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12396 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12397 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12398 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12399 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12400 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12401 LHSStrRef.find('\'') != StringRef::npos ||
12402 RHSStrRef.find('\'') != StringRef::npos)
12403 return;
12404
12405 bool SuggestXor =
12406 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12407 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12408 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12409 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12410 std::string SuggestedExpr = "1 << " + RHSStr;
12411 bool Overflow = false;
12412 llvm::APInt One = (LeftSideValue - 1);
12413 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12414 if (Overflow) {
12415 if (RightSideIntValue < 64)
12416 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12417 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12418 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12419 else if (RightSideIntValue == 64)
12420 S.Diag(Loc, diag::warn_xor_used_as_pow)
12421 << ExprStr << toString(XorValue, 10, true);
12422 else
12423 return;
12424 } else {
12425 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12426 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12427 << toString(PowValue, 10, true)
12428 << FixItHint::CreateReplacement(
12429 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12430 }
12431
12432 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12433 << ("0x2 ^ " + RHSStr) << SuggestXor;
12434 } else if (LeftSideValue == 10) {
12435 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12436 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12437 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12438 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12439 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12440 << ("0xA ^ " + RHSStr) << SuggestXor;
12441 }
12442}
12443
12444QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12445 SourceLocation Loc) {
12446 // Ensure that either both operands are of the same vector type, or
12447 // one operand is of a vector type and the other is of its element type.
12448 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12449 /*AllowBothBool*/true,
12450 /*AllowBoolConversions*/false);
12451 if (vType.isNull())
12452 return InvalidOperands(Loc, LHS, RHS);
12453 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12454 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12455 return InvalidOperands(Loc, LHS, RHS);
12456 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12457 // usage of the logical operators && and || with vectors in C. This
12458 // check could be notionally dropped.
12459 if (!getLangOpts().CPlusPlus &&
12460 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12461 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12462
12463 return GetSignedVectorType(LHS.get()->getType());
12464}
12465
12466QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12467 SourceLocation Loc,
12468 bool IsCompAssign) {
12469 if (!IsCompAssign) {
12470 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12471 if (LHS.isInvalid())
12472 return QualType();
12473 }
12474 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12475 if (RHS.isInvalid())
12476 return QualType();
12477
12478 // For conversion purposes, we ignore any qualifiers.
12479 // For example, "const float" and "float" are equivalent.
12480 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12481 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12482
12483 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12484 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12485 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")((void)0);
12486
12487 if (Context.hasSameType(LHSType, RHSType))
12488 return LHSType;
12489
12490 // Type conversion may change LHS/RHS. Keep copies to the original results, in
12491 // case we have to return InvalidOperands.
12492 ExprResult OriginalLHS = LHS;
12493 ExprResult OriginalRHS = RHS;
12494 if (LHSMatType && !RHSMatType) {
12495 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12496 if (!RHS.isInvalid())
12497 return LHSType;
12498
12499 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12500 }
12501
12502 if (!LHSMatType && RHSMatType) {
12503 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12504 if (!LHS.isInvalid())
12505 return RHSType;
12506 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12507 }
12508
12509 return InvalidOperands(Loc, LHS, RHS);
12510}
12511
12512QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12513 SourceLocation Loc,
12514 bool IsCompAssign) {
12515 if (!IsCompAssign) {
12516 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12517 if (LHS.isInvalid())
12518 return QualType();
12519 }
12520 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12521 if (RHS.isInvalid())
12522 return QualType();
12523
12524 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12525 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12526 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")((void)0);
12527
12528 if (LHSMatType && RHSMatType) {
12529 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12530 return InvalidOperands(Loc, LHS, RHS);
12531
12532 if (!Context.hasSameType(LHSMatType->getElementType(),
12533 RHSMatType->getElementType()))
12534 return InvalidOperands(Loc, LHS, RHS);
12535
12536 return Context.getConstantMatrixType(LHSMatType->getElementType(),
12537 LHSMatType->getNumRows(),
12538 RHSMatType->getNumColumns());
12539 }
12540 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12541}
12542
12543inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12544 SourceLocation Loc,
12545 BinaryOperatorKind Opc) {
12546 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12547
12548 bool IsCompAssign =
12549 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12550
12551 if (LHS.get()->getType()->isVectorType() ||
12552 RHS.get()->getType()->isVectorType()) {
12553 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12554 RHS.get()->getType()->hasIntegerRepresentation())
12555 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12556 /*AllowBothBool*/true,
12557 /*AllowBoolConversions*/getLangOpts().ZVector);
12558 return InvalidOperands(Loc, LHS, RHS);
12559 }
12560
12561 if (Opc == BO_And)
12562 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12563
12564 if (LHS.get()->getType()->hasFloatingRepresentation() ||
12565 RHS.get()->getType()->hasFloatingRepresentation())
12566 return InvalidOperands(Loc, LHS, RHS);
12567
12568 ExprResult LHSResult = LHS, RHSResult = RHS;
12569 QualType compType = UsualArithmeticConversions(
12570 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12571 if (LHSResult.isInvalid() || RHSResult.isInvalid())
12572 return QualType();
12573 LHS = LHSResult.get();
12574 RHS = RHSResult.get();
12575
12576 if (Opc == BO_Xor)
12577 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12578
12579 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12580 return compType;
12581 return InvalidOperands(Loc, LHS, RHS);
12582}
12583
12584// C99 6.5.[13,14]
12585inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12586 SourceLocation Loc,
12587 BinaryOperatorKind Opc) {
12588 // Check vector operands differently.
12589 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12590 return CheckVectorLogicalOperands(LHS, RHS, Loc);
12591
12592 bool EnumConstantInBoolContext = false;
12593 for (const ExprResult &HS : {LHS, RHS}) {
12594 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12595 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12596 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12597 EnumConstantInBoolContext = true;
12598 }
12599 }
12600
12601 if (EnumConstantInBoolContext)
12602 Diag(Loc, diag::warn_enum_constant_in_bool_context);
12603
12604 // Diagnose cases where the user write a logical and/or but probably meant a
12605 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
12606 // is a constant.
12607 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12608 !LHS.get()->getType()->isBooleanType() &&
12609 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12610 // Don't warn in macros or template instantiations.
12611 !Loc.isMacroID() && !inTemplateInstantiation()) {
12612 // If the RHS can be constant folded, and if it constant folds to something
12613 // that isn't 0 or 1 (which indicate a potential logical operation that
12614 // happened to fold to true/false) then warn.
12615 // Parens on the RHS are ignored.
12616 Expr::EvalResult EVResult;
12617 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12618 llvm::APSInt Result = EVResult.Val.getInt();
12619 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12620 !RHS.get()->getExprLoc().isMacroID()) ||
12621 (Result != 0 && Result != 1)) {
12622 Diag(Loc, diag::warn_logical_instead_of_bitwise)
12623 << RHS.get()->getSourceRange()
12624 << (Opc == BO_LAnd ? "&&" : "||");
12625 // Suggest replacing the logical operator with the bitwise version
12626 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12627 << (Opc == BO_LAnd ? "&" : "|")
12628 << FixItHint::CreateReplacement(SourceRange(
12629 Loc, getLocForEndOfToken(Loc)),
12630 Opc == BO_LAnd ? "&" : "|");
12631 if (Opc == BO_LAnd)
12632 // Suggest replacing "Foo() && kNonZero" with "Foo()"
12633 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12634 << FixItHint::CreateRemoval(
12635 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12636 RHS.get()->getEndLoc()));
12637 }
12638 }
12639 }
12640
12641 if (!Context.getLangOpts().CPlusPlus) {
12642 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12643 // not operate on the built-in scalar and vector float types.
12644 if (Context.getLangOpts().OpenCL &&
12645 Context.getLangOpts().OpenCLVersion < 120) {
12646 if (LHS.get()->getType()->isFloatingType() ||
12647 RHS.get()->getType()->isFloatingType())
12648 return InvalidOperands(Loc, LHS, RHS);
12649 }
12650
12651 LHS = UsualUnaryConversions(LHS.get());
12652 if (LHS.isInvalid())
12653 return QualType();
12654
12655 RHS = UsualUnaryConversions(RHS.get());
12656 if (RHS.isInvalid())
12657 return QualType();
12658
12659 if (!LHS.get()->getType()->isScalarType() ||
12660 !RHS.get()->getType()->isScalarType())
12661 return InvalidOperands(Loc, LHS, RHS);
12662
12663 return Context.IntTy;
12664 }
12665
12666 // The following is safe because we only use this method for
12667 // non-overloadable operands.
12668
12669 // C++ [expr.log.and]p1
12670 // C++ [expr.log.or]p1
12671 // The operands are both contextually converted to type bool.
12672 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12673 if (LHSRes.isInvalid())
12674 return InvalidOperands(Loc, LHS, RHS);
12675 LHS = LHSRes;
12676
12677 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12678 if (RHSRes.isInvalid())
12679 return InvalidOperands(Loc, LHS, RHS);
12680 RHS = RHSRes;
12681
12682 // C++ [expr.log.and]p2
12683 // C++ [expr.log.or]p2
12684 // The result is a bool.
12685 return Context.BoolTy;
12686}
12687
12688static bool IsReadonlyMessage(Expr *E, Sema &S) {
12689 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12690 if (!ME) return false;
12691 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12692 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12693 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12694 if (!Base) return false;
12695 return Base->getMethodDecl() != nullptr;
12696}
12697
12698/// Is the given expression (which must be 'const') a reference to a
12699/// variable which was originally non-const, but which has become
12700/// 'const' due to being captured within a block?
12701enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12702static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12703 assert(E->isLValue() && E->getType().isConstQualified())((void)0);
12704 E = E->IgnoreParens();
12705
12706 // Must be a reference to a declaration from an enclosing scope.
12707 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12708 if (!DRE) return NCCK_None;
12709 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12710
12711 // The declaration must be a variable which is not declared 'const'.
12712 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12713 if (!var) return NCCK_None;
12714 if (var->getType().isConstQualified()) return NCCK_None;
12715 assert(var->hasLocalStorage() && "capture added 'const' to non-local?")((void)0);
12716
12717 // Decide whether the first capture was for a block or a lambda.
12718 DeclContext *DC = S.CurContext, *Prev = nullptr;
12719 // Decide whether the first capture was for a block or a lambda.
12720 while (DC) {
12721 // For init-capture, it is possible that the variable belongs to the
12722 // template pattern of the current context.
12723 if (auto *FD = dyn_cast<FunctionDecl>(DC))
12724 if (var->isInitCapture() &&
12725 FD->getTemplateInstantiationPattern() == var->getDeclContext())
12726 break;
12727 if (DC == var->getDeclContext())
12728 break;
12729 Prev = DC;
12730 DC = DC->getParent();
12731 }
12732 // Unless we have an init-capture, we've gone one step too far.
12733 if (!var->isInitCapture())
12734 DC = Prev;
12735 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12736}
12737
12738static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12739 Ty = Ty.getNonReferenceType();
12740 if (IsDereference && Ty->isPointerType())
12741 Ty = Ty->getPointeeType();
12742 return !Ty.isConstQualified();
12743}
12744
12745// Update err_typecheck_assign_const and note_typecheck_assign_const
12746// when this enum is changed.
12747enum {
12748 ConstFunction,
12749 ConstVariable,
12750 ConstMember,
12751 ConstMethod,
12752 NestedConstMember,
12753 ConstUnknown, // Keep as last element
12754};
12755
12756/// Emit the "read-only variable not assignable" error and print notes to give
12757/// more information about why the variable is not assignable, such as pointing
12758/// to the declaration of a const variable, showing that a method is const, or
12759/// that the function is returning a const reference.
12760static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12761 SourceLocation Loc) {
12762 SourceRange ExprRange = E->getSourceRange();
12763
12764 // Only emit one error on the first const found. All other consts will emit
12765 // a note to the error.
12766 bool DiagnosticEmitted = false;
12767
12768 // Track if the current expression is the result of a dereference, and if the
12769 // next checked expression is the result of a dereference.
12770 bool IsDereference = false;
12771 bool NextIsDereference = false;
12772
12773 // Loop to process MemberExpr chains.
12774 while (true) {
12775 IsDereference = NextIsDereference;
12776
12777 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12778 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12779 NextIsDereference = ME->isArrow();
12780 const ValueDecl *VD = ME->getMemberDecl();
12781 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12782 // Mutable fields can be modified even if the class is const.
12783 if (Field->isMutable()) {
12784 assert(DiagnosticEmitted && "Expected diagnostic not emitted.")((void)0);
12785 break;
12786 }
12787
12788 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12789 if (!DiagnosticEmitted) {
12790 S.Diag(Loc, diag::err_typecheck_assign_const)
12791 << ExprRange << ConstMember << false /*static*/ << Field
12792 << Field->getType();
12793 DiagnosticEmitted = true;
12794 }
12795 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12796 << ConstMember << false /*static*/ << Field << Field->getType()
12797 << Field->getSourceRange();
12798 }
12799 E = ME->getBase();
12800 continue;
12801 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12802 if (VDecl->getType().isConstQualified()) {
12803 if (!DiagnosticEmitted) {
12804 S.Diag(Loc, diag::err_typecheck_assign_const)
12805 << ExprRange << ConstMember << true /*static*/ << VDecl
12806 << VDecl->getType();
12807 DiagnosticEmitted = true;
12808 }
12809 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12810 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12811 << VDecl->getSourceRange();
12812 }
12813 // Static fields do not inherit constness from parents.
12814 break;
12815 }
12816 break; // End MemberExpr
12817 } else if (const ArraySubscriptExpr *ASE =
12818 dyn_cast<ArraySubscriptExpr>(E)) {
12819 E = ASE->getBase()->IgnoreParenImpCasts();
12820 continue;
12821 } else if (const ExtVectorElementExpr *EVE =
12822 dyn_cast<ExtVectorElementExpr>(E)) {
12823 E = EVE->getBase()->IgnoreParenImpCasts();
12824 continue;
12825 }
12826 break;
12827 }
12828
12829 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12830 // Function calls
12831 const FunctionDecl *FD = CE->getDirectCallee();
12832 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12833 if (!DiagnosticEmitted) {
12834 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12835 << ConstFunction << FD;
12836 DiagnosticEmitted = true;
12837 }
12838 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12839 diag::note_typecheck_assign_const)
12840 << ConstFunction << FD << FD->getReturnType()
12841 << FD->getReturnTypeSourceRange();
12842 }
12843 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12844 // Point to variable declaration.
12845 if (const ValueDecl *VD = DRE->getDecl()) {
12846 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12847 if (!DiagnosticEmitted) {
12848 S.Diag(Loc, diag::err_typecheck_assign_const)
12849 << ExprRange << ConstVariable << VD << VD->getType();
12850 DiagnosticEmitted = true;
12851 }
12852 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12853 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12854 }
12855 }
12856 } else if (isa<CXXThisExpr>(E)) {
12857 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12858 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12859 if (MD->isConst()) {
12860 if (!DiagnosticEmitted) {
12861 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12862 << ConstMethod << MD;
12863 DiagnosticEmitted = true;
12864 }
12865 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12866 << ConstMethod << MD << MD->getSourceRange();
12867 }
12868 }
12869 }
12870 }
12871
12872 if (DiagnosticEmitted)
12873 return;
12874
12875 // Can't determine a more specific message, so display the generic error.
12876 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12877}
12878
12879enum OriginalExprKind {
12880 OEK_Variable,
12881 OEK_Member,
12882 OEK_LValue
12883};
12884
12885static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12886 const RecordType *Ty,
12887 SourceLocation Loc, SourceRange Range,
12888 OriginalExprKind OEK,
12889 bool &DiagnosticEmitted) {
12890 std::vector<const RecordType *> RecordTypeList;
12891 RecordTypeList.push_back(Ty);
12892 unsigned NextToCheckIndex = 0;
12893 // We walk the record hierarchy breadth-first to ensure that we print
12894 // diagnostics in field nesting order.
12895 while (RecordTypeList.size() > NextToCheckIndex) {
12896 bool IsNested = NextToCheckIndex > 0;
12897 for (const FieldDecl *Field :
12898 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12899 // First, check every field for constness.
12900 QualType FieldTy = Field->getType();
12901 if (FieldTy.isConstQualified()) {
12902 if (!DiagnosticEmitted) {
12903 S.Diag(Loc, diag::err_typecheck_assign_const)
12904 << Range << NestedConstMember << OEK << VD
12905 << IsNested << Field;
12906 DiagnosticEmitted = true;
12907 }
12908 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12909 << NestedConstMember << IsNested << Field
12910 << FieldTy << Field->getSourceRange();
12911 }
12912
12913 // Then we append it to the list to check next in order.
12914 FieldTy = FieldTy.getCanonicalType();
12915 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12916 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12917 RecordTypeList.push_back(FieldRecTy);
12918 }
12919 }
12920 ++NextToCheckIndex;
12921 }
12922}
12923
12924/// Emit an error for the case where a record we are trying to assign to has a
12925/// const-qualified field somewhere in its hierarchy.
12926static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12927 SourceLocation Loc) {
12928 QualType Ty = E->getType();
12929 assert(Ty->isRecordType() && "lvalue was not record?")((void)0);
12930 SourceRange Range = E->getSourceRange();
12931 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12932 bool DiagEmitted = false;
12933
12934 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12935 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12936 Range, OEK_Member, DiagEmitted);
12937 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12938 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12939 Range, OEK_Variable, DiagEmitted);
12940 else
12941 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12942 Range, OEK_LValue, DiagEmitted);
12943 if (!DiagEmitted)
12944 DiagnoseConstAssignment(S, E, Loc);
12945}
12946
12947/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
12948/// emit an error and return true. If so, return false.
12949static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12950 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))((void)0);
12951
12952 S.CheckShadowingDeclModification(E, Loc);
12953
12954 SourceLocation OrigLoc = Loc;
12955 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12956 &Loc);
12957 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12958 IsLV = Expr::MLV_InvalidMessageExpression;
12959 if (IsLV == Expr::MLV_Valid)
12960 return false;
12961
12962 unsigned DiagID = 0;
12963 bool NeedType = false;
12964 switch (IsLV) { // C99 6.5.16p2
12965 case Expr::MLV_ConstQualified:
12966 // Use a specialized diagnostic when we're assigning to an object
12967 // from an enclosing function or block.
12968 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12969 if (NCCK == NCCK_Block)
12970 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12971 else
12972 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12973 break;
12974 }
12975
12976 // In ARC, use some specialized diagnostics for occasions where we
12977 // infer 'const'. These are always pseudo-strong variables.
12978 if (S.getLangOpts().ObjCAutoRefCount) {
12979 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12980 if (declRef && isa<VarDecl>(declRef->getDecl())) {
12981 VarDecl *var = cast<VarDecl>(declRef->getDecl());
12982
12983 // Use the normal diagnostic if it's pseudo-__strong but the
12984 // user actually wrote 'const'.
12985 if (var->isARCPseudoStrong() &&
12986 (!var->getTypeSourceInfo() ||
12987 !var->getTypeSourceInfo()->getType().isConstQualified())) {
12988 // There are three pseudo-strong cases:
12989 // - self
12990 ObjCMethodDecl *method = S.getCurMethodDecl();
12991 if (method && var == method->getSelfDecl()) {
12992 DiagID = method->isClassMethod()
12993 ? diag::err_typecheck_arc_assign_self_class_method
12994 : diag::err_typecheck_arc_assign_self;
12995
12996 // - Objective-C externally_retained attribute.
12997 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12998 isa<ParmVarDecl>(var)) {
12999 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13000
13001 // - fast enumeration variables
13002 } else {
13003 DiagID = diag::err_typecheck_arr_assign_enumeration;
13004 }
13005
13006 SourceRange Assign;
13007 if (Loc != OrigLoc)
13008 Assign = SourceRange(OrigLoc, OrigLoc);
13009 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13010 // We need to preserve the AST regardless, so migration tool
13011 // can do its job.
13012 return false;
13013 }
13014 }
13015 }
13016
13017 // If none of the special cases above are triggered, then this is a
13018 // simple const assignment.
13019 if (DiagID == 0) {
13020 DiagnoseConstAssignment(S, E, Loc);
13021 return true;
13022 }
13023
13024 break;
13025 case Expr::MLV_ConstAddrSpace:
13026 DiagnoseConstAssignment(S, E, Loc);
13027 return true;
13028 case Expr::MLV_ConstQualifiedField:
13029 DiagnoseRecursiveConstFields(S, E, Loc);
13030 return true;
13031 case Expr::MLV_ArrayType:
13032 case Expr::MLV_ArrayTemporary:
13033 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13034 NeedType = true;
13035 break;
13036 case Expr::MLV_NotObjectType:
13037 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13038 NeedType = true;
13039 break;
13040 case Expr::MLV_LValueCast:
13041 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13042 break;
13043 case Expr::MLV_Valid:
13044 llvm_unreachable("did not take early return for MLV_Valid")__builtin_unreachable();
13045 case Expr::MLV_InvalidExpression:
13046 case Expr::MLV_MemberFunction:
13047 case Expr::MLV_ClassTemporary:
13048 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13049 break;
13050 case Expr::MLV_IncompleteType:
13051 case Expr::MLV_IncompleteVoidType:
13052 return S.RequireCompleteType(Loc, E->getType(),
13053 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13054 case Expr::MLV_DuplicateVectorComponents:
13055 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13056 break;
13057 case Expr::MLV_NoSetterProperty:
13058 llvm_unreachable("readonly properties should be processed differently")__builtin_unreachable();
13059 case Expr::MLV_InvalidMessageExpression:
13060 DiagID = diag::err_readonly_message_assignment;
13061 break;
13062 case Expr::MLV_SubObjCPropertySetting:
13063 DiagID = diag::err_no_subobject_property_setting;
13064 break;
13065 }
13066
13067 SourceRange Assign;
13068 if (Loc != OrigLoc)
13069 Assign = SourceRange(OrigLoc, OrigLoc);
13070 if (NeedType)
13071 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13072 else
13073 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13074 return true;
13075}
13076
13077static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13078 SourceLocation Loc,
13079 Sema &Sema) {
13080 if (Sema.inTemplateInstantiation())
13081 return;
13082 if (Sema.isUnevaluatedContext())
13083 return;
13084 if (Loc.isInvalid() || Loc.isMacroID())
13085 return;
13086 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13087 return;
13088
13089 // C / C++ fields
13090 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13091 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13092 if (ML && MR) {
13093 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13094 return;
13095 const ValueDecl *LHSDecl =
13096 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13097 const ValueDecl *RHSDecl =
13098 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13099 if (LHSDecl != RHSDecl)
13100 return;
13101 if (LHSDecl->getType().isVolatileQualified())
13102 return;
13103 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13104 if (RefTy->getPointeeType().isVolatileQualified())
13105 return;
13106
13107 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13108 }
13109
13110 // Objective-C instance variables
13111 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13112 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13113 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13114 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13115 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13116 if (RL && RR && RL->getDecl() == RR->getDecl())
13117 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13118 }
13119}
13120
13121// C99 6.5.16.1
13122QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13123 SourceLocation Loc,
13124 QualType CompoundType) {
13125 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))((void)0);
13126
13127 // Verify that LHS is a modifiable lvalue, and emit error if not.
13128 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13129 return QualType();
13130
13131 QualType LHSType = LHSExpr->getType();
13132 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13133 CompoundType;
13134 // OpenCL v1.2 s6.1.1.1 p2:
13135 // The half data type can only be used to declare a pointer to a buffer that
13136 // contains half values
13137 if (getLangOpts().OpenCL &&
13138 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13139 LHSType->isHalfType()) {
13140 Diag(Loc, diag::err_opencl_half_load_store) << 1
13141 << LHSType.getUnqualifiedType();
13142 return QualType();
13143 }
13144
13145 AssignConvertType ConvTy;
13146 if (CompoundType.isNull()) {
13147 Expr *RHSCheck = RHS.get();
13148
13149 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13150
13151 QualType LHSTy(LHSType);
13152 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13153 if (RHS.isInvalid())
13154 return QualType();
13155 // Special case of NSObject attributes on c-style pointer types.
13156 if (ConvTy == IncompatiblePointer &&
13157 ((Context.isObjCNSObjectType(LHSType) &&
13158 RHSType->isObjCObjectPointerType()) ||
13159 (Context.isObjCNSObjectType(RHSType) &&
13160 LHSType->isObjCObjectPointerType())))
13161 ConvTy = Compatible;
13162
13163 if (ConvTy == Compatible &&
13164 LHSType->isObjCObjectType())
13165 Diag(Loc, diag::err_objc_object_assignment)
13166 << LHSType;
13167
13168 // If the RHS is a unary plus or minus, check to see if they = and + are
13169 // right next to each other. If so, the user may have typo'd "x =+ 4"
13170 // instead of "x += 4".
13171 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13172 RHSCheck = ICE->getSubExpr();
13173 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13174 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13175 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13176 // Only if the two operators are exactly adjacent.
13177 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13178 // And there is a space or other character before the subexpr of the
13179 // unary +/-. We don't want to warn on "x=-1".
13180 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13181 UO->getSubExpr()->getBeginLoc().isFileID()) {
13182 Diag(Loc, diag::warn_not_compound_assign)
13183 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13184 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13185 }
13186 }
13187
13188 if (ConvTy == Compatible) {
13189 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13190 // Warn about retain cycles where a block captures the LHS, but
13191 // not if the LHS is a simple variable into which the block is
13192 // being stored...unless that variable can be captured by reference!
13193 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13194 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13195 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13196 checkRetainCycles(LHSExpr, RHS.get());
13197 }
13198
13199 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13200 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13201 // It is safe to assign a weak reference into a strong variable.
13202 // Although this code can still have problems:
13203 // id x = self.weakProp;
13204 // id y = self.weakProp;
13205 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13206 // paths through the function. This should be revisited if
13207 // -Wrepeated-use-of-weak is made flow-sensitive.
13208 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13209 // variable, which will be valid for the current autorelease scope.
13210 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13211 RHS.get()->getBeginLoc()))
13212 getCurFunction()->markSafeWeakUse(RHS.get());
13213
13214 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13215 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13216 }
13217 }
13218 } else {
13219 // Compound assignment "x += y"
13220 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13221 }
13222
13223 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13224 RHS.get(), AA_Assigning))
13225 return QualType();
13226
13227 CheckForNullPointerDereference(*this, LHSExpr);
13228
13229 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13230 if (CompoundType.isNull()) {
13231 // C++2a [expr.ass]p5:
13232 // A simple-assignment whose left operand is of a volatile-qualified
13233 // type is deprecated unless the assignment is either a discarded-value
13234 // expression or an unevaluated operand
13235 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13236 } else {
13237 // C++2a [expr.ass]p6:
13238 // [Compound-assignment] expressions are deprecated if E1 has
13239 // volatile-qualified type
13240 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13241 }
13242 }
13243
13244 // C99 6.5.16p3: The type of an assignment expression is the type of the
13245 // left operand unless the left operand has qualified type, in which case
13246 // it is the unqualified version of the type of the left operand.
13247 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13248 // is converted to the type of the assignment expression (above).
13249 // C++ 5.17p1: the type of the assignment expression is that of its left
13250 // operand.
13251 return (getLangOpts().CPlusPlus
13252 ? LHSType : LHSType.getUnqualifiedType());
13253}
13254
13255// Only ignore explicit casts to void.
13256static bool IgnoreCommaOperand(const Expr *E) {
13257 E = E->IgnoreParens();
13258
13259 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13260 if (CE->getCastKind() == CK_ToVoid) {
13261 return true;
13262 }
13263
13264 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13265 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13266 CE->getSubExpr()->getType()->isDependentType()) {
13267 return true;
13268 }
13269 }
13270
13271 return false;
13272}
13273
13274// Look for instances where it is likely the comma operator is confused with
13275// another operator. There is an explicit list of acceptable expressions for
13276// the left hand side of the comma operator, otherwise emit a warning.
13277void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13278 // No warnings in macros
13279 if (Loc.isMacroID())
13280 return;
13281
13282 // Don't warn in template instantiations.
13283 if (inTemplateInstantiation())
13284 return;
13285
13286 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13287 // instead, skip more than needed, then call back into here with the
13288 // CommaVisitor in SemaStmt.cpp.
13289 // The listed locations are the initialization and increment portions
13290 // of a for loop. The additional checks are on the condition of
13291 // if statements, do/while loops, and for loops.
13292 // Differences in scope flags for C89 mode requires the extra logic.
13293 const unsigned ForIncrementFlags =
13294 getLangOpts().C99 || getLangOpts().CPlusPlus
13295 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13296 : Scope::ContinueScope | Scope::BreakScope;
13297 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13298 const unsigned ScopeFlags = getCurScope()->getFlags();
13299 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13300 (ScopeFlags & ForInitFlags) == ForInitFlags)
13301 return;
13302
13303 // If there are multiple comma operators used together, get the RHS of the
13304 // of the comma operator as the LHS.
13305 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13306 if (BO->getOpcode() != BO_Comma)
13307 break;
13308 LHS = BO->getRHS();
13309 }
13310
13311 // Only allow some expressions on LHS to not warn.
13312 if (IgnoreCommaOperand(LHS))
13313 return;
13314
13315 Diag(Loc, diag::warn_comma_operator);
13316 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13317 << LHS->getSourceRange()
13318 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13319 LangOpts.CPlusPlus ? "static_cast<void>("
13320 : "(void)(")
13321 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13322 ")");
13323}
13324
13325// C99 6.5.17
13326static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13327 SourceLocation Loc) {
13328 LHS = S.CheckPlaceholderExpr(LHS.get());
13329 RHS = S.CheckPlaceholderExpr(RHS.get());
13330 if (LHS.isInvalid() || RHS.isInvalid())
13331 return QualType();
13332
13333 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13334 // operands, but not unary promotions.
13335 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13336
13337 // So we treat the LHS as a ignored value, and in C++ we allow the
13338 // containing site to determine what should be done with the RHS.
13339 LHS = S.IgnoredValueConversions(LHS.get());
13340 if (LHS.isInvalid())
13341 return QualType();
13342
13343 S.DiagnoseUnusedExprResult(LHS.get());
13344
13345 if (!S.getLangOpts().CPlusPlus) {
13346 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13347 if (RHS.isInvalid())
13348 return QualType();
13349 if (!RHS.get()->getType()->isVoidType())
13350 S.RequireCompleteType(Loc, RHS.get()->getType(),
13351 diag::err_incomplete_type);
13352 }
13353
13354 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13355 S.DiagnoseCommaOperator(LHS.get(), Loc);
13356
13357 return RHS.get()->getType();
13358}
13359
13360/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13361/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13362static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13363 ExprValueKind &VK,
13364 ExprObjectKind &OK,
13365 SourceLocation OpLoc,
13366 bool IsInc, bool IsPrefix) {
13367 if (Op->isTypeDependent())
13368 return S.Context.DependentTy;
13369
13370 QualType ResType = Op->getType();
13371 // Atomic types can be used for increment / decrement where the non-atomic
13372 // versions can, so ignore the _Atomic() specifier for the purpose of
13373 // checking.
13374 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13375 ResType = ResAtomicType->getValueType();
13376
13377 assert(!ResType.isNull() && "no type for increment/decrement expression")((void)0);
13378
13379 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13380 // Decrement of bool is not allowed.
13381 if (!IsInc) {
13382 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13383 return QualType();
13384 }
13385 // Increment of bool sets it to true, but is deprecated.
13386 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13387 : diag::warn_increment_bool)
13388 << Op->getSourceRange();
13389 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13390 // Error on enum increments and decrements in C++ mode
13391 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13392 return QualType();
13393 } else if (ResType->isRealType()) {
13394 // OK!
13395 } else if (ResType->isPointerType()) {
13396 // C99 6.5.2.4p2, 6.5.6p2
13397 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13398 return QualType();
13399 } else if (ResType->isObjCObjectPointerType()) {
13400 // On modern runtimes, ObjC pointer arithmetic is forbidden.
13401 // Otherwise, we just need a complete type.
13402 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13403 checkArithmeticOnObjCPointer(S, OpLoc, Op))
13404 return QualType();
13405 } else if (ResType->isAnyComplexType()) {
13406 // C99 does not support ++/-- on complex types, we allow as an extension.
13407 S.Diag(OpLoc, diag::ext_integer_increment_complex)
13408 << ResType << Op->getSourceRange();
13409 } else if (ResType->isPlaceholderType()) {
13410 ExprResult PR = S.CheckPlaceholderExpr(Op);
13411 if (PR.isInvalid()) return QualType();
13412 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13413 IsInc, IsPrefix);
13414 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13415 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13416 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13417 (ResType->castAs<VectorType>()->getVectorKind() !=
13418 VectorType::AltiVecBool)) {
13419 // The z vector extensions allow ++ and -- for non-bool vectors.
13420 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13421 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13422 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13423 } else {
13424 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13425 << ResType << int(IsInc) << Op->getSourceRange();
13426 return QualType();
13427 }
13428 // At this point, we know we have a real, complex or pointer type.
13429 // Now make sure the operand is a modifiable lvalue.
13430 if (CheckForModifiableLvalue(Op, OpLoc, S))
13431 return QualType();
13432 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13433 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13434 // An operand with volatile-qualified type is deprecated
13435 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13436 << IsInc << ResType;
13437 }
13438 // In C++, a prefix increment is the same type as the operand. Otherwise
13439 // (in C or with postfix), the increment is the unqualified type of the
13440 // operand.
13441 if (IsPrefix && S.getLangOpts().CPlusPlus) {
13442 VK = VK_LValue;
13443 OK = Op->getObjectKind();
13444 return ResType;
13445 } else {
13446 VK = VK_PRValue;
13447 return ResType.getUnqualifiedType();
13448 }
13449}
13450
13451
13452/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13453/// This routine allows us to typecheck complex/recursive expressions
13454/// where the declaration is needed for type checking. We only need to
13455/// handle cases when the expression references a function designator
13456/// or is an lvalue. Here are some examples:
13457/// - &(x) => x
13458/// - &*****f => f for f a function designator.
13459/// - &s.xx => s
13460/// - &s.zz[1].yy -> s, if zz is an array
13461/// - *(x + 1) -> x, if x is an array
13462/// - &"123"[2] -> 0
13463/// - & __real__ x -> x
13464///
13465/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13466/// members.
13467static ValueDecl *getPrimaryDecl(Expr *E) {
13468 switch (E->getStmtClass()) {
13469 case Stmt::DeclRefExprClass:
13470 return cast<DeclRefExpr>(E)->getDecl();
13471 case Stmt::MemberExprClass:
13472 // If this is an arrow operator, the address is an offset from
13473 // the base's value, so the object the base refers to is
13474 // irrelevant.
13475 if (cast<MemberExpr>(E)->isArrow())
13476 return nullptr;
13477 // Otherwise, the expression refers to a part of the base
13478 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13479 case Stmt::ArraySubscriptExprClass: {
13480 // FIXME: This code shouldn't be necessary! We should catch the implicit
13481 // promotion of register arrays earlier.
13482 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13483 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13484 if (ICE->getSubExpr()->getType()->isArrayType())
13485 return getPrimaryDecl(ICE->getSubExpr());
13486 }
13487 return nullptr;
13488 }
13489 case Stmt::UnaryOperatorClass: {
13490 UnaryOperator *UO = cast<UnaryOperator>(E);
13491
13492 switch(UO->getOpcode()) {
13493 case UO_Real:
13494 case UO_Imag:
13495 case UO_Extension:
13496 return getPrimaryDecl(UO->getSubExpr());
13497 default:
13498 return nullptr;
13499 }
13500 }
13501 case Stmt::ParenExprClass:
13502 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13503 case Stmt::ImplicitCastExprClass:
13504 // If the result of an implicit cast is an l-value, we care about
13505 // the sub-expression; otherwise, the result here doesn't matter.
13506 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13507 case Stmt::CXXUuidofExprClass:
13508 return cast<CXXUuidofExpr>(E)->getGuidDecl();
13509 default:
13510 return nullptr;
13511 }
13512}
13513
13514namespace {
13515enum {
13516 AO_Bit_Field = 0,
13517 AO_Vector_Element = 1,
13518 AO_Property_Expansion = 2,
13519 AO_Register_Variable = 3,
13520 AO_Matrix_Element = 4,
13521 AO_No_Error = 5
13522};
13523}
13524/// Diagnose invalid operand for address of operations.
13525///
13526/// \param Type The type of operand which cannot have its address taken.
13527static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13528 Expr *E, unsigned Type) {
13529 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13530}
13531
13532/// CheckAddressOfOperand - The operand of & must be either a function
13533/// designator or an lvalue designating an object. If it is an lvalue, the
13534/// object cannot be declared with storage class register or be a bit field.
13535/// Note: The usual conversions are *not* applied to the operand of the &
13536/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13537/// In C++, the operand might be an overloaded function name, in which case
13538/// we allow the '&' but retain the overloaded-function type.
13539QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13540 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13541 if (PTy->getKind() == BuiltinType::Overload) {
13542 Expr *E = OrigOp.get()->IgnoreParens();
13543 if (!isa<OverloadExpr>(E)) {
13544 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)((void)0);
13545 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13546 << OrigOp.get()->getSourceRange();
13547 return QualType();
13548 }
13549
13550 OverloadExpr *Ovl = cast<OverloadExpr>(E);
13551 if (isa<UnresolvedMemberExpr>(Ovl))
13552 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13553 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13554 << OrigOp.get()->getSourceRange();
13555 return QualType();
13556 }
13557
13558 return Context.OverloadTy;
13559 }
13560
13561 if (PTy->getKind() == BuiltinType::UnknownAny)
13562 return Context.UnknownAnyTy;
13563
13564 if (PTy->getKind() == BuiltinType::BoundMember) {
13565 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13566 << OrigOp.get()->getSourceRange();
13567 return QualType();
13568 }
13569
13570 OrigOp = CheckPlaceholderExpr(OrigOp.get());
13571 if (OrigOp.isInvalid()) return QualType();
13572 }
13573
13574 if (OrigOp.get()->isTypeDependent())
13575 return Context.DependentTy;
13576
13577 assert(!OrigOp.get()->getType()->isPlaceholderType())((void)0);
13578
13579 // Make sure to ignore parentheses in subsequent checks
13580 Expr *op = OrigOp.get()->IgnoreParens();
13581
13582 // In OpenCL captures for blocks called as lambda functions
13583 // are located in the private address space. Blocks used in
13584 // enqueue_kernel can be located in a different address space
13585 // depending on a vendor implementation. Thus preventing
13586 // taking an address of the capture to avoid invalid AS casts.
13587 if (LangOpts.OpenCL) {
13588 auto* VarRef = dyn_cast<DeclRefExpr>(op);
13589 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13590 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13591 return QualType();
13592 }
13593 }
13594
13595 if (getLangOpts().C99) {
13596 // Implement C99-only parts of addressof rules.
13597 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13598 if (uOp->getOpcode() == UO_Deref)
13599 // Per C99 6.5.3.2, the address of a deref always returns a valid result
13600 // (assuming the deref expression is valid).
13601 return uOp->getSubExpr()->getType();
13602 }
13603 // Technically, there should be a check for array subscript
13604 // expressions here, but the result of one is always an lvalue anyway.
13605 }
13606 ValueDecl *dcl = getPrimaryDecl(op);
13607
13608 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13609 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13610 op->getBeginLoc()))
13611 return QualType();
13612
13613 Expr::LValueClassification lval = op->ClassifyLValue(Context);
13614 unsigned AddressOfError = AO_No_Error;
13615
13616 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13617 bool sfinae = (bool)isSFINAEContext();
13618 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13619 : diag::ext_typecheck_addrof_temporary)
13620 << op->getType() << op->getSourceRange();
13621 if (sfinae)
13622 return QualType();
13623 // Materialize the temporary as an lvalue so that we can take its address.
13624 OrigOp = op =
13625 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13626 } else if (isa<ObjCSelectorExpr>(op)) {
13627 return Context.getPointerType(op->getType());
13628 } else if (lval == Expr::LV_MemberFunction) {
13629 // If it's an instance method, make a member pointer.
13630 // The expression must have exactly the form &A::foo.
13631
13632 // If the underlying expression isn't a decl ref, give up.
13633 if (!isa<DeclRefExpr>(op)) {
13634 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13635 << OrigOp.get()->getSourceRange();
13636 return QualType();
13637 }
13638 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13639 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13640
13641 // The id-expression was parenthesized.
13642 if (OrigOp.get() != DRE) {
13643 Diag(OpLoc, diag::err_parens_pointer_member_function)
13644 << OrigOp.get()->getSourceRange();
13645
13646 // The method was named without a qualifier.
13647 } else if (!DRE->getQualifier()) {
13648 if (MD->getParent()->getName().empty())
13649 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13650 << op->getSourceRange();
13651 else {
13652 SmallString<32> Str;
13653 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13654 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13655 << op->getSourceRange()
13656 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13657 }
13658 }
13659
13660 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13661 if (isa<CXXDestructorDecl>(MD))
13662 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13663
13664 QualType MPTy = Context.getMemberPointerType(
13665 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13666 // Under the MS ABI, lock down the inheritance model now.
13667 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13668 (void)isCompleteType(OpLoc, MPTy);
13669 return MPTy;
13670 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13671 // C99 6.5.3.2p1
13672 // The operand must be either an l-value or a function designator
13673 if (!op->getType()->isFunctionType()) {
13674 // Use a special diagnostic for loads from property references.
13675 if (isa<PseudoObjectExpr>(op)) {
13676 AddressOfError = AO_Property_Expansion;
13677 } else {
13678 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13679 << op->getType() << op->getSourceRange();
13680 return QualType();
13681 }
13682 }
13683 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13684 // The operand cannot be a bit-field
13685 AddressOfError = AO_Bit_Field;
13686 } else if (op->getObjectKind() == OK_VectorComponent) {
13687 // The operand cannot be an element of a vector
13688 AddressOfError = AO_Vector_Element;
13689 } else if (op->getObjectKind() == OK_MatrixComponent) {
13690 // The operand cannot be an element of a matrix.
13691 AddressOfError = AO_Matrix_Element;
13692 } else if (dcl) { // C99 6.5.3.2p1
13693 // We have an lvalue with a decl. Make sure the decl is not declared
13694 // with the register storage-class specifier.
13695 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13696 // in C++ it is not error to take address of a register
13697 // variable (c++03 7.1.1P3)
13698 if (vd->getStorageClass() == SC_Register &&
13699 !getLangOpts().CPlusPlus) {
13700 AddressOfError = AO_Register_Variable;
13701 }
13702 } else if (isa<MSPropertyDecl>(dcl)) {
13703 AddressOfError = AO_Property_Expansion;
13704 } else if (isa<FunctionTemplateDecl>(dcl)) {
13705 return Context.OverloadTy;
13706 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13707 // Okay: we can take the address of a field.
13708 // Could be a pointer to member, though, if there is an explicit
13709 // scope qualifier for the class.
13710 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13711 DeclContext *Ctx = dcl->getDeclContext();
13712 if (Ctx && Ctx->isRecord()) {
13713 if (dcl->getType()->isReferenceType()) {
13714 Diag(OpLoc,
13715 diag::err_cannot_form_pointer_to_member_of_reference_type)
13716 << dcl->getDeclName() << dcl->getType();
13717 return QualType();
13718 }
13719
13720 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13721 Ctx = Ctx->getParent();
13722
13723 QualType MPTy = Context.getMemberPointerType(
13724 op->getType(),
13725 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13726 // Under the MS ABI, lock down the inheritance model now.
13727 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13728 (void)isCompleteType(OpLoc, MPTy);
13729 return MPTy;
13730 }
13731 }
13732 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13733 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13734 llvm_unreachable("Unknown/unexpected decl type")__builtin_unreachable();
13735 }
13736
13737 if (AddressOfError != AO_No_Error) {
13738 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13739 return QualType();
13740 }
13741
13742 if (lval == Expr::LV_IncompleteVoidType) {
13743 // Taking the address of a void variable is technically illegal, but we
13744 // allow it in cases which are otherwise valid.
13745 // Example: "extern void x; void* y = &x;".
13746 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13747 }
13748
13749 // If the operand has type "type", the result has type "pointer to type".
13750 if (op->getType()->isObjCObjectType())
13751 return Context.getObjCObjectPointerType(op->getType());
13752
13753 CheckAddressOfPackedMember(op);
13754
13755 return Context.getPointerType(op->getType());
13756}
13757
13758static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13759 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13760 if (!DRE)
13761 return;
13762 const Decl *D = DRE->getDecl();
13763 if (!D)
13764 return;
13765 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13766 if (!Param)
13767 return;
13768 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13769 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13770 return;
13771 if (FunctionScopeInfo *FD = S.getCurFunction())
13772 if (!FD->ModifiedNonNullParams.count(Param))
13773 FD->ModifiedNonNullParams.insert(Param);
13774}
13775
13776/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13777static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13778 SourceLocation OpLoc) {
13779 if (Op->isTypeDependent())
13780 return S.Context.DependentTy;
13781
13782 ExprResult ConvResult = S.UsualUnaryConversions(Op);
13783 if (ConvResult.isInvalid())
13784 return QualType();
13785 Op = ConvResult.get();
13786 QualType OpTy = Op->getType();
13787 QualType Result;
13788
13789 if (isa<CXXReinterpretCastExpr>(Op)) {
13790 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13791 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13792 Op->getSourceRange());
13793 }
13794
13795 if (const PointerType *PT = OpTy->getAs<PointerType>())
13796 {
13797 Result = PT->getPointeeType();
13798 }
13799 else if (const ObjCObjectPointerType *OPT =
13800 OpTy->getAs<ObjCObjectPointerType>())
13801 Result = OPT->getPointeeType();
13802 else {
13803 ExprResult PR = S.CheckPlaceholderExpr(Op);
13804 if (PR.isInvalid()) return QualType();
13805 if (PR.get() != Op)
13806 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13807 }
13808
13809 if (Result.isNull()) {
13810 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13811 << OpTy << Op->getSourceRange();
13812 return QualType();
13813 }
13814
13815 // Note that per both C89 and C99, indirection is always legal, even if Result
13816 // is an incomplete type or void. It would be possible to warn about
13817 // dereferencing a void pointer, but it's completely well-defined, and such a
13818 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13819 // for pointers to 'void' but is fine for any other pointer type:
13820 //
13821 // C++ [expr.unary.op]p1:
13822 // [...] the expression to which [the unary * operator] is applied shall
13823 // be a pointer to an object type, or a pointer to a function type
13824 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13825 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13826 << OpTy << Op->getSourceRange();
13827
13828 // Dereferences are usually l-values...
13829 VK = VK_LValue;
13830
13831 // ...except that certain expressions are never l-values in C.
13832 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13833 VK = VK_PRValue;
13834
13835 return Result;
13836}
13837
13838BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13839 BinaryOperatorKind Opc;
13840 switch (Kind) {
13841 default: llvm_unreachable("Unknown binop!")__builtin_unreachable();
13842 case tok::periodstar: Opc = BO_PtrMemD; break;
13843 case tok::arrowstar: Opc = BO_PtrMemI; break;
13844 case tok::star: Opc = BO_Mul; break;
13845 case tok::slash: Opc = BO_Div; break;
13846 case tok::percent: Opc = BO_Rem; break;
13847 case tok::plus: Opc = BO_Add; break;
13848 case tok::minus: Opc = BO_Sub; break;
13849 case tok::lessless: Opc = BO_Shl; break;
13850 case tok::greatergreater: Opc = BO_Shr; break;
13851 case tok::lessequal: Opc = BO_LE; break;
13852 case tok::less: Opc = BO_LT; break;
13853 case tok::greaterequal: Opc = BO_GE; break;
13854 case tok::greater: Opc = BO_GT; break;
13855 case tok::exclaimequal: Opc = BO_NE; break;
13856 case tok::equalequal: Opc = BO_EQ; break;
13857 case tok::spaceship: Opc = BO_Cmp; break;
13858 case tok::amp: Opc = BO_And; break;
13859 case tok::caret: Opc = BO_Xor; break;
13860 case tok::pipe: Opc = BO_Or; break;
13861 case tok::ampamp: Opc = BO_LAnd; break;
13862 case tok::pipepipe: Opc = BO_LOr; break;
13863 case tok::equal: Opc = BO_Assign; break;
13864 case tok::starequal: Opc = BO_MulAssign; break;
13865 case tok::slashequal: Opc = BO_DivAssign; break;
13866 case tok::percentequal: Opc = BO_RemAssign; break;
13867 case tok::plusequal: Opc = BO_AddAssign; break;
13868 case tok::minusequal: Opc = BO_SubAssign; break;
13869 case tok::lesslessequal: Opc = BO_ShlAssign; break;
13870 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
13871 case tok::ampequal: Opc = BO_AndAssign; break;
13872 case tok::caretequal: Opc = BO_XorAssign; break;
13873 case tok::pipeequal: Opc = BO_OrAssign; break;
13874 case tok::comma: Opc = BO_Comma; break;
13875 }
13876 return Opc;
13877}
13878
13879static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13880 tok::TokenKind Kind) {
13881 UnaryOperatorKind Opc;
13882 switch (Kind) {
13883 default: llvm_unreachable("Unknown unary op!")__builtin_unreachable();
13884 case tok::plusplus: Opc = UO_PreInc; break;
13885 case tok::minusminus: Opc = UO_PreDec; break;
13886 case tok::amp: Opc = UO_AddrOf; break;
13887 case tok::star: Opc = UO_Deref; break;
13888 case tok::plus: Opc = UO_Plus; break;
13889 case tok::minus: Opc = UO_Minus; break;
13890 case tok::tilde: Opc = UO_Not; break;
13891 case tok::exclaim: Opc = UO_LNot; break;
13892 case tok::kw___real: Opc = UO_Real; break;
13893 case tok::kw___imag: Opc = UO_Imag; break;
13894 case tok::kw___extension__: Opc = UO_Extension; break;
13895 }
13896 return Opc;
13897}
13898
13899/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13900/// This warning suppressed in the event of macro expansions.
13901static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13902 SourceLocation OpLoc, bool IsBuiltin) {
13903 if (S.inTemplateInstantiation())
13904 return;
13905 if (S.isUnevaluatedContext())
13906 return;
13907 if (OpLoc.isInvalid() || OpLoc.isMacroID())
13908 return;
13909 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13910 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13911 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13912 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13913 if (!LHSDeclRef || !RHSDeclRef ||
13914 LHSDeclRef->getLocation().isMacroID() ||
13915 RHSDeclRef->getLocation().isMacroID())
13916 return;
13917 const ValueDecl *LHSDecl =
13918 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13919 const ValueDecl *RHSDecl =
13920 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13921 if (LHSDecl != RHSDecl)
13922 return;
13923 if (LHSDecl->getType().isVolatileQualified())
13924 return;
13925 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13926 if (RefTy->getPointeeType().isVolatileQualified())
13927 return;
13928
13929 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13930 : diag::warn_self_assignment_overloaded)
13931 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13932 << RHSExpr->getSourceRange();
13933}
13934
13935/// Check if a bitwise-& is performed on an Objective-C pointer. This
13936/// is usually indicative of introspection within the Objective-C pointer.
13937static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13938 SourceLocation OpLoc) {
13939 if (!S.getLangOpts().ObjC)
13940 return;
13941
13942 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13943 const Expr *LHS = L.get();
13944 const Expr *RHS = R.get();
13945
13946 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13947 ObjCPointerExpr = LHS;
13948 OtherExpr = RHS;
13949 }
13950 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13951 ObjCPointerExpr = RHS;
13952 OtherExpr = LHS;
13953 }
13954
13955 // This warning is deliberately made very specific to reduce false
13956 // positives with logic that uses '&' for hashing. This logic mainly
13957 // looks for code trying to introspect into tagged pointers, which
13958 // code should generally never do.
13959 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13960 unsigned Diag = diag::warn_objc_pointer_masking;
13961 // Determine if we are introspecting the result of performSelectorXXX.
13962 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13963 // Special case messages to -performSelector and friends, which
13964 // can return non-pointer values boxed in a pointer value.
13965 // Some clients may wish to silence warnings in this subcase.
13966 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13967 Selector S = ME->getSelector();
13968 StringRef SelArg0 = S.getNameForSlot(0);
13969 if (SelArg0.startswith("performSelector"))
13970 Diag = diag::warn_objc_pointer_masking_performSelector;
13971 }
13972
13973 S.Diag(OpLoc, Diag)
13974 << ObjCPointerExpr->getSourceRange();
13975 }
13976}
13977
13978static NamedDecl *getDeclFromExpr(Expr *E) {
13979 if (!E)
13980 return nullptr;
13981 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13982 return DRE->getDecl();
13983 if (auto *ME = dyn_cast<MemberExpr>(E))
13984 return ME->getMemberDecl();
13985 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13986 return IRE->getDecl();
13987 return nullptr;
13988}
13989
13990// This helper function promotes a binary operator's operands (which are of a
13991// half vector type) to a vector of floats and then truncates the result to
13992// a vector of either half or short.
13993static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13994 BinaryOperatorKind Opc, QualType ResultTy,
13995 ExprValueKind VK, ExprObjectKind OK,
13996 bool IsCompAssign, SourceLocation OpLoc,
13997 FPOptionsOverride FPFeatures) {
13998 auto &Context = S.getASTContext();
13999 assert((isVector(ResultTy, Context.HalfTy) ||((void)0)
14000 isVector(ResultTy, Context.ShortTy)) &&((void)0)
14001 "Result must be a vector of half or short")((void)0);
14002 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&((void)0)
14003 isVector(RHS.get()->getType(), Context.HalfTy) &&((void)0)
14004 "both operands expected to be a half vector")((void)0);
14005
14006 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14007 QualType BinOpResTy = RHS.get()->getType();
14008
14009 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14010 // change BinOpResTy to a vector of ints.
14011 if (isVector(ResultTy, Context.ShortTy))
14012 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14013
14014 if (IsCompAssign)
14015 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14016 ResultTy, VK, OK, OpLoc, FPFeatures,
14017 BinOpResTy, BinOpResTy);
14018
14019 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14020 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14021 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14022 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14023}
14024
14025static std::pair<ExprResult, ExprResult>
14026CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14027 Expr *RHSExpr) {
14028 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14029 if (!S.Context.isDependenceAllowed()) {
14030 // C cannot handle TypoExpr nodes on either side of a binop because it
14031 // doesn't handle dependent types properly, so make sure any TypoExprs have
14032 // been dealt with before checking the operands.
14033 LHS = S.CorrectDelayedTyposInExpr(LHS);
14034 RHS = S.CorrectDelayedTyposInExpr(
14035 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14036 [Opc, LHS](Expr *E) {
14037 if (Opc != BO_Assign)
14038 return ExprResult(E);
14039 // Avoid correcting the RHS to the same Expr as the LHS.
14040 Decl *D = getDeclFromExpr(E);
14041 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14042 });
14043 }
14044 return std::make_pair(LHS, RHS);
14045}
14046
14047/// Returns true if conversion between vectors of halfs and vectors of floats
14048/// is needed.
14049static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14050 Expr *E0, Expr *E1 = nullptr) {
14051 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14052 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14053 return false;
14054
14055 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14056 QualType Ty = E->IgnoreImplicit()->getType();
14057
14058 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14059 // to vectors of floats. Although the element type of the vectors is __fp16,
14060 // the vectors shouldn't be treated as storage-only types. See the
14061 // discussion here: https://reviews.llvm.org/rG825235c140e7
14062 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14063 if (VT->getVectorKind() == VectorType::NeonVector)
14064 return false;
14065 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14066 }
14067 return false;
14068 };
14069
14070 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14071}
14072
14073/// CreateBuiltinBinOp - Creates a new built-in binary operation with
14074/// operator @p Opc at location @c TokLoc. This routine only supports
14075/// built-in operations; ActOnBinOp handles overloaded operators.
14076ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14077 BinaryOperatorKind Opc,
14078 Expr *LHSExpr, Expr *RHSExpr) {
14079 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14080 // The syntax only allows initializer lists on the RHS of assignment,
14081 // so we don't need to worry about accepting invalid code for
14082 // non-assignment operators.
14083 // C++11 5.17p9:
14084 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14085 // of x = {} is x = T().
14086 InitializationKind Kind = InitializationKind::CreateDirectList(
14087 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14088 InitializedEntity Entity =
14089 InitializedEntity::InitializeTemporary(LHSExpr->getType());
14090 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14091 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14092 if (Init.isInvalid())
14093 return Init;
14094 RHSExpr = Init.get();
14095 }
14096
14097 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14098 QualType ResultTy; // Result type of the binary operator.
14099 // The following two variables are used for compound assignment operators
14100 QualType CompLHSTy; // Type of LHS after promotions for computation
14101 QualType CompResultTy; // Type of computation result
14102 ExprValueKind VK = VK_PRValue;
14103 ExprObjectKind OK = OK_Ordinary;
14104 bool ConvertHalfVec = false;
14105
14106 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14107 if (!LHS.isUsable() || !RHS.isUsable())
14108 return ExprError();
14109
14110 if (getLangOpts().OpenCL) {
14111 QualType LHSTy = LHSExpr->getType();
14112 QualType RHSTy = RHSExpr->getType();
14113 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14114 // the ATOMIC_VAR_INIT macro.
14115 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14116 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14117 if (BO_Assign == Opc)
14118 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14119 else
14120 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14121 return ExprError();
14122 }
14123
14124 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14125 // only with a builtin functions and therefore should be disallowed here.
14126 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14127 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14128 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14129 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14130 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14131 return ExprError();
14132 }
14133 }
14134
14135 switch (Opc) {
14136 case BO_Assign:
14137 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14138 if (getLangOpts().CPlusPlus &&
14139 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14140 VK = LHS.get()->getValueKind();
14141 OK = LHS.get()->getObjectKind();
14142 }
14143 if (!ResultTy.isNull()) {
14144 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14145 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14146
14147 // Avoid copying a block to the heap if the block is assigned to a local
14148 // auto variable that is declared in the same scope as the block. This
14149 // optimization is unsafe if the local variable is declared in an outer
14150 // scope. For example:
14151 //
14152 // BlockTy b;
14153 // {
14154 // b = ^{...};
14155 // }
14156 // // It is unsafe to invoke the block here if it wasn't copied to the
14157 // // heap.
14158 // b();
14159
14160 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14161 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14162 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14163 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14164 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14165
14166 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14167 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14168 NTCUC_Assignment, NTCUK_Copy);
14169 }
14170 RecordModifiableNonNullParam(*this, LHS.get());
14171 break;
14172 case BO_PtrMemD:
14173 case BO_PtrMemI:
14174 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14175 Opc == BO_PtrMemI);
14176 break;
14177 case BO_Mul:
14178 case BO_Div:
14179 ConvertHalfVec = true;
14180 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14181 Opc == BO_Div);
14182 break;
14183 case BO_Rem:
14184 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14185 break;
14186 case BO_Add:
14187 ConvertHalfVec = true;
14188 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14189 break;
14190 case BO_Sub:
14191 ConvertHalfVec = true;
14192 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14193 break;
14194 case BO_Shl:
14195 case BO_Shr:
14196 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14197 break;
14198 case BO_LE:
14199 case BO_LT:
14200 case BO_GE:
14201 case BO_GT:
14202 ConvertHalfVec = true;
14203 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14204 break;
14205 case BO_EQ:
14206 case BO_NE:
14207 ConvertHalfVec = true;
14208 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14209 break;
14210 case BO_Cmp:
14211 ConvertHalfVec = true;
14212 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14213 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())((void)0);
14214 break;
14215 case BO_And:
14216 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14217 LLVM_FALLTHROUGH[[gnu::fallthrough]];
14218 case BO_Xor:
14219 case BO_Or:
14220 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14221 break;
14222 case BO_LAnd:
14223 case BO_LOr:
14224 ConvertHalfVec = true;
14225 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14226 break;
14227 case BO_MulAssign:
14228 case BO_DivAssign:
14229 ConvertHalfVec = true;
14230 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14231 Opc == BO_DivAssign);
14232 CompLHSTy = CompResultTy;
14233 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14234 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14235 break;
14236 case BO_RemAssign:
14237 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14238 CompLHSTy = CompResultTy;
14239 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14240 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14241 break;
14242 case BO_AddAssign:
14243 ConvertHalfVec = true;
14244 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14245 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14246 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14247 break;
14248 case BO_SubAssign:
14249 ConvertHalfVec = true;
14250 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14251 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14252 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14253 break;
14254 case BO_ShlAssign:
14255 case BO_ShrAssign:
14256 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14257 CompLHSTy = CompResultTy;
14258 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14259 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14260 break;
14261 case BO_AndAssign:
14262 case BO_OrAssign: // fallthrough
14263 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14264 LLVM_FALLTHROUGH[[gnu::fallthrough]];
14265 case BO_XorAssign:
14266 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14267 CompLHSTy = CompResultTy;
14268 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14269 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14270 break;
14271 case BO_Comma:
14272 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14273 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14274 VK = RHS.get()->getValueKind();
14275 OK = RHS.get()->getObjectKind();
14276 }
14277 break;
14278 }
14279 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14280 return ExprError();
14281
14282 // Some of the binary operations require promoting operands of half vector to
14283 // float vectors and truncating the result back to half vector. For now, we do
14284 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14285 // arm64).
14286 assert(((void)0)
14287 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==((void)0)
14288 isVector(LHS.get()->getType(), Context.HalfTy)) &&((void)0)
14289 "both sides are half vectors or neither sides are")((void)0);
14290 ConvertHalfVec =
14291 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14292
14293 // Check for array bounds violations for both sides of the BinaryOperator
14294 CheckArrayAccess(LHS.get());
14295 CheckArrayAccess(RHS.get());
14296
14297 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14298 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14299 &Context.Idents.get("object_setClass"),
14300 SourceLocation(), LookupOrdinaryName);
14301 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14302 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14303 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14304 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14305 "object_setClass(")
14306 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14307 ",")
14308 << FixItHint::CreateInsertion(RHSLocEnd, ")");
14309 }
14310 else
14311 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14312 }
14313 else if (const ObjCIvarRefExpr *OIRE =
14314 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14315 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14316
14317 // Opc is not a compound assignment if CompResultTy is null.
14318 if (CompResultTy.isNull()) {
14319 if (ConvertHalfVec)
14320 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14321 OpLoc, CurFPFeatureOverrides());
14322 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14323 VK, OK, OpLoc, CurFPFeatureOverrides());
14324 }
14325
14326 // Handle compound assignments.
14327 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14328 OK_ObjCProperty) {
14329 VK = VK_LValue;
14330 OK = LHS.get()->getObjectKind();
14331 }
14332
14333 // The LHS is not converted to the result type for fixed-point compound
14334 // assignment as the common type is computed on demand. Reset the CompLHSTy
14335 // to the LHS type we would have gotten after unary conversions.
14336 if (CompResultTy->isFixedPointType())
14337 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14338
14339 if (ConvertHalfVec)
14340 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14341 OpLoc, CurFPFeatureOverrides());
14342
14343 return CompoundAssignOperator::Create(
14344 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14345 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14346}
14347
14348/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14349/// operators are mixed in a way that suggests that the programmer forgot that
14350/// comparison operators have higher precedence. The most typical example of
14351/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14352static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14353 SourceLocation OpLoc, Expr *LHSExpr,
14354 Expr *RHSExpr) {
14355 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14356 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14357
14358 // Check that one of the sides is a comparison operator and the other isn't.
14359 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14360 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14361 if (isLeftComp == isRightComp)
14362 return;
14363
14364 // Bitwise operations are sometimes used as eager logical ops.
14365 // Don't diagnose this.
14366 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14367 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14368 if (isLeftBitwise || isRightBitwise)
14369 return;
14370
14371 SourceRange DiagRange = isLeftComp
14372 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14373 : SourceRange(OpLoc, RHSExpr->getEndLoc());
14374 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14375 SourceRange ParensRange =
14376 isLeftComp
14377 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14378 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14379
14380 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14381 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14382 SuggestParentheses(Self, OpLoc,
14383 Self.PDiag(diag::note_precedence_silence) << OpStr,
14384 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14385 SuggestParentheses(Self, OpLoc,
14386 Self.PDiag(diag::note_precedence_bitwise_first)
14387 << BinaryOperator::getOpcodeStr(Opc),
14388 ParensRange);
14389}
14390
14391/// It accepts a '&&' expr that is inside a '||' one.
14392/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14393/// in parentheses.
14394static void
14395EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14396 BinaryOperator *Bop) {
14397 assert(Bop->getOpcode() == BO_LAnd)((void)0);
14398 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14399 << Bop->getSourceRange() << OpLoc;
14400 SuggestParentheses(Self, Bop->getOperatorLoc(),
14401 Self.PDiag(diag::note_precedence_silence)
14402 << Bop->getOpcodeStr(),
14403 Bop->getSourceRange());
14404}
14405
14406/// Returns true if the given expression can be evaluated as a constant
14407/// 'true'.
14408static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14409 bool Res;
14410 return !E->isValueDependent() &&
14411 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14412}
14413
14414/// Returns true if the given expression can be evaluated as a constant
14415/// 'false'.
14416static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14417 bool Res;
14418 return !E->isValueDependent() &&
14419 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14420}
14421
14422/// Look for '&&' in the left hand of a '||' expr.
14423static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14424 Expr *LHSExpr, Expr *RHSExpr) {
14425 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14426 if (Bop->getOpcode() == BO_LAnd) {
14427 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14428 if (EvaluatesAsFalse(S, RHSExpr))
14429 return;
14430 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14431 if (!EvaluatesAsTrue(S, Bop->getLHS()))
14432 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14433 } else if (Bop->getOpcode() == BO_LOr) {
14434 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14435 // If it's "a || b && 1 || c" we didn't warn earlier for
14436 // "a || b && 1", but warn now.
14437 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14438 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14439 }
14440 }
14441 }
14442}
14443
14444/// Look for '&&' in the right hand of a '||' expr.
14445static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14446 Expr *LHSExpr, Expr *RHSExpr) {
14447 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14448 if (Bop->getOpcode() == BO_LAnd) {
14449 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14450 if (EvaluatesAsFalse(S, LHSExpr))
14451 return;
14452 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14453 if (!EvaluatesAsTrue(S, Bop->getRHS()))
14454 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14455 }
14456 }
14457}
14458
14459/// Look for bitwise op in the left or right hand of a bitwise op with
14460/// lower precedence and emit a diagnostic together with a fixit hint that wraps
14461/// the '&' expression in parentheses.
14462static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14463 SourceLocation OpLoc, Expr *SubExpr) {
14464 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14465 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14466 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14467 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14468 << Bop->getSourceRange() << OpLoc;
14469 SuggestParentheses(S, Bop->getOperatorLoc(),
14470 S.PDiag(diag::note_precedence_silence)
14471 << Bop->getOpcodeStr(),
14472 Bop->getSourceRange());
14473 }
14474 }
14475}
14476
14477static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14478 Expr *SubExpr, StringRef Shift) {
14479 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14480 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14481 StringRef Op = Bop->getOpcodeStr();
14482 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14483 << Bop->getSourceRange() << OpLoc << Shift << Op;
14484 SuggestParentheses(S, Bop->getOperatorLoc(),
14485 S.PDiag(diag::note_precedence_silence) << Op,
14486 Bop->getSourceRange());
14487 }
14488 }
14489}
14490
14491static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14492 Expr *LHSExpr, Expr *RHSExpr) {
14493 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14494 if (!OCE)
14495 return;
14496
14497 FunctionDecl *FD = OCE->getDirectCallee();
14498 if (!FD || !FD->isOverloadedOperator())
14499 return;
14500
14501 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14502 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14503 return;
14504
14505 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14506 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14507 << (Kind == OO_LessLess);
14508 SuggestParentheses(S, OCE->getOperatorLoc(),
14509 S.PDiag(diag::note_precedence_silence)
14510 << (Kind == OO_LessLess ? "<<" : ">>"),
14511 OCE->getSourceRange());
14512 SuggestParentheses(
14513 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14514 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14515}
14516
14517/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14518/// precedence.
14519static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14520 SourceLocation OpLoc, Expr *LHSExpr,
14521 Expr *RHSExpr){
14522 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14523 if (BinaryOperator::isBitwiseOp(Opc))
14524 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14525
14526 // Diagnose "arg1 & arg2 | arg3"
14527 if ((Opc == BO_Or || Opc == BO_Xor) &&
14528 !OpLoc.isMacroID()/* Don't warn in macros. */) {
14529 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14530 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14531 }
14532
14533 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14534 // We don't warn for 'assert(a || b && "bad")' since this is safe.
14535 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14536 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14537 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14538 }
14539
14540 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14541 || Opc == BO_Shr) {
14542 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14543 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14544 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14545 }
14546
14547 // Warn on overloaded shift operators and comparisons, such as:
14548 // cout << 5 == 4;
14549 if (BinaryOperator::isComparisonOp(Opc))
14550 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14551}
14552
14553// Binary Operators. 'Tok' is the token for the operator.
14554ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14555 tok::TokenKind Kind,
14556 Expr *LHSExpr, Expr *RHSExpr) {
14557 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14558 assert(LHSExpr && "ActOnBinOp(): missing left expression")((void)0);
14559 assert(RHSExpr && "ActOnBinOp(): missing right expression")((void)0);
14560
14561 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14562 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14563
14564 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14565}
14566
14567void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14568 UnresolvedSetImpl &Functions) {
14569 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14570 if (OverOp != OO_None && OverOp != OO_Equal)
14571 LookupOverloadedOperatorName(OverOp, S, Functions);
14572
14573 // In C++20 onwards, we may have a second operator to look up.
14574 if (getLangOpts().CPlusPlus20) {
14575 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14576 LookupOverloadedOperatorName(ExtraOp, S, Functions);
14577 }
14578}
14579
14580/// Build an overloaded binary operator expression in the given scope.
14581static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14582 BinaryOperatorKind Opc,
14583 Expr *LHS, Expr *RHS) {
14584 switch (Opc) {
14585 case BO_Assign:
14586 case BO_DivAssign:
14587 case BO_RemAssign:
14588 case BO_SubAssign:
14589 case BO_AndAssign:
14590 case BO_OrAssign:
14591 case BO_XorAssign:
14592 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14593 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14594 break;
14595 default:
14596 break;
14597 }
14598
14599 // Find all of the overloaded operators visible from this point.
14600 UnresolvedSet<16> Functions;
14601 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14602
14603 // Build the (potentially-overloaded, potentially-dependent)
14604 // binary operation.
14605 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14606}
14607
14608ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14609 BinaryOperatorKind Opc,
14610 Expr *LHSExpr, Expr *RHSExpr) {
14611 ExprResult LHS, RHS;
14612 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14613 if (!LHS.isUsable() || !RHS.isUsable())
14614 return ExprError();
14615 LHSExpr = LHS.get();
14616 RHSExpr = RHS.get();
14617
14618 // We want to end up calling one of checkPseudoObjectAssignment
14619 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14620 // both expressions are overloadable or either is type-dependent),
14621 // or CreateBuiltinBinOp (in any other case). We also want to get
14622 // any placeholder types out of the way.
14623
14624 // Handle pseudo-objects in the LHS.
14625 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14626 // Assignments with a pseudo-object l-value need special analysis.
14627 if (pty->getKind() == BuiltinType::PseudoObject &&
14628 BinaryOperator::isAssignmentOp(Opc))
14629 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14630
14631 // Don't resolve overloads if the other type is overloadable.
14632 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14633 // We can't actually test that if we still have a placeholder,
14634 // though. Fortunately, none of the exceptions we see in that
14635 // code below are valid when the LHS is an overload set. Note
14636 // that an overload set can be dependently-typed, but it never
14637 // instantiates to having an overloadable type.
14638 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14639 if (resolvedRHS.isInvalid()) return ExprError();
14640 RHSExpr = resolvedRHS.get();
14641
14642 if (RHSExpr->isTypeDependent() ||
14643 RHSExpr->getType()->isOverloadableType())
14644 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14645 }
14646
14647 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14648 // template, diagnose the missing 'template' keyword instead of diagnosing
14649 // an invalid use of a bound member function.
14650 //
14651 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14652 // to C++1z [over.over]/1.4, but we already checked for that case above.
14653 if (Opc == BO_LT && inTemplateInstantiation() &&
14654 (pty->getKind() == BuiltinType::BoundMember ||
14655 pty->getKind() == BuiltinType::Overload)) {
14656 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14657 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14658 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14659 return isa<FunctionTemplateDecl>(ND);
14660 })) {
14661 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14662 : OE->getNameLoc(),
14663 diag::err_template_kw_missing)
14664 << OE->getName().getAsString() << "";
14665 return ExprError();
14666 }
14667 }
14668
14669 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14670 if (LHS.isInvalid()) return ExprError();
14671 LHSExpr = LHS.get();
14672 }
14673
14674 // Handle pseudo-objects in the RHS.
14675 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14676 // An overload in the RHS can potentially be resolved by the type
14677 // being assigned to.
14678 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14679 if (getLangOpts().CPlusPlus &&
14680 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14681 LHSExpr->getType()->isOverloadableType()))
14682 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14683
14684 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14685 }
14686
14687 // Don't resolve overloads if the other type is overloadable.
14688 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14689 LHSExpr->getType()->isOverloadableType())
14690 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14691
14692 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14693 if (!resolvedRHS.isUsable()) return ExprError();
14694 RHSExpr = resolvedRHS.get();
14695 }
14696
14697 if (getLangOpts().CPlusPlus) {
14698 // If either expression is type-dependent, always build an
14699 // overloaded op.
14700 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14701 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14702
14703 // Otherwise, build an overloaded op if either expression has an
14704 // overloadable type.
14705 if (LHSExpr->getType()->isOverloadableType() ||
14706 RHSExpr->getType()->isOverloadableType())
14707 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14708 }
14709
14710 if (getLangOpts().RecoveryAST &&
14711 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14712 assert(!getLangOpts().CPlusPlus)((void)0);
14713 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&((void)0)
14714 "Should only occur in error-recovery path.")((void)0);
14715 if (BinaryOperator::isCompoundAssignmentOp(Opc))
14716 // C [6.15.16] p3:
14717 // An assignment expression has the value of the left operand after the
14718 // assignment, but is not an lvalue.
14719 return CompoundAssignOperator::Create(
14720 Context, LHSExpr, RHSExpr, Opc,
14721 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
14722 OpLoc, CurFPFeatureOverrides());
14723 QualType ResultType;
14724 switch (Opc) {
14725 case BO_Assign:
14726 ResultType = LHSExpr->getType().getUnqualifiedType();
14727 break;
14728 case BO_LT:
14729 case BO_GT:
14730 case BO_LE:
14731 case BO_GE:
14732 case BO_EQ:
14733 case BO_NE:
14734 case BO_LAnd:
14735 case BO_LOr:
14736 // These operators have a fixed result type regardless of operands.
14737 ResultType = Context.IntTy;
14738 break;
14739 case BO_Comma:
14740 ResultType = RHSExpr->getType();
14741 break;
14742 default:
14743 ResultType = Context.DependentTy;
14744 break;
14745 }
14746 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14747 VK_PRValue, OK_Ordinary, OpLoc,
14748 CurFPFeatureOverrides());
14749 }
14750
14751 // Build a built-in binary operation.
14752 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14753}
14754
14755static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14756 if (T.isNull() || T->isDependentType())
14757 return false;
14758
14759 if (!T->isPromotableIntegerType())
14760 return true;
14761
14762 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14763}
14764
14765ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14766 UnaryOperatorKind Opc,
14767 Expr *InputExpr) {
14768 ExprResult Input = InputExpr;
14769 ExprValueKind VK = VK_PRValue;
14770 ExprObjectKind OK = OK_Ordinary;
14771 QualType resultType;
14772 bool CanOverflow = false;
14773
14774 bool ConvertHalfVec = false;
14775 if (getLangOpts().OpenCL) {
14776 QualType Ty = InputExpr->getType();
14777 // The only legal unary operation for atomics is '&'.
14778 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14779 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14780 // only with a builtin functions and therefore should be disallowed here.
14781 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14782 || Ty->isBlockPointerType())) {
14783 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14784 << InputExpr->getType()
14785 << Input.get()->getSourceRange());
14786 }
14787 }
14788
14789 switch (Opc) {
14790 case UO_PreInc:
14791 case UO_PreDec:
14792 case UO_PostInc:
14793 case UO_PostDec:
14794 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14795 OpLoc,
14796 Opc == UO_PreInc ||
14797 Opc == UO_PostInc,
14798 Opc == UO_PreInc ||
14799 Opc == UO_PreDec);
14800 CanOverflow = isOverflowingIntegerType(Context, resultType);
14801 break;
14802 case UO_AddrOf:
14803 resultType = CheckAddressOfOperand(Input, OpLoc);
14804 CheckAddressOfNoDeref(InputExpr);
14805 RecordModifiableNonNullParam(*this, InputExpr);
14806 break;
14807 case UO_Deref: {
14808 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14809 if (Input.isInvalid()) return ExprError();
14810 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14811 break;
14812 }
14813 case UO_Plus:
14814 case UO_Minus:
14815 CanOverflow = Opc == UO_Minus &&
14816 isOverflowingIntegerType(Context, Input.get()->getType());
14817 Input = UsualUnaryConversions(Input.get());
14818 if (Input.isInvalid()) return ExprError();
14819 // Unary plus and minus require promoting an operand of half vector to a
14820 // float vector and truncating the result back to a half vector. For now, we
14821 // do this only when HalfArgsAndReturns is set (that is, when the target is
14822 // arm or arm64).
14823 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14824
14825 // If the operand is a half vector, promote it to a float vector.
14826 if (ConvertHalfVec)
14827 Input = convertVector(Input.get(), Context.FloatTy, *this);
14828 resultType = Input.get()->getType();
14829 if (resultType->isDependentType())
14830 break;
14831 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14832 break;
14833 else if (resultType->isVectorType() &&
14834 // The z vector extensions don't allow + or - with bool vectors.
14835 (!Context.getLangOpts().ZVector ||
14836 resultType->castAs<VectorType>()->getVectorKind() !=
14837 VectorType::AltiVecBool))
14838 break;
14839 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14840 Opc == UO_Plus &&
14841 resultType->isPointerType())
14842 break;
14843
14844 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14845 << resultType << Input.get()->getSourceRange());
14846
14847 case UO_Not: // bitwise complement
14848 Input = UsualUnaryConversions(Input.get());
14849 if (Input.isInvalid())
14850 return ExprError();
14851 resultType = Input.get()->getType();
14852 if (resultType->isDependentType())
14853 break;
14854 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14855 if (resultType->isComplexType() || resultType->isComplexIntegerType())
14856 // C99 does not support '~' for complex conjugation.
14857 Diag(OpLoc, diag::ext_integer_complement_complex)
14858 << resultType << Input.get()->getSourceRange();
14859 else if (resultType->hasIntegerRepresentation())
14860 break;
14861 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14862 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14863 // on vector float types.
14864 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14865 if (!T->isIntegerType())
14866 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14867 << resultType << Input.get()->getSourceRange());
14868 } else {
14869 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14870 << resultType << Input.get()->getSourceRange());
14871 }
14872 break;
14873
14874 case UO_LNot: // logical negation
14875 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14876 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14877 if (Input.isInvalid()) return ExprError();
14878 resultType = Input.get()->getType();
14879
14880 // Though we still have to promote half FP to float...
14881 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14882 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14883 resultType = Context.FloatTy;
14884 }
14885
14886 if (resultType->isDependentType())
14887 break;
14888 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14889 // C99 6.5.3.3p1: ok, fallthrough;
14890 if (Context.getLangOpts().CPlusPlus) {
14891 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14892 // operand contextually converted to bool.
14893 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14894 ScalarTypeToBooleanCastKind(resultType));
14895 } else if (Context.getLangOpts().OpenCL &&
14896 Context.getLangOpts().OpenCLVersion < 120) {
14897 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14898 // operate on scalar float types.
14899 if (!resultType->isIntegerType() && !resultType->isPointerType())
14900 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14901 << resultType << Input.get()->getSourceRange());
14902 }
14903 } else if (resultType->isExtVectorType()) {
14904 if (Context.getLangOpts().OpenCL &&
14905 Context.getLangOpts().OpenCLVersion < 120 &&
14906 !Context.getLangOpts().OpenCLCPlusPlus) {
14907 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14908 // operate on vector float types.
14909 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14910 if (!T->isIntegerType())
14911 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14912 << resultType << Input.get()->getSourceRange());
14913 }
14914 // Vector logical not returns the signed variant of the operand type.
14915 resultType = GetSignedVectorType(resultType);
14916 break;
14917 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14918 const VectorType *VTy = resultType->castAs<VectorType>();
14919 if (VTy->getVectorKind() != VectorType::GenericVector)
14920 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14921 << resultType << Input.get()->getSourceRange());
14922
14923 // Vector logical not returns the signed variant of the operand type.
14924 resultType = GetSignedVectorType(resultType);
14925 break;
14926 } else {
14927 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14928 << resultType << Input.get()->getSourceRange());
14929 }
14930
14931 // LNot always has type int. C99 6.5.3.3p5.
14932 // In C++, it's bool. C++ 5.3.1p8
14933 resultType = Context.getLogicalOperationType();
14934 break;
14935 case UO_Real:
14936 case UO_Imag:
14937 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14938 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14939 // complex l-values to ordinary l-values and all other values to r-values.
14940 if (Input.isInvalid()) return ExprError();
14941 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14942 if (Input.get()->isGLValue() &&
14943 Input.get()->getObjectKind() == OK_Ordinary)
14944 VK = Input.get()->getValueKind();
14945 } else if (!getLangOpts().CPlusPlus) {
14946 // In C, a volatile scalar is read by __imag. In C++, it is not.
14947 Input = DefaultLvalueConversion(Input.get());
14948 }
14949 break;
14950 case UO_Extension:
14951 resultType = Input.get()->getType();
14952 VK = Input.get()->getValueKind();
14953 OK = Input.get()->getObjectKind();
14954 break;
14955 case UO_Coawait:
14956 // It's unnecessary to represent the pass-through operator co_await in the
14957 // AST; just return the input expression instead.
14958 assert(!Input.get()->getType()->isDependentType() &&((void)0)
14959 "the co_await expression must be non-dependant before "((void)0)
14960 "building operator co_await")((void)0);
14961 return Input;
14962 }
14963 if (resultType.isNull() || Input.isInvalid())
14964 return ExprError();
14965
14966 // Check for array bounds violations in the operand of the UnaryOperator,
14967 // except for the '*' and '&' operators that have to be handled specially
14968 // by CheckArrayAccess (as there are special cases like &array[arraysize]
14969 // that are explicitly defined as valid by the standard).
14970 if (Opc != UO_AddrOf && Opc != UO_Deref)
14971 CheckArrayAccess(Input.get());
14972
14973 auto *UO =
14974 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14975 OpLoc, CanOverflow, CurFPFeatureOverrides());
14976
14977 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14978 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
14979 !isUnevaluatedContext())
14980 ExprEvalContexts.back().PossibleDerefs.insert(UO);
14981
14982 // Convert the result back to a half vector.
14983 if (ConvertHalfVec)
14984 return convertVector(UO, Context.HalfTy, *this);
14985 return UO;
14986}
14987
14988/// Determine whether the given expression is a qualified member
14989/// access expression, of a form that could be turned into a pointer to member
14990/// with the address-of operator.
14991bool Sema::isQualifiedMemberAccess(Expr *E) {
14992 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14993 if (!DRE->getQualifier())
14994 return false;
14995
14996 ValueDecl *VD = DRE->getDecl();
14997 if (!VD->isCXXClassMember())
14998 return false;
14999
15000 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15001 return true;
15002 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15003 return Method->isInstance();
15004
15005 return false;
15006 }
15007
15008 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15009 if (!ULE->getQualifier())
15010 return false;
15011
15012 for (NamedDecl *D : ULE->decls()) {
15013 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15014 if (Method->isInstance())
15015 return true;
15016 } else {
15017 // Overload set does not contain methods.
15018 break;
15019 }
15020 }
15021
15022 return false;
15023 }
15024
15025 return false;
15026}
15027
15028ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15029 UnaryOperatorKind Opc, Expr *Input) {
15030 // First things first: handle placeholders so that the
15031 // overloaded-operator check considers the right type.
15032 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15033 // Increment and decrement of pseudo-object references.
15034 if (pty->getKind() == BuiltinType::PseudoObject &&
15035 UnaryOperator::isIncrementDecrementOp(Opc))
15036 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15037
15038 // extension is always a builtin operator.
15039 if (Opc == UO_Extension)
15040 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15041
15042 // & gets special logic for several kinds of placeholder.
15043 // The builtin code knows what to do.
15044 if (Opc == UO_AddrOf &&
15045 (pty->getKind() == BuiltinType::Overload ||
15046 pty->getKind() == BuiltinType::UnknownAny ||
15047 pty->getKind() == BuiltinType::BoundMember))
15048 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15049
15050 // Anything else needs to be handled now.
15051 ExprResult Result = CheckPlaceholderExpr(Input);
15052 if (Result.isInvalid()) return ExprError();
15053 Input = Result.get();
15054 }
15055
15056 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15057 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15058 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15059 // Find all of the overloaded operators visible from this point.
15060 UnresolvedSet<16> Functions;
15061 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15062 if (S && OverOp != OO_None)
15063 LookupOverloadedOperatorName(OverOp, S, Functions);
15064
15065 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15066 }
15067
15068 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15069}
15070
15071// Unary Operators. 'Tok' is the token for the operator.
15072ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15073 tok::TokenKind Op, Expr *Input) {
15074 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15075}
15076
15077/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15078ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15079 LabelDecl *TheDecl) {
15080 TheDecl->markUsed(Context);
15081 // Create the AST node. The address of a label always has type 'void*'.
15082 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15083 Context.getPointerType(Context.VoidTy));
15084}
15085
15086void Sema::ActOnStartStmtExpr() {
15087 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15088}
15089
15090void Sema::ActOnStmtExprError() {
15091 // Note that function is also called by TreeTransform when leaving a
15092 // StmtExpr scope without rebuilding anything.
15093
15094 DiscardCleanupsInEvaluationContext();
15095 PopExpressionEvaluationContext();
15096}
15097
15098ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15099 SourceLocation RPLoc) {
15100 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15101}
15102
15103ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15104 SourceLocation RPLoc, unsigned TemplateDepth) {
15105 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")((void)0);
15106 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15107
15108 if (hasAnyUnrecoverableErrorsInThisFunction())
15109 DiscardCleanupsInEvaluationContext();
15110 assert(!Cleanup.exprNeedsCleanups() &&((void)0)
15111 "cleanups within StmtExpr not correctly bound!")((void)0);
15112 PopExpressionEvaluationContext();
15113
15114 // FIXME: there are a variety of strange constraints to enforce here, for
15115 // example, it is not possible to goto into a stmt expression apparently.
15116 // More semantic analysis is needed.
15117
15118 // If there are sub-stmts in the compound stmt, take the type of the last one
15119 // as the type of the stmtexpr.
15120 QualType Ty = Context.VoidTy;
15121 bool StmtExprMayBindToTemp = false;
15122 if (!Compound->body_empty()) {
15123 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15124 if (const auto *LastStmt =
15125 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15126 if (const Expr *Value = LastStmt->getExprStmt()) {
15127 StmtExprMayBindToTemp = true;
15128 Ty = Value->getType();
15129 }
15130 }
15131 }
15132
15133 // FIXME: Check that expression type is complete/non-abstract; statement
15134 // expressions are not lvalues.
15135 Expr *ResStmtExpr =
15136 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15137 if (StmtExprMayBindToTemp)
15138 return MaybeBindToTemporary(ResStmtExpr);
15139 return ResStmtExpr;
15140}
15141
15142ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15143 if (ER.isInvalid())
15144 return ExprError();
15145
15146 // Do function/array conversion on the last expression, but not
15147 // lvalue-to-rvalue. However, initialize an unqualified type.
15148 ER = DefaultFunctionArrayConversion(ER.get());
15149 if (ER.isInvalid())
15150 return ExprError();
15151 Expr *E = ER.get();
15152
15153 if (E->isTypeDependent())
15154 return E;
15155
15156 // In ARC, if the final expression ends in a consume, splice
15157 // the consume out and bind it later. In the alternate case
15158 // (when dealing with a retainable type), the result
15159 // initialization will create a produce. In both cases the
15160 // result will be +1, and we'll need to balance that out with
15161 // a bind.
15162 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15163 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15164 return Cast->getSubExpr();
15165
15166 // FIXME: Provide a better location for the initialization.
15167 return PerformCopyInitialization(
15168 InitializedEntity::InitializeStmtExprResult(
15169 E->getBeginLoc(), E->getType().getUnqualifiedType()),
15170 SourceLocation(), E);
15171}
15172
15173ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15174 TypeSourceInfo *TInfo,
15175 ArrayRef<OffsetOfComponent> Components,
15176 SourceLocation RParenLoc) {
15177 QualType ArgTy = TInfo->getType();
15178 bool Dependent = ArgTy->isDependentType();
15179 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15180
15181 // We must have at least one component that refers to the type, and the first
15182 // one is known to be a field designator. Verify that the ArgTy represents
15183 // a struct/union/class.
15184 if (!Dependent && !ArgTy->isRecordType())
15185 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15186 << ArgTy << TypeRange);
15187
15188 // Type must be complete per C99 7.17p3 because a declaring a variable
15189 // with an incomplete type would be ill-formed.
15190 if (!Dependent
15191 && RequireCompleteType(BuiltinLoc, ArgTy,
15192 diag::err_offsetof_incomplete_type, TypeRange))
15193 return ExprError();
15194
15195 bool DidWarnAboutNonPOD = false;
15196 QualType CurrentType = ArgTy;
15197 SmallVector<OffsetOfNode, 4> Comps;
15198 SmallVector<Expr*, 4> Exprs;
15199 for (const OffsetOfComponent &OC : Components) {
15200 if (OC.isBrackets) {
15201 // Offset of an array sub-field. TODO: Should we allow vector elements?
15202 if (!CurrentType->isDependentType()) {
15203 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15204 if(!AT)
15205 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15206 << CurrentType);
15207 CurrentType = AT->getElementType();
15208 } else
15209 CurrentType = Context.DependentTy;
15210
15211 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15212 if (IdxRval.isInvalid())
15213 return ExprError();
15214 Expr *Idx = IdxRval.get();
15215
15216 // The expression must be an integral expression.
15217 // FIXME: An integral constant expression?
15218 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15219 !Idx->getType()->isIntegerType())
15220 return ExprError(
15221 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15222 << Idx->getSourceRange());
15223
15224 // Record this array index.
15225 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15226 Exprs.push_back(Idx);
15227 continue;
15228 }
15229
15230 // Offset of a field.
15231 if (CurrentType->isDependentType()) {
15232 // We have the offset of a field, but we can't look into the dependent
15233 // type. Just record the identifier of the field.
15234 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15235 CurrentType = Context.DependentTy;
15236 continue;
15237 }
15238
15239 // We need to have a complete type to look into.
15240 if (RequireCompleteType(OC.LocStart, CurrentType,
15241 diag::err_offsetof_incomplete_type))
15242 return ExprError();
15243
15244 // Look for the designated field.
15245 const RecordType *RC = CurrentType->getAs<RecordType>();
15246 if (!RC)
15247 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15248 << CurrentType);
15249 RecordDecl *RD = RC->getDecl();
15250
15251 // C++ [lib.support.types]p5:
15252 // The macro offsetof accepts a restricted set of type arguments in this
15253 // International Standard. type shall be a POD structure or a POD union
15254 // (clause 9).
15255 // C++11 [support.types]p4:
15256 // If type is not a standard-layout class (Clause 9), the results are
15257 // undefined.
15258 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15259 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15260 unsigned DiagID =
15261 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15262 : diag::ext_offsetof_non_pod_type;
15263
15264 if (!IsSafe && !DidWarnAboutNonPOD &&
15265 DiagRuntimeBehavior(BuiltinLoc, nullptr,
15266 PDiag(DiagID)
15267 << SourceRange(Components[0].LocStart, OC.LocEnd)
15268 << CurrentType))
15269 DidWarnAboutNonPOD = true;
15270 }
15271
15272 // Look for the field.
15273 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15274 LookupQualifiedName(R, RD);
15275 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15276 IndirectFieldDecl *IndirectMemberDecl = nullptr;
15277 if (!MemberDecl) {
15278 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15279 MemberDecl = IndirectMemberDecl->getAnonField();
15280 }
15281
15282 if (!MemberDecl)
15283 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15284 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15285 OC.LocEnd));
15286
15287 // C99 7.17p3:
15288 // (If the specified member is a bit-field, the behavior is undefined.)
15289 //
15290 // We diagnose this as an error.
15291 if (MemberDecl->isBitField()) {
15292 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15293 << MemberDecl->getDeclName()
15294 << SourceRange(BuiltinLoc, RParenLoc);
15295 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15296 return ExprError();
15297 }
15298
15299 RecordDecl *Parent = MemberDecl->getParent();
15300 if (IndirectMemberDecl)
15301 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15302
15303 // If the member was found in a base class, introduce OffsetOfNodes for
15304 // the base class indirections.
15305 CXXBasePaths Paths;
15306 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15307 Paths)) {
15308 if (Paths.getDetectedVirtual()) {
15309 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15310 << MemberDecl->getDeclName()
15311 << SourceRange(BuiltinLoc, RParenLoc);
15312 return ExprError();
15313 }
15314
15315 CXXBasePath &Path = Paths.front();
15316 for (const CXXBasePathElement &B : Path)
15317 Comps.push_back(OffsetOfNode(B.Base));
15318 }
15319
15320 if (IndirectMemberDecl) {
15321 for (auto *FI : IndirectMemberDecl->chain()) {
15322 assert(isa<FieldDecl>(FI))((void)0);
15323 Comps.push_back(OffsetOfNode(OC.LocStart,
15324 cast<FieldDecl>(FI), OC.LocEnd));
15325 }
15326 } else
15327 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15328
15329 CurrentType = MemberDecl->getType().getNonReferenceType();
15330 }
15331
15332 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15333 Comps, Exprs, RParenLoc);
15334}
15335
15336ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15337 SourceLocation BuiltinLoc,
15338 SourceLocation TypeLoc,
15339 ParsedType ParsedArgTy,
15340 ArrayRef<OffsetOfComponent> Components,
15341 SourceLocation RParenLoc) {
15342
15343 TypeSourceInfo *ArgTInfo;
15344 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15345 if (ArgTy.isNull())
15346 return ExprError();
15347
15348 if (!ArgTInfo)
15349 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15350
15351 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15352}
15353
15354
15355ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15356 Expr *CondExpr,
15357 Expr *LHSExpr, Expr *RHSExpr,
15358 SourceLocation RPLoc) {
15359 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")((void)0);
15360
15361 ExprValueKind VK = VK_PRValue;
15362 ExprObjectKind OK = OK_Ordinary;
15363 QualType resType;
15364 bool CondIsTrue = false;
15365 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15366 resType = Context.DependentTy;
15367 } else {
15368 // The conditional expression is required to be a constant expression.
15369 llvm::APSInt condEval(32);
15370 ExprResult CondICE = VerifyIntegerConstantExpression(
15371 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15372 if (CondICE.isInvalid())
15373 return ExprError();
15374 CondExpr = CondICE.get();
15375 CondIsTrue = condEval.getZExtValue();
15376
15377 // If the condition is > zero, then the AST type is the same as the LHSExpr.
15378 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15379
15380 resType = ActiveExpr->getType();
15381 VK = ActiveExpr->getValueKind();
15382 OK = ActiveExpr->getObjectKind();
15383 }
15384
15385 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15386 resType, VK, OK, RPLoc, CondIsTrue);
15387}
15388
15389//===----------------------------------------------------------------------===//
15390// Clang Extensions.
15391//===----------------------------------------------------------------------===//
15392
15393/// ActOnBlockStart - This callback is invoked when a block literal is started.
15394void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15395 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15396
15397 if (LangOpts.CPlusPlus) {
15398 MangleNumberingContext *MCtx;
15399 Decl *ManglingContextDecl;
15400 std::tie(MCtx, ManglingContextDecl) =
15401 getCurrentMangleNumberContext(Block->getDeclContext());
15402 if (MCtx) {
15403 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15404 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15405 }
15406 }
15407
15408 PushBlockScope(CurScope, Block);
15409 CurContext->addDecl(Block);
15410 if (CurScope)
15411 PushDeclContext(CurScope, Block);
15412 else
15413 CurContext = Block;
15414
15415 getCurBlock()->HasImplicitReturnType = true;
15416
15417 // Enter a new evaluation context to insulate the block from any
15418 // cleanups from the enclosing full-expression.
15419 PushExpressionEvaluationContext(
15420 ExpressionEvaluationContext::PotentiallyEvaluated);
15421}
15422
15423void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15424 Scope *CurScope) {
15425 assert(ParamInfo.getIdentifier() == nullptr &&((void)0)
15426 "block-id should have no identifier!")((void)0);
15427 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral)((void)0);
15428 BlockScopeInfo *CurBlock = getCurBlock();
15429
15430 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15431 QualType T = Sig->getType();
15432
15433 // FIXME: We should allow unexpanded parameter packs here, but that would,
15434 // in turn, make the block expression contain unexpanded parameter packs.
15435 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15436 // Drop the parameters.
15437 FunctionProtoType::ExtProtoInfo EPI;
15438 EPI.HasTrailingReturn = false;
15439 EPI.TypeQuals.addConst();
15440 T = Context.getFunctionType(Context.DependentTy, None, EPI);
15441 Sig = Context.getTrivialTypeSourceInfo(T);
15442 }
15443
15444 // GetTypeForDeclarator always produces a function type for a block
15445 // literal signature. Furthermore, it is always a FunctionProtoType
15446 // unless the function was written with a typedef.
15447 assert(T->isFunctionType() &&((void)0)
15448 "GetTypeForDeclarator made a non-function block signature")((void)0);
15449
15450 // Look for an explicit signature in that function type.
15451 FunctionProtoTypeLoc ExplicitSignature;
15452
15453 if ((ExplicitSignature = Sig->getTypeLoc()
15454 .getAsAdjusted<FunctionProtoTypeLoc>())) {
15455
15456 // Check whether that explicit signature was synthesized by
15457 // GetTypeForDeclarator. If so, don't save that as part of the
15458 // written signature.
15459 if (ExplicitSignature.getLocalRangeBegin() ==
15460 ExplicitSignature.getLocalRangeEnd()) {
15461 // This would be much cheaper if we stored TypeLocs instead of
15462 // TypeSourceInfos.
15463 TypeLoc Result = ExplicitSignature.getReturnLoc();
15464 unsigned Size = Result.getFullDataSize();
15465 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15466 Sig->getTypeLoc().initializeFullCopy(Result, Size);
15467
15468 ExplicitSignature = FunctionProtoTypeLoc();
15469 }
15470 }
15471
15472 CurBlock->TheDecl->setSignatureAsWritten(Sig);
15473 CurBlock->FunctionType = T;
15474
15475 const auto *Fn = T->castAs<FunctionType>();
15476 QualType RetTy = Fn->getReturnType();
15477 bool isVariadic =
15478 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15479
15480 CurBlock->TheDecl->setIsVariadic(isVariadic);
15481
15482 // Context.DependentTy is used as a placeholder for a missing block
15483 // return type. TODO: what should we do with declarators like:
15484 // ^ * { ... }
15485 // If the answer is "apply template argument deduction"....
15486 if (RetTy != Context.DependentTy) {
15487 CurBlock->ReturnType = RetTy;
15488 CurBlock->TheDecl->setBlockMissingReturnType(false);
15489 CurBlock->HasImplicitReturnType = false;
15490 }
15491
15492 // Push block parameters from the declarator if we had them.
15493 SmallVector<ParmVarDecl*, 8> Params;
15494 if (ExplicitSignature) {
15495 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15496 ParmVarDecl *Param = ExplicitSignature.getParam(I);
15497 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15498 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15499 // Diagnose this as an extension in C17 and earlier.
15500 if (!getLangOpts().C2x)
15501 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15502 }
15503 Params.push_back(Param);
15504 }
15505
15506 // Fake up parameter variables if we have a typedef, like
15507 // ^ fntype { ... }
15508 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15509 for (const auto &I : Fn->param_types()) {
15510 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15511 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15512 Params.push_back(Param);
15513 }
15514 }
15515
15516 // Set the parameters on the block decl.
15517 if (!Params.empty()) {
15518 CurBlock->TheDecl->setParams(Params);
15519 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15520 /*CheckParameterNames=*/false);
15521 }
15522
15523 // Finally we can process decl attributes.
15524 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15525
15526 // Put the parameter variables in scope.
15527 for (auto AI : CurBlock->TheDecl->parameters()) {
15528 AI->setOwningFunction(CurBlock->TheDecl);
15529
15530 // If this has an identifier, add it to the scope stack.
15531 if (AI->getIdentifier()) {
15532 CheckShadow(CurBlock->TheScope, AI);
15533
15534 PushOnScopeChains(AI, CurBlock->TheScope);
15535 }
15536 }
15537}
15538
15539/// ActOnBlockError - If there is an error parsing a block, this callback
15540/// is invoked to pop the information about the block from the action impl.
15541void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15542 // Leave the expression-evaluation context.
15543 DiscardCleanupsInEvaluationContext();
15544 PopExpressionEvaluationContext();
15545
15546 // Pop off CurBlock, handle nested blocks.
15547 PopDeclContext();
15548 PopFunctionScopeInfo();
15549}
15550
15551/// ActOnBlockStmtExpr - This is called when the body of a block statement
15552/// literal was successfully completed. ^(int x){...}
15553ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15554 Stmt *Body, Scope *CurScope) {
15555 // If blocks are disabled, emit an error.
15556 if (!LangOpts.Blocks)
15557 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15558
15559 // Leave the expression-evaluation context.
15560 if (hasAnyUnrecoverableErrorsInThisFunction())
15561 DiscardCleanupsInEvaluationContext();
15562 assert(!Cleanup.exprNeedsCleanups() &&((void)0)
15563 "cleanups within block not correctly bound!")((void)0);
15564 PopExpressionEvaluationContext();
15565
15566 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15567 BlockDecl *BD = BSI->TheDecl;
15568
15569 if (BSI->HasImplicitReturnType)
15570 deduceClosureReturnType(*BSI);
15571
15572 QualType RetTy = Context.VoidTy;
15573 if (!BSI->ReturnType.isNull())
15574 RetTy = BSI->ReturnType;
15575
15576 bool NoReturn = BD->hasAttr<NoReturnAttr>();
15577 QualType BlockTy;
15578
15579 // If the user wrote a function type in some form, try to use that.
15580 if (!BSI->FunctionType.isNull()) {
15581 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15582
15583 FunctionType::ExtInfo Ext = FTy->getExtInfo();
15584 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15585
15586 // Turn protoless block types into nullary block types.
15587 if (isa<FunctionNoProtoType>(FTy)) {
15588 FunctionProtoType::ExtProtoInfo EPI;
15589 EPI.ExtInfo = Ext;
15590 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15591
15592 // Otherwise, if we don't need to change anything about the function type,
15593 // preserve its sugar structure.
15594 } else if (FTy->getReturnType() == RetTy &&
15595 (!NoReturn || FTy->getNoReturnAttr())) {
15596 BlockTy = BSI->FunctionType;
15597
15598 // Otherwise, make the minimal modifications to the function type.
15599 } else {
15600 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15601 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15602 EPI.TypeQuals = Qualifiers();
15603 EPI.ExtInfo = Ext;
15604 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15605 }
15606
15607 // If we don't have a function type, just build one from nothing.
15608 } else {
15609 FunctionProtoType::ExtProtoInfo EPI;
15610 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15611 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15612 }
15613
15614 DiagnoseUnusedParameters(BD->parameters());
15615 BlockTy = Context.getBlockPointerType(BlockTy);
15616
15617 // If needed, diagnose invalid gotos and switches in the block.
15618 if (getCurFunction()->NeedsScopeChecking() &&
15619 !PP.isCodeCompletionEnabled())
15620 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15621
15622 BD->setBody(cast<CompoundStmt>(Body));
15623
15624 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15625 DiagnoseUnguardedAvailabilityViolations(BD);
15626
15627 // Try to apply the named return value optimization. We have to check again
15628 // if we can do this, though, because blocks keep return statements around
15629 // to deduce an implicit return type.
15630 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15631 !BD->isDependentContext())
15632 computeNRVO(Body, BSI);
15633
15634 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15635 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15636 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15637 NTCUK_Destruct|NTCUK_Copy);
15638
15639 PopDeclContext();
15640
15641 // Set the captured variables on the block.
15642 SmallVector<BlockDecl::Capture, 4> Captures;
15643 for (Capture &Cap : BSI->Captures) {
15644 if (Cap.isInvalid() || Cap.isThisCapture())
15645 continue;
15646
15647 VarDecl *Var = Cap.getVariable();
15648 Expr *CopyExpr = nullptr;
15649 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15650 if (const RecordType *Record =
15651 Cap.getCaptureType()->getAs<RecordType>()) {
15652 // The capture logic needs the destructor, so make sure we mark it.
15653 // Usually this is unnecessary because most local variables have
15654 // their destructors marked at declaration time, but parameters are
15655 // an exception because it's technically only the call site that
15656 // actually requires the destructor.
15657 if (isa<ParmVarDecl>(Var))
15658 FinalizeVarWithDestructor(Var, Record);
15659
15660 // Enter a separate potentially-evaluated context while building block
15661 // initializers to isolate their cleanups from those of the block
15662 // itself.
15663 // FIXME: Is this appropriate even when the block itself occurs in an
15664 // unevaluated operand?
15665 EnterExpressionEvaluationContext EvalContext(
15666 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15667
15668 SourceLocation Loc = Cap.getLocation();
15669
15670 ExprResult Result = BuildDeclarationNameExpr(
15671 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15672
15673 // According to the blocks spec, the capture of a variable from
15674 // the stack requires a const copy constructor. This is not true
15675 // of the copy/move done to move a __block variable to the heap.
15676 if (!Result.isInvalid() &&
15677 !Result.get()->getType().isConstQualified()) {
15678 Result = ImpCastExprToType(Result.get(),
15679 Result.get()->getType().withConst(),
15680 CK_NoOp, VK_LValue);
15681 }
15682
15683 if (!Result.isInvalid()) {
15684 Result = PerformCopyInitialization(
15685 InitializedEntity::InitializeBlock(Var->getLocation(),
15686 Cap.getCaptureType()),
15687 Loc, Result.get());
15688 }
15689
15690 // Build a full-expression copy expression if initialization
15691 // succeeded and used a non-trivial constructor. Recover from
15692 // errors by pretending that the copy isn't necessary.
15693 if (!Result.isInvalid() &&
15694 !cast<CXXConstructExpr>(Result.get())->getConstructor()
15695 ->isTrivial()) {
15696 Result = MaybeCreateExprWithCleanups(Result);
15697 CopyExpr = Result.get();
15698 }
15699 }
15700 }
15701
15702 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15703 CopyExpr);
15704 Captures.push_back(NewCap);
15705 }
15706 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15707
15708 // Pop the block scope now but keep it alive to the end of this function.
15709 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15710 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15711
15712 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15713
15714 // If the block isn't obviously global, i.e. it captures anything at
15715 // all, then we need to do a few things in the surrounding context:
15716 if (Result->getBlockDecl()->hasCaptures()) {
15717 // First, this expression has a new cleanup object.
15718 ExprCleanupObjects.push_back(Result->getBlockDecl());
15719 Cleanup.setExprNeedsCleanups(true);
15720
15721 // It also gets a branch-protected scope if any of the captured
15722 // variables needs destruction.
15723 for (const auto &CI : Result->getBlockDecl()->captures()) {
15724 const VarDecl *var = CI.getVariable();
15725 if (var->getType().isDestructedType() != QualType::DK_none) {
15726 setFunctionHasBranchProtectedScope();
15727 break;
15728 }
15729 }
15730 }
15731
15732 if (getCurFunction())
15733 getCurFunction()->addBlock(BD);
15734
15735 return Result;
15736}
15737
15738ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15739 SourceLocation RPLoc) {
15740 TypeSourceInfo *TInfo;
15741 GetTypeFromParser(Ty, &TInfo);
15742 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15743}
15744
15745ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15746 Expr *E, TypeSourceInfo *TInfo,
15747 SourceLocation RPLoc) {
15748 Expr *OrigExpr = E;
15749 bool IsMS = false;
15750
15751 // CUDA device code does not support varargs.
15752 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15753 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15754 CUDAFunctionTarget T = IdentifyCUDATarget(F);
15755 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15756 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15757 }
15758 }
15759
15760 // NVPTX does not support va_arg expression.
15761 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15762 Context.getTargetInfo().getTriple().isNVPTX())
15763 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15764
15765 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15766 // as Microsoft ABI on an actual Microsoft platform, where
15767 // __builtin_ms_va_list and __builtin_va_list are the same.)
15768 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15769 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15770 QualType MSVaListType = Context.getBuiltinMSVaListType();
15771 if (Context.hasSameType(MSVaListType, E->getType())) {
15772 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15773 return ExprError();
15774 IsMS = true;
15775 }
15776 }
15777
15778 // Get the va_list type
15779 QualType VaListType = Context.getBuiltinVaListType();
15780 if (!IsMS) {
15781 if (VaListType->isArrayType()) {
15782 // Deal with implicit array decay; for example, on x86-64,
15783 // va_list is an array, but it's supposed to decay to
15784 // a pointer for va_arg.
15785 VaListType = Context.getArrayDecayedType(VaListType);
15786 // Make sure the input expression also decays appropriately.
15787 ExprResult Result = UsualUnaryConversions(E);
15788 if (Result.isInvalid())
15789 return ExprError();
15790 E = Result.get();
15791 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15792 // If va_list is a record type and we are compiling in C++ mode,
15793 // check the argument using reference binding.
15794 InitializedEntity Entity = InitializedEntity::InitializeParameter(
15795 Context, Context.getLValueReferenceType(VaListType), false);
15796 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15797 if (Init.isInvalid())
15798 return ExprError();
15799 E = Init.getAs<Expr>();
15800 } else {
15801 // Otherwise, the va_list argument must be an l-value because
15802 // it is modified by va_arg.
15803 if (!E->isTypeDependent() &&
15804 CheckForModifiableLvalue(E, BuiltinLoc, *this))
15805 return ExprError();
15806 }
15807 }
15808
15809 if (!IsMS && !E->isTypeDependent() &&
15810 !Context.hasSameType(VaListType, E->getType()))
15811 return ExprError(
15812 Diag(E->getBeginLoc(),
15813 diag::err_first_argument_to_va_arg_not_of_type_va_list)
15814 << OrigExpr->getType() << E->getSourceRange());
15815
15816 if (!TInfo->getType()->isDependentType()) {
15817 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15818 diag::err_second_parameter_to_va_arg_incomplete,
15819 TInfo->getTypeLoc()))
15820 return ExprError();
15821
15822 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15823 TInfo->getType(),
15824 diag::err_second_parameter_to_va_arg_abstract,
15825 TInfo->getTypeLoc()))
15826 return ExprError();
15827
15828 if (!TInfo->getType().isPODType(Context)) {
15829 Diag(TInfo->getTypeLoc().getBeginLoc(),
15830 TInfo->getType()->isObjCLifetimeType()
15831 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15832 : diag::warn_second_parameter_to_va_arg_not_pod)
15833 << TInfo->getType()
15834 << TInfo->getTypeLoc().getSourceRange();
15835 }
15836
15837 // Check for va_arg where arguments of the given type will be promoted
15838 // (i.e. this va_arg is guaranteed to have undefined behavior).
15839 QualType PromoteType;
15840 if (TInfo->getType()->isPromotableIntegerType()) {
15841 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15842 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
15843 // and C2x 7.16.1.1p2 says, in part:
15844 // If type is not compatible with the type of the actual next argument
15845 // (as promoted according to the default argument promotions), the
15846 // behavior is undefined, except for the following cases:
15847 // - both types are pointers to qualified or unqualified versions of
15848 // compatible types;
15849 // - one type is a signed integer type, the other type is the
15850 // corresponding unsigned integer type, and the value is
15851 // representable in both types;
15852 // - one type is pointer to qualified or unqualified void and the
15853 // other is a pointer to a qualified or unqualified character type.
15854 // Given that type compatibility is the primary requirement (ignoring
15855 // qualifications), you would think we could call typesAreCompatible()
15856 // directly to test this. However, in C++, that checks for *same type*,
15857 // which causes false positives when passing an enumeration type to
15858 // va_arg. Instead, get the underlying type of the enumeration and pass
15859 // that.
15860 QualType UnderlyingType = TInfo->getType();
15861 if (const auto *ET = UnderlyingType->getAs<EnumType>())
15862 UnderlyingType = ET->getDecl()->getIntegerType();
15863 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
15864 /*CompareUnqualified*/ true))
15865 PromoteType = QualType();
15866
15867 // If the types are still not compatible, we need to test whether the
15868 // promoted type and the underlying type are the same except for
15869 // signedness. Ask the AST for the correctly corresponding type and see
15870 // if that's compatible.
15871 if (!PromoteType.isNull() &&
15872 PromoteType->isUnsignedIntegerType() !=
15873 UnderlyingType->isUnsignedIntegerType()) {
15874 UnderlyingType =
15875 UnderlyingType->isUnsignedIntegerType()
15876 ? Context.getCorrespondingSignedType(UnderlyingType)
15877 : Context.getCorrespondingUnsignedType(UnderlyingType);
15878 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
15879 /*CompareUnqualified*/ true))
15880 PromoteType = QualType();
15881 }
15882 }
15883 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15884 PromoteType = Context.DoubleTy;
15885 if (!PromoteType.isNull())
15886 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15887 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15888 << TInfo->getType()
15889 << PromoteType
15890 << TInfo->getTypeLoc().getSourceRange());
15891 }
15892
15893 QualType T = TInfo->getType().getNonLValueExprType(Context);
15894 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15895}
15896
15897ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15898 // The type of __null will be int or long, depending on the size of
15899 // pointers on the target.
15900 QualType Ty;
15901 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15902 if (pw == Context.getTargetInfo().getIntWidth())
15903 Ty = Context.IntTy;
15904 else if (pw == Context.getTargetInfo().getLongWidth())
15905 Ty = Context.LongTy;
15906 else if (pw == Context.getTargetInfo().getLongLongWidth())
15907 Ty = Context.LongLongTy;
15908 else {
15909 llvm_unreachable("I don't know size of pointer!")__builtin_unreachable();
15910 }
15911
15912 return new (Context) GNUNullExpr(Ty, TokenLoc);
15913}
15914
15915ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15916 SourceLocation BuiltinLoc,
15917 SourceLocation RPLoc) {
15918 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15919}
15920
15921ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15922 SourceLocation BuiltinLoc,
15923 SourceLocation RPLoc,
15924 DeclContext *ParentContext) {
15925 return new (Context)
15926 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15927}
15928
15929bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15930 bool Diagnose) {
15931 if (!getLangOpts().ObjC)
15932 return false;
15933
15934 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15935 if (!PT)
15936 return false;
15937 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15938
15939 // Ignore any parens, implicit casts (should only be
15940 // array-to-pointer decays), and not-so-opaque values. The last is
15941 // important for making this trigger for property assignments.
15942 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15943 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15944 if (OV->getSourceExpr())
15945 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15946
15947 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15948 if (!PT->isObjCIdType() &&
15949 !(ID && ID->getIdentifier()->isStr("NSString")))
15950 return false;
15951 if (!SL->isAscii())
15952 return false;
15953
15954 if (Diagnose) {
15955 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15956 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15957 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15958 }
15959 return true;
15960 }
15961
15962 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15963 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15964 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15965 !SrcExpr->isNullPointerConstant(
15966 getASTContext(), Expr::NPC_NeverValueDependent)) {
15967 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15968 return false;
15969 if (Diagnose) {
15970 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15971 << /*number*/1
15972 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15973 Expr *NumLit =
15974 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15975 if (NumLit)
15976 Exp = NumLit;
15977 }
15978 return true;
15979 }
15980
15981 return false;
15982}
15983
15984static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15985 const Expr *SrcExpr) {
15986 if (!DstType->isFunctionPointerType() ||
15987 !SrcExpr->getType()->isFunctionType())
15988 return false;
15989
15990 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15991 if (!DRE)
15992 return false;
15993
15994 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15995 if (!FD)
15996 return false;
15997
15998 return !S.checkAddressOfFunctionIsAvailable(FD,
15999 /*Complain=*/true,
16000 SrcExpr->getBeginLoc());
16001}
16002
16003bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16004 SourceLocation Loc,
16005 QualType DstType, QualType SrcType,
16006 Expr *SrcExpr, AssignmentAction Action,
16007 bool *Complained) {
16008 if (Complained)
16009 *Complained = false;
16010
16011 // Decode the result (notice that AST's are still created for extensions).
16012 bool CheckInferredResultType = false;
16013 bool isInvalid = false;
16014 unsigned DiagKind = 0;
16015 ConversionFixItGenerator ConvHints;
16016 bool MayHaveConvFixit = false;
16017 bool MayHaveFunctionDiff = false;
16018 const ObjCInterfaceDecl *IFace = nullptr;
16019 const ObjCProtocolDecl *PDecl = nullptr;
16020
16021 switch (ConvTy) {
16022 case Compatible:
16023 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16024 return false;
16025
16026 case PointerToInt:
16027 if (getLangOpts().CPlusPlus) {
16028 DiagKind = diag::err_typecheck_convert_pointer_int;
16029 isInvalid = true;
16030 } else {
16031 DiagKind = diag::ext_typecheck_convert_pointer_int;
16032 }
16033 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16034 MayHaveConvFixit = true;
16035 break;
16036 case IntToPointer:
16037 if (getLangOpts().CPlusPlus) {
16038 DiagKind = diag::err_typecheck_convert_int_pointer;
16039 isInvalid = true;
16040 } else {
16041 DiagKind = diag::ext_typecheck_convert_int_pointer;
16042 }
16043 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16044 MayHaveConvFixit = true;
16045 break;
16046 case IncompatibleFunctionPointer:
16047 if (getLangOpts().CPlusPlus) {
16048 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16049 isInvalid = true;
16050 } else {
16051 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16052 }
16053 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16054 MayHaveConvFixit = true;
16055 break;
16056 case IncompatiblePointer:
16057 if (Action == AA_Passing_CFAudited) {
16058 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16059 } else if (getLangOpts().CPlusPlus) {
16060 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16061 isInvalid = true;
16062 } else {
16063 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16064 }
16065 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16066 SrcType->isObjCObjectPointerType();
16067 if (!CheckInferredResultType) {
16068 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16069 } else if (CheckInferredResultType) {
16070 SrcType = SrcType.getUnqualifiedType();
16071 DstType = DstType.getUnqualifiedType();
16072 }
16073 MayHaveConvFixit = true;
16074 break;
16075 case IncompatiblePointerSign:
16076 if (getLangOpts().CPlusPlus) {
16077 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16078 isInvalid = true;
16079 } else {
16080 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16081 }
16082 break;
16083 case FunctionVoidPointer:
16084 if (getLangOpts().CPlusPlus) {
16085 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16086 isInvalid = true;
16087 } else {
16088 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16089 }
16090 break;
16091 case IncompatiblePointerDiscardsQualifiers: {
16092 // Perform array-to-pointer decay if necessary.
16093 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16094
16095 isInvalid = true;
16096
16097 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16098 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16099 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16100 DiagKind = diag::err_typecheck_incompatible_address_space;
16101 break;
16102
16103 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16104 DiagKind = diag::err_typecheck_incompatible_ownership;
16105 break;
16106 }
16107
16108 llvm_unreachable("unknown error case for discarding qualifiers!")__builtin_unreachable();
16109 // fallthrough
16110 }
16111 case CompatiblePointerDiscardsQualifiers:
16112 // If the qualifiers lost were because we were applying the
16113 // (deprecated) C++ conversion from a string literal to a char*
16114 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16115 // Ideally, this check would be performed in
16116 // checkPointerTypesForAssignment. However, that would require a
16117 // bit of refactoring (so that the second argument is an
16118 // expression, rather than a type), which should be done as part
16119 // of a larger effort to fix checkPointerTypesForAssignment for
16120 // C++ semantics.
16121 if (getLangOpts().CPlusPlus &&
16122 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16123 return false;
16124 if (getLangOpts().CPlusPlus) {
16125 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16126 isInvalid = true;
16127 } else {
16128 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16129 }
16130
16131 break;
16132 case IncompatibleNestedPointerQualifiers:
16133 if (getLangOpts().CPlusPlus) {
16134 isInvalid = true;
16135 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16136 } else {
16137 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16138 }
16139 break;
16140 case IncompatibleNestedPointerAddressSpaceMismatch:
16141 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16142 isInvalid = true;
16143 break;
16144 case IntToBlockPointer:
16145 DiagKind = diag::err_int_to_block_pointer;
16146 isInvalid = true;
16147 break;
16148 case IncompatibleBlockPointer:
16149 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16150 isInvalid = true;
16151 break;
16152 case IncompatibleObjCQualifiedId: {
16153 if (SrcType->isObjCQualifiedIdType()) {
16154 const ObjCObjectPointerType *srcOPT =
16155 SrcType->castAs<ObjCObjectPointerType>();
16156 for (auto *srcProto : srcOPT->quals()) {
16157 PDecl = srcProto;
16158 break;
16159 }
16160 if (const ObjCInterfaceType *IFaceT =
16161 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16162 IFace = IFaceT->getDecl();
16163 }
16164 else if (DstType->isObjCQualifiedIdType()) {
16165 const ObjCObjectPointerType *dstOPT =
16166 DstType->castAs<ObjCObjectPointerType>();
16167 for (auto *dstProto : dstOPT->quals()) {
16168 PDecl = dstProto;
16169 break;
16170 }
16171 if (const ObjCInterfaceType *IFaceT =
16172 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16173 IFace = IFaceT->getDecl();
16174 }
16175 if (getLangOpts().CPlusPlus) {
16176 DiagKind = diag::err_incompatible_qualified_id;
16177 isInvalid = true;
16178 } else {
16179 DiagKind = diag::warn_incompatible_qualified_id;
16180 }
16181 break;
16182 }
16183 case IncompatibleVectors:
16184 if (getLangOpts().CPlusPlus) {
16185 DiagKind = diag::err_incompatible_vectors;
16186 isInvalid = true;
16187 } else {
16188 DiagKind = diag::warn_incompatible_vectors;
16189 }
16190 break;
16191 case IncompatibleObjCWeakRef:
16192 DiagKind = diag::err_arc_weak_unavailable_assign;
16193 isInvalid = true;
16194 break;
16195 case Incompatible:
16196 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16197 if (Complained)
16198 *Complained = true;
16199 return true;
16200 }
16201
16202 DiagKind = diag::err_typecheck_convert_incompatible;
16203 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16204 MayHaveConvFixit = true;
16205 isInvalid = true;
16206 MayHaveFunctionDiff = true;
16207 break;
16208 }
16209
16210 QualType FirstType, SecondType;
16211 switch (Action) {
16212 case AA_Assigning:
16213 case AA_Initializing:
16214 // The destination type comes first.
16215 FirstType = DstType;
16216 SecondType = SrcType;
16217 break;
16218
16219 case AA_Returning:
16220 case AA_Passing:
16221 case AA_Passing_CFAudited:
16222 case AA_Converting:
16223 case AA_Sending:
16224 case AA_Casting:
16225 // The source type comes first.
16226 FirstType = SrcType;
16227 SecondType = DstType;
16228 break;
16229 }
16230
16231 PartialDiagnostic FDiag = PDiag(DiagKind);
16232 if (Action == AA_Passing_CFAudited)
16233 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16234 else
16235 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16236
16237 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16238 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16239 auto isPlainChar = [](const clang::Type *Type) {
16240 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16241 Type->isSpecificBuiltinType(BuiltinType::Char_U);
16242 };
16243 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16244 isPlainChar(SecondType->getPointeeOrArrayElementType()));
16245 }
16246
16247 // If we can fix the conversion, suggest the FixIts.
16248 if (!ConvHints.isNull()) {
16249 for (FixItHint &H : ConvHints.Hints)
16250 FDiag << H;
16251 }
16252
16253 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16254
16255 if (MayHaveFunctionDiff)
16256 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16257
16258 Diag(Loc, FDiag);
16259 if ((DiagKind == diag::warn_incompatible_qualified_id ||
16260 DiagKind == diag::err_incompatible_qualified_id) &&
16261 PDecl && IFace && !IFace->hasDefinition())
16262 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16263 << IFace << PDecl;
16264
16265 if (SecondType == Context.OverloadTy)
16266 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16267 FirstType, /*TakingAddress=*/true);
16268
16269 if (CheckInferredResultType)
16270 EmitRelatedResultTypeNote(SrcExpr);
16271
16272 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16273 EmitRelatedResultTypeNoteForReturn(DstType);
16274
16275 if (Complained)
16276 *Complained = true;
16277 return isInvalid;
16278}
16279
16280ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16281 llvm::APSInt *Result,
16282 AllowFoldKind CanFold) {
16283 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16284 public:
16285 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16286 QualType T) override {
16287 return S.Diag(Loc, diag::err_ice_not_integral)
16288 << T << S.LangOpts.CPlusPlus;
16289 }
16290 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16291 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16292 }
16293 } Diagnoser;
16294
16295 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16296}
16297
16298ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16299 llvm::APSInt *Result,
16300 unsigned DiagID,
16301 AllowFoldKind CanFold) {
16302 class IDDiagnoser : public VerifyICEDiagnoser {
16303 unsigned DiagID;
16304
16305 public:
16306 IDDiagnoser(unsigned DiagID)
16307 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16308
16309 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16310 return S.Diag(Loc, DiagID);
16311 }
16312 } Diagnoser(DiagID);
16313
16314 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16315}
16316
16317Sema::SemaDiagnosticBuilder
16318Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16319 QualType T) {
16320 return diagnoseNotICE(S, Loc);
16321}
16322
16323Sema::SemaDiagnosticBuilder
16324Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16325 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16326}
16327
16328ExprResult
16329Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16330 VerifyICEDiagnoser &Diagnoser,
16331 AllowFoldKind CanFold) {
16332 SourceLocation DiagLoc = E->getBeginLoc();
16333
16334 if (getLangOpts().CPlusPlus11) {
16335 // C++11 [expr.const]p5:
16336 // If an expression of literal class type is used in a context where an
16337 // integral constant expression is required, then that class type shall
16338 // have a single non-explicit conversion function to an integral or
16339 // unscoped enumeration type
16340 ExprResult Converted;
16341 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16342 VerifyICEDiagnoser &BaseDiagnoser;
16343 public:
16344 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16345 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16346 BaseDiagnoser.Suppress, true),
16347 BaseDiagnoser(BaseDiagnoser) {}
16348
16349 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16350 QualType T) override {
16351 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16352 }
16353
16354 SemaDiagnosticBuilder diagnoseIncomplete(
16355 Sema &S, SourceLocation Loc, QualType T) override {
16356 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16357 }
16358
16359 SemaDiagnosticBuilder diagnoseExplicitConv(
16360 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16361 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16362 }
16363
16364 SemaDiagnosticBuilder noteExplicitConv(
16365 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16366 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16367 << ConvTy->isEnumeralType() << ConvTy;
16368 }
16369
16370 SemaDiagnosticBuilder diagnoseAmbiguous(
16371 Sema &S, SourceLocation Loc, QualType T) override {
16372 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16373 }
16374
16375 SemaDiagnosticBuilder noteAmbiguous(
16376 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16377 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16378 << ConvTy->isEnumeralType() << ConvTy;
16379 }
16380
16381 SemaDiagnosticBuilder diagnoseConversion(
16382 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16383 llvm_unreachable("conversion functions are permitted")__builtin_unreachable();
16384 }
16385 } ConvertDiagnoser(Diagnoser);
16386
16387 Converted = PerformContextualImplicitConversion(DiagLoc, E,
16388 ConvertDiagnoser);
16389 if (Converted.isInvalid())
16390 return Converted;
16391 E = Converted.get();
16392 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16393 return ExprError();
16394 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16395 // An ICE must be of integral or unscoped enumeration type.
16396 if (!Diagnoser.Suppress)
16397 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16398 << E->getSourceRange();
16399 return ExprError();
16400 }
16401
16402 ExprResult RValueExpr = DefaultLvalueConversion(E);
16403 if (RValueExpr.isInvalid())
16404 return ExprError();
16405
16406 E = RValueExpr.get();
16407
16408 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16409 // in the non-ICE case.
16410 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16411 if (Result)
16412 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16413 if (!isa<ConstantExpr>(E))
16414 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
16415 : ConstantExpr::Create(Context, E);
16416 return E;
16417 }
16418
16419 Expr::EvalResult EvalResult;
16420 SmallVector<PartialDiagnosticAt, 8> Notes;
16421 EvalResult.Diag = &Notes;
16422
16423 // Try to evaluate the expression, and produce diagnostics explaining why it's
16424 // not a constant expression as a side-effect.
16425 bool Folded =
16426 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16427 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16428
16429 if (!isa<ConstantExpr>(E))
16430 E = ConstantExpr::Create(Context, E, EvalResult.Val);
16431
16432 // In C++11, we can rely on diagnostics being produced for any expression
16433 // which is not a constant expression. If no diagnostics were produced, then
16434 // this is a constant expression.
16435 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16436 if (Result)
16437 *Result = EvalResult.Val.getInt();
16438 return E;
16439 }
16440
16441 // If our only note is the usual "invalid subexpression" note, just point
16442 // the caret at its location rather than producing an essentially
16443 // redundant note.
16444 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16445 diag::note_invalid_subexpr_in_const_expr) {
16446 DiagLoc = Notes[0].first;
16447 Notes.clear();
16448 }
16449
16450 if (!Folded || !CanFold) {
16451 if (!Diagnoser.Suppress) {
16452 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16453 for (const PartialDiagnosticAt &Note : Notes)
16454 Diag(Note.first, Note.second);
16455 }
16456
16457 return ExprError();
16458 }
16459
16460 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16461 for (const PartialDiagnosticAt &Note : Notes)
16462 Diag(Note.first, Note.second);
16463
16464 if (Result)
16465 *Result = EvalResult.Val.getInt();
16466 return E;
16467}
16468
16469namespace {
16470 // Handle the case where we conclude a expression which we speculatively
16471 // considered to be unevaluated is actually evaluated.
16472 class TransformToPE : public TreeTransform<TransformToPE> {
16473 typedef TreeTransform<TransformToPE> BaseTransform;
16474
16475 public:
16476 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16477
16478 // Make sure we redo semantic analysis
16479 bool AlwaysRebuild() { return true; }
16480 bool ReplacingOriginal() { return true; }
16481
16482 // We need to special-case DeclRefExprs referring to FieldDecls which
16483 // are not part of a member pointer formation; normal TreeTransforming
16484 // doesn't catch this case because of the way we represent them in the AST.
16485 // FIXME: This is a bit ugly; is it really the best way to handle this
16486 // case?
16487 //
16488 // Error on DeclRefExprs referring to FieldDecls.
16489 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16490 if (isa<FieldDecl>(E->getDecl()) &&
16491 !SemaRef.isUnevaluatedContext())
16492 return SemaRef.Diag(E->getLocation(),
16493 diag::err_invalid_non_static_member_use)
16494 << E->getDecl() << E->getSourceRange();
16495
16496 return BaseTransform::TransformDeclRefExpr(E);
16497 }
16498
16499 // Exception: filter out member pointer formation
16500 ExprResult TransformUnaryOperator(UnaryOperator *E) {
16501 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16502 return E;
16503
16504 return BaseTransform::TransformUnaryOperator(E);
16505 }
16506
16507 // The body of a lambda-expression is in a separate expression evaluation
16508 // context so never needs to be transformed.
16509 // FIXME: Ideally we wouldn't transform the closure type either, and would
16510 // just recreate the capture expressions and lambda expression.
16511 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16512 return SkipLambdaBody(E, Body);
16513 }
16514 };
16515}
16516
16517ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16518 assert(isUnevaluatedContext() &&((void)0)
16519 "Should only transform unevaluated expressions")((void)0);
16520 ExprEvalContexts.back().Context =
16521 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16522 if (isUnevaluatedContext())
16523 return E;
16524 return TransformToPE(*this).TransformExpr(E);
16525}
16526
16527void
16528Sema::PushExpressionEvaluationContext(
16529 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16530 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16531 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16532 LambdaContextDecl, ExprContext);
16533 Cleanup.reset();
16534 if (!MaybeODRUseExprs.empty())
16535 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16536}
16537
16538void
16539Sema::PushExpressionEvaluationContext(
16540 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16541 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16542 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16543 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16544}
16545
16546namespace {
16547
16548const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16549 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16550 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16551 if (E->getOpcode() == UO_Deref)
16552 return CheckPossibleDeref(S, E->getSubExpr());
16553 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16554 return CheckPossibleDeref(S, E->getBase());
16555 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16556 return CheckPossibleDeref(S, E->getBase());
16557 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16558 QualType Inner;
16559 QualType Ty = E->getType();
16560 if (const auto *Ptr = Ty->getAs<PointerType>())
16561 Inner = Ptr->getPointeeType();
16562 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16563 Inner = Arr->getElementType();
16564 else
16565 return nullptr;
16566
16567 if (Inner->hasAttr(attr::NoDeref))
16568 return E;
16569 }
16570 return nullptr;
16571}
16572
16573} // namespace
16574
16575void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16576 for (const Expr *E : Rec.PossibleDerefs) {
16577 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16578 if (DeclRef) {
16579 const ValueDecl *Decl = DeclRef->getDecl();
16580 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16581 << Decl->getName() << E->getSourceRange();
16582 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16583 } else {
16584 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16585 << E->getSourceRange();
16586 }
16587 }
16588 Rec.PossibleDerefs.clear();
16589}
16590
16591/// Check whether E, which is either a discarded-value expression or an
16592/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16593/// and if so, remove it from the list of volatile-qualified assignments that
16594/// we are going to warn are deprecated.
16595void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16596 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16597 return;
16598
16599 // Note: ignoring parens here is not justified by the standard rules, but
16600 // ignoring parentheses seems like a more reasonable approach, and this only
16601 // drives a deprecation warning so doesn't affect conformance.
16602 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16603 if (BO->getOpcode() == BO_Assign) {
16604 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16605 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16606 LHSs.end());
16607 }
16608 }
16609}
16610
16611ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16612 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16613 RebuildingImmediateInvocation)
16614 return E;
16615
16616 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16617 /// It's OK if this fails; we'll also remove this in
16618 /// HandleImmediateInvocations, but catching it here allows us to avoid
16619 /// walking the AST looking for it in simple cases.
16620 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16621 if (auto *DeclRef =
16622 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16623 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16624
16625 E = MaybeCreateExprWithCleanups(E);
16626
16627 ConstantExpr *Res = ConstantExpr::Create(
16628 getASTContext(), E.get(),
16629 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16630 getASTContext()),
16631 /*IsImmediateInvocation*/ true);
16632 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16633 return Res;
16634}
16635
16636static void EvaluateAndDiagnoseImmediateInvocation(
16637 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16638 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16639 Expr::EvalResult Eval;
16640 Eval.Diag = &Notes;
16641 ConstantExpr *CE = Candidate.getPointer();
16642 bool Result = CE->EvaluateAsConstantExpr(
16643 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16644 if (!Result || !Notes.empty()) {
16645 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16646 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16647 InnerExpr = FunctionalCast->getSubExpr();
16648 FunctionDecl *FD = nullptr;
16649 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16650 FD = cast<FunctionDecl>(Call->getCalleeDecl());
16651 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16652 FD = Call->getConstructor();
16653 else
16654 llvm_unreachable("unhandled decl kind")__builtin_unreachable();
16655 assert(FD->isConsteval())((void)0);
16656 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16657 for (auto &Note : Notes)
16658 SemaRef.Diag(Note.first, Note.second);
16659 return;
16660 }
16661 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16662}
16663
16664static void RemoveNestedImmediateInvocation(
16665 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16666 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16667 struct ComplexRemove : TreeTransform<ComplexRemove> {
16668 using Base = TreeTransform<ComplexRemove>;
16669 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16670 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16671 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16672 CurrentII;
16673 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16674 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16675 SmallVector<Sema::ImmediateInvocationCandidate,
16676 4>::reverse_iterator Current)
16677 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16678 void RemoveImmediateInvocation(ConstantExpr* E) {
16679 auto It = std::find_if(CurrentII, IISet.rend(),
16680 [E](Sema::ImmediateInvocationCandidate Elem) {
16681 return Elem.getPointer() == E;
16682 });
16683 assert(It != IISet.rend() &&((void)0)
16684 "ConstantExpr marked IsImmediateInvocation should "((void)0)
16685 "be present")((void)0);
16686 It->setInt(1); // Mark as deleted
16687 }
16688 ExprResult TransformConstantExpr(ConstantExpr *E) {
16689 if (!E->isImmediateInvocation())
16690 return Base::TransformConstantExpr(E);
16691 RemoveImmediateInvocation(E);
16692 return Base::TransformExpr(E->getSubExpr());
16693 }
16694 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16695 /// we need to remove its DeclRefExpr from the DRSet.
16696 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16697 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16698 return Base::TransformCXXOperatorCallExpr(E);
16699 }
16700 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16701 /// here.
16702 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16703 if (!Init)
16704 return Init;
16705 /// ConstantExpr are the first layer of implicit node to be removed so if
16706 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16707 if (auto *CE = dyn_cast<ConstantExpr>(Init))
16708 if (CE->isImmediateInvocation())
16709 RemoveImmediateInvocation(CE);
16710 return Base::TransformInitializer(Init, NotCopyInit);
16711 }
16712 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16713 DRSet.erase(E);
16714 return E;
16715 }
16716 bool AlwaysRebuild() { return false; }
16717 bool ReplacingOriginal() { return true; }
16718 bool AllowSkippingCXXConstructExpr() {
16719 bool Res = AllowSkippingFirstCXXConstructExpr;
16720 AllowSkippingFirstCXXConstructExpr = true;
16721 return Res;
16722 }
16723 bool AllowSkippingFirstCXXConstructExpr = true;
16724 } Transformer(SemaRef, Rec.ReferenceToConsteval,
16725 Rec.ImmediateInvocationCandidates, It);
16726
16727 /// CXXConstructExpr with a single argument are getting skipped by
16728 /// TreeTransform in some situtation because they could be implicit. This
16729 /// can only occur for the top-level CXXConstructExpr because it is used
16730 /// nowhere in the expression being transformed therefore will not be rebuilt.
16731 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16732 /// skipping the first CXXConstructExpr.
16733 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16734 Transformer.AllowSkippingFirstCXXConstructExpr = false;
16735
16736 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16737 assert(Res.isUsable())((void)0);
16738 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16739 It->getPointer()->setSubExpr(Res.get());
16740}
16741
16742static void
16743HandleImmediateInvocations(Sema &SemaRef,
16744 Sema::ExpressionEvaluationContextRecord &Rec) {
16745 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16746 Rec.ReferenceToConsteval.size() == 0) ||
16747 SemaRef.RebuildingImmediateInvocation)
16748 return;
16749
16750 /// When we have more then 1 ImmediateInvocationCandidates we need to check
16751 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16752 /// need to remove ReferenceToConsteval in the immediate invocation.
16753 if (Rec.ImmediateInvocationCandidates.size() > 1) {
16754
16755 /// Prevent sema calls during the tree transform from adding pointers that
16756 /// are already in the sets.
16757 llvm::SaveAndRestore<bool> DisableIITracking(
16758 SemaRef.RebuildingImmediateInvocation, true);
16759
16760 /// Prevent diagnostic during tree transfrom as they are duplicates
16761 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16762
16763 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16764 It != Rec.ImmediateInvocationCandidates.rend(); It++)
16765 if (!It->getInt())
16766 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16767 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16768 Rec.ReferenceToConsteval.size()) {
16769 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16770 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16771 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16772 bool VisitDeclRefExpr(DeclRefExpr *E) {
16773 DRSet.erase(E);
16774 return DRSet.size();
16775 }
16776 } Visitor(Rec.ReferenceToConsteval);
16777 Visitor.TraverseStmt(
16778 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16779 }
16780 for (auto CE : Rec.ImmediateInvocationCandidates)
16781 if (!CE.getInt())
16782 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16783 for (auto DR : Rec.ReferenceToConsteval) {
16784 auto *FD = cast<FunctionDecl>(DR->getDecl());
16785 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16786 << FD;
16787 SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16788 }
16789}
16790
16791void Sema::PopExpressionEvaluationContext() {
16792 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16793 unsigned NumTypos = Rec.NumTypos;
16794
16795 if (!Rec.Lambdas.empty()) {
16796 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16797 if (!getLangOpts().CPlusPlus20 &&
16798 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
16799 Rec.isUnevaluated() ||
16800 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
16801 unsigned D;
16802 if (Rec.isUnevaluated()) {
16803 // C++11 [expr.prim.lambda]p2:
16804 // A lambda-expression shall not appear in an unevaluated operand
16805 // (Clause 5).
16806 D = diag::err_lambda_unevaluated_operand;
16807 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16808 // C++1y [expr.const]p2:
16809 // A conditional-expression e is a core constant expression unless the
16810 // evaluation of e, following the rules of the abstract machine, would
16811 // evaluate [...] a lambda-expression.
16812 D = diag::err_lambda_in_constant_expression;
16813 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16814 // C++17 [expr.prim.lamda]p2:
16815 // A lambda-expression shall not appear [...] in a template-argument.
16816 D = diag::err_lambda_in_invalid_context;
16817 } else
16818 llvm_unreachable("Couldn't infer lambda error message.")__builtin_unreachable();
16819
16820 for (const auto *L : Rec.Lambdas)
16821 Diag(L->getBeginLoc(), D);
16822 }
16823 }
16824
16825 WarnOnPendingNoDerefs(Rec);
16826 HandleImmediateInvocations(*this, Rec);
16827
16828 // Warn on any volatile-qualified simple-assignments that are not discarded-
16829 // value expressions nor unevaluated operands (those cases get removed from
16830 // this list by CheckUnusedVolatileAssignment).
16831 for (auto *BO : Rec.VolatileAssignmentLHSs)
16832 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16833 << BO->getType();
16834
16835 // When are coming out of an unevaluated context, clear out any
16836 // temporaries that we may have created as part of the evaluation of
16837 // the expression in that context: they aren't relevant because they
16838 // will never be constructed.
16839 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16840 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16841 ExprCleanupObjects.end());
16842 Cleanup = Rec.ParentCleanup;
16843 CleanupVarDeclMarking();
16844 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16845 // Otherwise, merge the contexts together.
16846 } else {
16847 Cleanup.mergeFrom(Rec.ParentCleanup);
16848 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16849 Rec.SavedMaybeODRUseExprs.end());
16850 }
16851
16852 // Pop the current expression evaluation context off the stack.
16853 ExprEvalContexts.pop_back();
16854
16855 // The global expression evaluation context record is never popped.
16856 ExprEvalContexts.back().NumTypos += NumTypos;
16857}
16858
16859void Sema::DiscardCleanupsInEvaluationContext() {
16860 ExprCleanupObjects.erase(
16861 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16862 ExprCleanupObjects.end());
16863 Cleanup.reset();
16864 MaybeODRUseExprs.clear();
16865}
16866
16867ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16868 ExprResult Result = CheckPlaceholderExpr(E);
16869 if (Result.isInvalid())
16870 return ExprError();
16871 E = Result.get();
16872 if (!E->getType()->isVariablyModifiedType())
16873 return E;
16874 return TransformToPotentiallyEvaluated(E);
16875}
16876
16877/// Are we in a context that is potentially constant evaluated per C++20
16878/// [expr.const]p12?
16879static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16880 /// C++2a [expr.const]p12:
16881 // An expression or conversion is potentially constant evaluated if it is
16882 switch (SemaRef.ExprEvalContexts.back().Context) {
16883 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16884 // -- a manifestly constant-evaluated expression,
16885 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16886 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16887 case Sema::ExpressionEvaluationContext::DiscardedStatement:
16888 // -- a potentially-evaluated expression,
16889 case Sema::ExpressionEvaluationContext::UnevaluatedList:
16890 // -- an immediate subexpression of a braced-init-list,
16891
16892 // -- [FIXME] an expression of the form & cast-expression that occurs
16893 // within a templated entity
16894 // -- a subexpression of one of the above that is not a subexpression of
16895 // a nested unevaluated operand.
16896 return true;
16897
16898 case Sema::ExpressionEvaluationContext::Unevaluated:
16899 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16900 // Expressions in this context are never evaluated.
16901 return false;
16902 }
16903 llvm_unreachable("Invalid context")__builtin_unreachable();
16904}
16905
16906/// Return true if this function has a calling convention that requires mangling
16907/// in the size of the parameter pack.
16908static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16909 // These manglings don't do anything on non-Windows or non-x86 platforms, so
16910 // we don't need parameter type sizes.
16911 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16912 if (!TT.isOSWindows() || !TT.isX86())
16913 return false;
16914
16915 // If this is C++ and this isn't an extern "C" function, parameters do not
16916 // need to be complete. In this case, C++ mangling will apply, which doesn't
16917 // use the size of the parameters.
16918 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16919 return false;
16920
16921 // Stdcall, fastcall, and vectorcall need this special treatment.
16922 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16923 switch (CC) {
16924 case CC_X86StdCall:
16925 case CC_X86FastCall:
16926 case CC_X86VectorCall:
16927 return true;
16928 default:
16929 break;
16930 }
16931 return false;
16932}
16933
16934/// Require that all of the parameter types of function be complete. Normally,
16935/// parameter types are only required to be complete when a function is called
16936/// or defined, but to mangle functions with certain calling conventions, the
16937/// mangler needs to know the size of the parameter list. In this situation,
16938/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16939/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16940/// result in a linker error. Clang doesn't implement this behavior, and instead
16941/// attempts to error at compile time.
16942static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16943 SourceLocation Loc) {
16944 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16945 FunctionDecl *FD;
16946 ParmVarDecl *Param;
16947
16948 public:
16949 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16950 : FD(FD), Param(Param) {}
16951
16952 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16953 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16954 StringRef CCName;
16955 switch (CC) {
16956 case CC_X86StdCall:
16957 CCName = "stdcall";
16958 break;
16959 case CC_X86FastCall:
16960 CCName = "fastcall";
16961 break;
16962 case CC_X86VectorCall:
16963 CCName = "vectorcall";
16964 break;
16965 default:
16966 llvm_unreachable("CC does not need mangling")__builtin_unreachable();
16967 }
16968
16969 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16970 << Param->getDeclName() << FD->getDeclName() << CCName;
16971 }
16972 };
16973
16974 for (ParmVarDecl *Param : FD->parameters()) {
16975 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16976 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16977 }
16978}
16979
16980namespace {
16981enum class OdrUseContext {
16982 /// Declarations in this context are not odr-used.
16983 None,
16984 /// Declarations in this context are formally odr-used, but this is a
16985 /// dependent context.
16986 Dependent,
16987 /// Declarations in this context are odr-used but not actually used (yet).
16988 FormallyOdrUsed,
16989 /// Declarations in this context are used.
16990 Used
16991};
16992}
16993
16994/// Are we within a context in which references to resolved functions or to
16995/// variables result in odr-use?
16996static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16997 OdrUseContext Result;
16998
16999 switch (SemaRef.ExprEvalContexts.back().Context) {
17000 case Sema::ExpressionEvaluationContext::Unevaluated:
17001 case Sema::ExpressionEvaluationContext::UnevaluatedList:
17002 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17003 return OdrUseContext::None;
17004
17005 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17006 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17007 Result = OdrUseContext::Used;
17008 break;
17009
17010 case Sema::ExpressionEvaluationContext::DiscardedStatement:
17011 Result = OdrUseContext::FormallyOdrUsed;
17012 break;
17013
17014 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17015 // A default argument formally results in odr-use, but doesn't actually
17016 // result in a use in any real sense until it itself is used.
17017 Result = OdrUseContext::FormallyOdrUsed;
17018 break;
17019 }
17020
17021 if (SemaRef.CurContext->isDependentContext())
17022 return OdrUseContext::Dependent;
17023
17024 return Result;
17025}
17026
17027static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17028 if (!Func->isConstexpr())
17029 return false;
17030
17031 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17032 return true;
17033 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17034 return CCD && CCD->getInheritedConstructor();
17035}
17036
17037/// Mark a function referenced, and check whether it is odr-used
17038/// (C++ [basic.def.odr]p2, C99 6.9p3)
17039void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17040 bool MightBeOdrUse) {
17041 assert(Func && "No function?")((void)0);
17042
17043 Func->setReferenced();
17044
17045 // Recursive functions aren't really used until they're used from some other
17046 // context.
17047 bool IsRecursiveCall = CurContext == Func;
17048
17049 // C++11 [basic.def.odr]p3:
17050 // A function whose name appears as a potentially-evaluated expression is
17051 // odr-used if it is the unique lookup result or the selected member of a
17052 // set of overloaded functions [...].
17053 //
17054 // We (incorrectly) mark overload resolution as an unevaluated context, so we
17055 // can just check that here.
17056 OdrUseContext OdrUse =
17057 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17058 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17059 OdrUse = OdrUseContext::FormallyOdrUsed;
17060
17061 // Trivial default constructors and destructors are never actually used.
17062 // FIXME: What about other special members?
17063 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17064 OdrUse == OdrUseContext::Used) {
17065 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17066 if (Constructor->isDefaultConstructor())
17067 OdrUse = OdrUseContext::FormallyOdrUsed;
17068 if (isa<CXXDestructorDecl>(Func))
17069 OdrUse = OdrUseContext::FormallyOdrUsed;
17070 }
17071
17072 // C++20 [expr.const]p12:
17073 // A function [...] is needed for constant evaluation if it is [...] a
17074 // constexpr function that is named by an expression that is potentially
17075 // constant evaluated
17076 bool NeededForConstantEvaluation =
17077 isPotentiallyConstantEvaluatedContext(*this) &&
17078 isImplicitlyDefinableConstexprFunction(Func);
17079
17080 // Determine whether we require a function definition to exist, per
17081 // C++11 [temp.inst]p3:
17082 // Unless a function template specialization has been explicitly
17083 // instantiated or explicitly specialized, the function template
17084 // specialization is implicitly instantiated when the specialization is
17085 // referenced in a context that requires a function definition to exist.
17086 // C++20 [temp.inst]p7:
17087 // The existence of a definition of a [...] function is considered to
17088 // affect the semantics of the program if the [...] function is needed for
17089 // constant evaluation by an expression
17090 // C++20 [basic.def.odr]p10:
17091 // Every program shall contain exactly one definition of every non-inline
17092 // function or variable that is odr-used in that program outside of a
17093 // discarded statement
17094 // C++20 [special]p1:
17095 // The implementation will implicitly define [defaulted special members]
17096 // if they are odr-used or needed for constant evaluation.
17097 //
17098 // Note that we skip the implicit instantiation of templates that are only
17099 // used in unused default arguments or by recursive calls to themselves.
17100 // This is formally non-conforming, but seems reasonable in practice.
17101 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17102 NeededForConstantEvaluation);
17103
17104 // C++14 [temp.expl.spec]p6:
17105 // If a template [...] is explicitly specialized then that specialization
17106 // shall be declared before the first use of that specialization that would
17107 // cause an implicit instantiation to take place, in every translation unit
17108 // in which such a use occurs
17109 if (NeedDefinition &&
17110 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17111 Func->getMemberSpecializationInfo()))
17112 checkSpecializationVisibility(Loc, Func);
17113
17114 if (getLangOpts().CUDA)
17115 CheckCUDACall(Loc, Func);
17116
17117 if (getLangOpts().SYCLIsDevice)
17118 checkSYCLDeviceFunction(Loc, Func);
17119
17120 // If we need a definition, try to create one.
17121 if (NeedDefinition && !Func->getBody()) {
17122 runWithSufficientStackSpace(Loc, [&] {
17123 if (CXXConstructorDecl *Constructor =
17124 dyn_cast<CXXConstructorDecl>(Func)) {
17125 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17126 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17127 if (Constructor->isDefaultConstructor()) {
17128 if (Constructor->isTrivial() &&
17129 !Constructor->hasAttr<DLLExportAttr>())
17130 return;
17131 DefineImplicitDefaultConstructor(Loc, Constructor);
17132 } else if (Constructor->isCopyConstructor()) {
17133 DefineImplicitCopyConstructor(Loc, Constructor);
17134 } else if (Constructor->isMoveConstructor()) {
17135 DefineImplicitMoveConstructor(Loc, Constructor);
17136 }
17137 } else if (Constructor->getInheritedConstructor()) {
17138 DefineInheritingConstructor(Loc, Constructor);
17139 }
17140 } else if (CXXDestructorDecl *Destructor =
17141 dyn_cast<CXXDestructorDecl>(Func)) {
17142 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17143 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17144 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17145 return;
17146 DefineImplicitDestructor(Loc, Destructor);
17147 }
17148 if (Destructor->isVirtual() && getLangOpts().AppleKext)
17149 MarkVTableUsed(Loc, Destructor->getParent());
17150 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17151 if (MethodDecl->isOverloadedOperator() &&
17152 MethodDecl->getOverloadedOperator() == OO_Equal) {
17153 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17154 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17155 if (MethodDecl->isCopyAssignmentOperator())
17156 DefineImplicitCopyAssignment(Loc, MethodDecl);
17157 else if (MethodDecl->isMoveAssignmentOperator())
17158 DefineImplicitMoveAssignment(Loc, MethodDecl);
17159 }
17160 } else if (isa<CXXConversionDecl>(MethodDecl) &&
17161 MethodDecl->getParent()->isLambda()) {
17162 CXXConversionDecl *Conversion =
17163 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17164 if (Conversion->isLambdaToBlockPointerConversion())
17165 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17166 else
17167 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17168 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17169 MarkVTableUsed(Loc, MethodDecl->getParent());
17170 }
17171
17172 if (Func->isDefaulted() && !Func->isDeleted()) {
17173 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17174 if (DCK != DefaultedComparisonKind::None)
17175 DefineDefaultedComparison(Loc, Func, DCK);
17176 }
17177
17178 // Implicit instantiation of function templates and member functions of
17179 // class templates.
17180 if (Func->isImplicitlyInstantiable()) {
17181 TemplateSpecializationKind TSK =
17182 Func->getTemplateSpecializationKindForInstantiation();
17183 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17184 bool FirstInstantiation = PointOfInstantiation.isInvalid();
17185 if (FirstInstantiation) {
17186 PointOfInstantiation = Loc;
17187 if (auto *MSI = Func->getMemberSpecializationInfo())
17188 MSI->setPointOfInstantiation(Loc);
17189 // FIXME: Notify listener.
17190 else
17191 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17192 } else if (TSK != TSK_ImplicitInstantiation) {
17193 // Use the point of use as the point of instantiation, instead of the
17194 // point of explicit instantiation (which we track as the actual point
17195 // of instantiation). This gives better backtraces in diagnostics.
17196 PointOfInstantiation = Loc;
17197 }
17198
17199 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17200 Func->isConstexpr()) {
17201 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17202 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17203 CodeSynthesisContexts.size())
17204 PendingLocalImplicitInstantiations.push_back(
17205 std::make_pair(Func, PointOfInstantiation));
17206 else if (Func->isConstexpr())
17207 // Do not defer instantiations of constexpr functions, to avoid the
17208 // expression evaluator needing to call back into Sema if it sees a
17209 // call to such a function.
17210 InstantiateFunctionDefinition(PointOfInstantiation, Func);
17211 else {
17212 Func->setInstantiationIsPending(true);
17213 PendingInstantiations.push_back(
17214 std::make_pair(Func, PointOfInstantiation));
17215 // Notify the consumer that a function was implicitly instantiated.
17216 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17217 }
17218 }
17219 } else {
17220 // Walk redefinitions, as some of them may be instantiable.
17221 for (auto i : Func->redecls()) {
17222 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17223 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17224 }
17225 }
17226 });
17227 }
17228
17229 // C++14 [except.spec]p17:
17230 // An exception-specification is considered to be needed when:
17231 // - the function is odr-used or, if it appears in an unevaluated operand,
17232 // would be odr-used if the expression were potentially-evaluated;
17233 //
17234 // Note, we do this even if MightBeOdrUse is false. That indicates that the
17235 // function is a pure virtual function we're calling, and in that case the
17236 // function was selected by overload resolution and we need to resolve its
17237 // exception specification for a different reason.
17238 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17239 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17240 ResolveExceptionSpec(Loc, FPT);
17241
17242 // If this is the first "real" use, act on that.
17243 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17244 // Keep track of used but undefined functions.
17245 if (!Func->isDefined()) {
17246 if (mightHaveNonExternalLinkage(Func))
17247 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17248 else if (Func->getMostRecentDecl()->isInlined() &&
17249 !LangOpts.GNUInline &&
17250 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17251 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17252 else if (isExternalWithNoLinkageType(Func))
17253 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17254 }
17255
17256 // Some x86 Windows calling conventions mangle the size of the parameter
17257 // pack into the name. Computing the size of the parameters requires the
17258 // parameter types to be complete. Check that now.
17259 if (funcHasParameterSizeMangling(*this, Func))
17260 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17261
17262 // In the MS C++ ABI, the compiler emits destructor variants where they are
17263 // used. If the destructor is used here but defined elsewhere, mark the
17264 // virtual base destructors referenced. If those virtual base destructors
17265 // are inline, this will ensure they are defined when emitting the complete
17266 // destructor variant. This checking may be redundant if the destructor is
17267 // provided later in this TU.
17268 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17269 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17270 CXXRecordDecl *Parent = Dtor->getParent();
17271 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17272 CheckCompleteDestructorVariant(Loc, Dtor);
17273 }
17274 }
17275
17276 Func->markUsed(Context);
17277 }
17278}
17279
17280/// Directly mark a variable odr-used. Given a choice, prefer to use
17281/// MarkVariableReferenced since it does additional checks and then
17282/// calls MarkVarDeclODRUsed.
17283/// If the variable must be captured:
17284/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17285/// - else capture it in the DeclContext that maps to the
17286/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17287static void
17288MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17289 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17290 // Keep track of used but undefined variables.
17291 // FIXME: We shouldn't suppress this warning for static data members.
17292 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17293 (!Var->isExternallyVisible() || Var->isInline() ||
17294 SemaRef.isExternalWithNoLinkageType(Var)) &&
17295 !(Var->isStaticDataMember() && Var->hasInit())) {
17296 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17297 if (old.isInvalid())
17298 old = Loc;
17299 }
17300 QualType CaptureType, DeclRefType;
17301 if (SemaRef.LangOpts.OpenMP)
17302 SemaRef.tryCaptureOpenMPLambdas(Var);
17303 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17304 /*EllipsisLoc*/ SourceLocation(),
17305 /*BuildAndDiagnose*/ true,
17306 CaptureType, DeclRefType,
17307 FunctionScopeIndexToStopAt);
17308
17309 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) {
17310 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
17311 auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
17312 auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
17313 if (VarTarget == Sema::CVT_Host &&
17314 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
17315 UserTarget == Sema::CFT_Global)) {
17316 // Diagnose ODR-use of host global variables in device functions.
17317 // Reference of device global variables in host functions is allowed
17318 // through shadow variables therefore it is not diagnosed.
17319 if (SemaRef.LangOpts.CUDAIsDevice) {
17320 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
17321 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
17322 SemaRef.targetDiag(Var->getLocation(),
17323 Var->getType().isConstQualified()
17324 ? diag::note_cuda_const_var_unpromoted
17325 : diag::note_cuda_host_var);
17326 }
17327 } else if (VarTarget == Sema::CVT_Device &&
17328 (UserTarget == Sema::CFT_Host ||
17329 UserTarget == Sema::CFT_HostDevice) &&
17330 !Var->hasExternalStorage()) {
17331 // Record a CUDA/HIP device side variable if it is ODR-used
17332 // by host code. This is done conservatively, when the variable is
17333 // referenced in any of the following contexts:
17334 // - a non-function context
17335 // - a host function
17336 // - a host device function
17337 // This makes the ODR-use of the device side variable by host code to
17338 // be visible in the device compilation for the compiler to be able to
17339 // emit template variables instantiated by host code only and to
17340 // externalize the static device side variable ODR-used by host code.
17341 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
17342 }
17343 }
17344
17345 Var->markUsed(SemaRef.Context);
17346}
17347
17348void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17349 SourceLocation Loc,
17350 unsigned CapturingScopeIndex) {
17351 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17352}
17353
17354static void
17355diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17356 ValueDecl *var, DeclContext *DC) {
17357 DeclContext *VarDC = var->getDeclContext();
17358
17359 // If the parameter still belongs to the translation unit, then
17360 // we're actually just using one parameter in the declaration of
17361 // the next.
17362 if (isa<ParmVarDecl>(var) &&
17363 isa<TranslationUnitDecl>(VarDC))
17364 return;
17365
17366 // For C code, don't diagnose about capture if we're not actually in code
17367 // right now; it's impossible to write a non-constant expression outside of
17368 // function context, so we'll get other (more useful) diagnostics later.
17369 //
17370 // For C++, things get a bit more nasty... it would be nice to suppress this
17371 // diagnostic for certain cases like using a local variable in an array bound
17372 // for a member of a local class, but the correct predicate is not obvious.
17373 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17374 return;
17375
17376 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17377 unsigned ContextKind = 3; // unknown
17378 if (isa<CXXMethodDecl>(VarDC) &&
17379 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17380 ContextKind = 2;
17381 } else if (isa<FunctionDecl>(VarDC)) {
17382 ContextKind = 0;
17383 } else if (isa<BlockDecl>(VarDC)) {
17384 ContextKind = 1;
17385 }
17386
17387 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17388 << var << ValueKind << ContextKind << VarDC;
17389 S.Diag(var->getLocation(), diag::note_entity_declared_at)
17390 << var;
17391
17392 // FIXME: Add additional diagnostic info about class etc. which prevents
17393 // capture.
17394}
17395
17396
17397static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17398 bool &SubCapturesAreNested,
17399 QualType &CaptureType,
17400 QualType &DeclRefType) {
17401 // Check whether we've already captured it.
17402 if (CSI->CaptureMap.count(Var)) {
17403 // If we found a capture, any subcaptures are nested.
17404 SubCapturesAreNested = true;
17405
17406 // Retrieve the capture type for this variable.
17407 CaptureType = CSI->getCapture(Var).getCaptureType();
17408
17409 // Compute the type of an expression that refers to this variable.
17410 DeclRefType = CaptureType.getNonReferenceType();
17411
17412 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17413 // are mutable in the sense that user can change their value - they are
17414 // private instances of the captured declarations.
17415 const Capture &Cap = CSI->getCapture(Var);
17416 if (Cap.isCopyCapture() &&
17417 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17418 !(isa<CapturedRegionScopeInfo>(CSI) &&
17419 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17420 DeclRefType.addConst();
17421 return true;
17422 }
17423 return false;
17424}
17425
17426// Only block literals, captured statements, and lambda expressions can
17427// capture; other scopes don't work.
17428static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17429 SourceLocation Loc,
17430 const bool Diagnose, Sema &S) {
17431 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17432 return getLambdaAwareParentOfDeclContext(DC);
17433 else if (Var->hasLocalStorage()) {
17434 if (Diagnose)
17435 diagnoseUncapturableValueReference(S, Loc, Var, DC);
17436 }
17437 return nullptr;
17438}
17439
17440// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17441// certain types of variables (unnamed, variably modified types etc.)
17442// so check for eligibility.
17443static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17444 SourceLocation Loc,
17445 const bool Diagnose, Sema &S) {
17446
17447 bool IsBlock = isa<BlockScopeInfo>(CSI);
17448 bool IsLambda = isa<LambdaScopeInfo>(CSI);
17449
17450 // Lambdas are not allowed to capture unnamed variables
17451 // (e.g. anonymous unions).
17452 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17453 // assuming that's the intent.
17454 if (IsLambda && !Var->getDeclName()) {
17455 if (Diagnose) {
17456 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17457 S.Diag(Var->getLocation(), diag::note_declared_at);
17458 }
17459 return false;
17460 }
17461
17462 // Prohibit variably-modified types in blocks; they're difficult to deal with.
17463 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17464 if (Diagnose) {
17465 S.Diag(Loc, diag::err_ref_vm_type);
17466 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17467 }
17468 return false;
17469 }
17470 // Prohibit structs with flexible array members too.
17471 // We cannot capture what is in the tail end of the struct.
17472 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17473 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17474 if (Diagnose) {
17475 if (IsBlock)
17476 S.Diag(Loc, diag::err_ref_flexarray_type);
17477 else
17478 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17479 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17480 }
17481 return false;
17482 }
17483 }
17484 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17485 // Lambdas and captured statements are not allowed to capture __block
17486 // variables; they don't support the expected semantics.
17487 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17488 if (Diagnose) {
17489 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17490 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17491 }
17492 return false;
17493 }
17494 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17495 if (S.getLangOpts().OpenCL && IsBlock &&
17496 Var->getType()->isBlockPointerType()) {
17497 if (Diagnose)
17498 S.Diag(Loc, diag::err_opencl_block_ref_block);
17499 return false;
17500 }
17501
17502 return true;
17503}
17504
17505// Returns true if the capture by block was successful.
17506static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17507 SourceLocation Loc,
17508 const bool BuildAndDiagnose,
17509 QualType &CaptureType,
17510 QualType &DeclRefType,
17511 const bool Nested,
17512 Sema &S, bool Invalid) {
17513 bool ByRef = false;
17514
17515 // Blocks are not allowed to capture arrays, excepting OpenCL.
17516 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17517 // (decayed to pointers).
17518 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17519 if (BuildAndDiagnose) {
17520 S.Diag(Loc, diag::err_ref_array_type);
17521 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17522 Invalid = true;
17523 } else {
17524 return false;
17525 }
17526 }
17527
17528 // Forbid the block-capture of autoreleasing variables.
17529 if (!Invalid &&
17530 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17531 if (BuildAndDiagnose) {
17532 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17533 << /*block*/ 0;
17534 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17535 Invalid = true;
17536 } else {
17537 return false;
17538 }
17539 }
17540
17541 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17542 if (const auto *PT = CaptureType->getAs<PointerType>()) {
17543 QualType PointeeTy = PT->getPointeeType();
17544
17545 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17546 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17547 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17548 if (BuildAndDiagnose) {
17549 SourceLocation VarLoc = Var->getLocation();
17550 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17551 S.Diag(VarLoc, diag::note_declare_parameter_strong);
17552 }
17553 }
17554 }
17555
17556 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17557 if (HasBlocksAttr || CaptureType->isReferenceType() ||
17558 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17559 // Block capture by reference does not change the capture or
17560 // declaration reference types.
17561 ByRef = true;
17562 } else {
17563 // Block capture by copy introduces 'const'.
17564 CaptureType = CaptureType.getNonReferenceType().withConst();
17565 DeclRefType = CaptureType;
17566 }
17567
17568 // Actually capture the variable.
17569 if (BuildAndDiagnose)
17570 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17571 CaptureType, Invalid);
17572
17573 return !Invalid;
17574}
17575
17576
17577/// Capture the given variable in the captured region.
17578static bool captureInCapturedRegion(
17579 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
17580 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
17581 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
17582 bool IsTopScope, Sema &S, bool Invalid) {
17583 // By default, capture variables by reference.
17584 bool ByRef = true;
17585 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17586 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17587 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17588 // Using an LValue reference type is consistent with Lambdas (see below).
17589 if (S.isOpenMPCapturedDecl(Var)) {
17590 bool HasConst = DeclRefType.isConstQualified();
17591 DeclRefType = DeclRefType.getUnqualifiedType();
17592 // Don't lose diagnostics about assignments to const.
17593 if (HasConst)
17594 DeclRefType.addConst();
17595 }
17596 // Do not capture firstprivates in tasks.
17597 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17598 OMPC_unknown)
17599 return true;
17600 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17601 RSI->OpenMPCaptureLevel);
17602 }
17603
17604 if (ByRef)
17605 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17606 else
17607 CaptureType = DeclRefType;
17608
17609 // Actually capture the variable.
17610 if (BuildAndDiagnose)
17611 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17612 Loc, SourceLocation(), CaptureType, Invalid);
17613
17614 return !Invalid;
17615}
17616
17617/// Capture the given variable in the lambda.
17618static bool captureInLambda(LambdaScopeInfo *LSI,
17619 VarDecl *Var,
17620 SourceLocation Loc,
17621 const bool BuildAndDiagnose,
17622 QualType &CaptureType,
17623 QualType &DeclRefType,
17624 const bool RefersToCapturedVariable,
17625 const Sema::TryCaptureKind Kind,
17626 SourceLocation EllipsisLoc,
17627 const bool IsTopScope,
17628 Sema &S, bool Invalid) {
17629 // Determine whether we are capturing by reference or by value.
17630 bool ByRef = false;
17631 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17632 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17633 } else {
17634 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17635 }
17636
17637 // Compute the type of the field that will capture this variable.
17638 if (ByRef) {
17639 // C++11 [expr.prim.lambda]p15:
17640 // An entity is captured by reference if it is implicitly or
17641 // explicitly captured but not captured by copy. It is
17642 // unspecified whether additional unnamed non-static data
17643 // members are declared in the closure type for entities
17644 // captured by reference.
17645 //
17646 // FIXME: It is not clear whether we want to build an lvalue reference
17647 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17648 // to do the former, while EDG does the latter. Core issue 1249 will
17649 // clarify, but for now we follow GCC because it's a more permissive and
17650 // easily defensible position.
17651 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17652 } else {
17653 // C++11 [expr.prim.lambda]p14:
17654 // For each entity captured by copy, an unnamed non-static
17655 // data member is declared in the closure type. The
17656 // declaration order of these members is unspecified. The type
17657 // of such a data member is the type of the corresponding
17658 // captured entity if the entity is not a reference to an
17659 // object, or the referenced type otherwise. [Note: If the
17660 // captured entity is a reference to a function, the
17661 // corresponding data member is also a reference to a
17662 // function. - end note ]
17663 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17664 if (!RefType->getPointeeType()->isFunctionType())
17665 CaptureType = RefType->getPointeeType();
17666 }
17667
17668 // Forbid the lambda copy-capture of autoreleasing variables.
17669 if (!Invalid &&
17670 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17671 if (BuildAndDiagnose) {
17672 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17673 S.Diag(Var->getLocation(), diag::note_previous_decl)
17674 << Var->getDeclName();
17675 Invalid = true;
17676 } else {
17677 return false;
17678 }
17679 }
17680
17681 // Make sure that by-copy captures are of a complete and non-abstract type.
17682 if (!Invalid && BuildAndDiagnose) {
17683 if (!CaptureType->isDependentType() &&
17684 S.RequireCompleteSizedType(
17685 Loc, CaptureType,
17686 diag::err_capture_of_incomplete_or_sizeless_type,
17687 Var->getDeclName()))
17688 Invalid = true;
17689 else if (S.RequireNonAbstractType(Loc, CaptureType,
17690 diag::err_capture_of_abstract_type))
17691 Invalid = true;
17692 }
17693 }
17694
17695 // Compute the type of a reference to this captured variable.
17696 if (ByRef)
17697 DeclRefType = CaptureType.getNonReferenceType();
17698 else {
17699 // C++ [expr.prim.lambda]p5:
17700 // The closure type for a lambda-expression has a public inline
17701 // function call operator [...]. This function call operator is
17702 // declared const (9.3.1) if and only if the lambda-expression's
17703 // parameter-declaration-clause is not followed by mutable.
17704 DeclRefType = CaptureType.getNonReferenceType();
17705 if (!LSI->Mutable && !CaptureType->isReferenceType())
17706 DeclRefType.addConst();
17707 }
17708
17709 // Add the capture.
17710 if (BuildAndDiagnose)
17711 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17712 Loc, EllipsisLoc, CaptureType, Invalid);
17713
17714 return !Invalid;
17715}
17716
17717static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
17718 // Offer a Copy fix even if the type is dependent.
17719 if (Var->getType()->isDependentType())
17720 return true;
17721 QualType T = Var->getType().getNonReferenceType();
17722 if (T.isTriviallyCopyableType(Context))
17723 return true;
17724 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
17725
17726 if (!(RD = RD->getDefinition()))
17727 return false;
17728 if (RD->hasSimpleCopyConstructor())
17729 return true;
17730 if (RD->hasUserDeclaredCopyConstructor())
17731 for (CXXConstructorDecl *Ctor : RD->ctors())
17732 if (Ctor->isCopyConstructor())
17733 return !Ctor->isDeleted();
17734 }
17735 return false;
17736}
17737
17738/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
17739/// default capture. Fixes may be omitted if they aren't allowed by the
17740/// standard, for example we can't emit a default copy capture fix-it if we
17741/// already explicitly copy capture capture another variable.
17742static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
17743 VarDecl *Var) {
17744 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None)((void)0);
17745 // Don't offer Capture by copy of default capture by copy fixes if Var is
17746 // known not to be copy constructible.
17747 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
17748
17749 SmallString<32> FixBuffer;
17750 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
17751 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
17752 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
17753 if (ShouldOfferCopyFix) {
17754 // Offer fixes to insert an explicit capture for the variable.
17755 // [] -> [VarName]
17756 // [OtherCapture] -> [OtherCapture, VarName]
17757 FixBuffer.assign({Separator, Var->getName()});
17758 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17759 << Var << /*value*/ 0
17760 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17761 }
17762 // As above but capture by reference.
17763 FixBuffer.assign({Separator, "&", Var->getName()});
17764 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17765 << Var << /*reference*/ 1
17766 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17767 }
17768
17769 // Only try to offer default capture if there are no captures excluding this
17770 // and init captures.
17771 // [this]: OK.
17772 // [X = Y]: OK.
17773 // [&A, &B]: Don't offer.
17774 // [A, B]: Don't offer.
17775 if (llvm::any_of(LSI->Captures, [](Capture &C) {
17776 return !C.isThisCapture() && !C.isInitCapture();
17777 }))
17778 return;
17779
17780 // The default capture specifiers, '=' or '&', must appear first in the
17781 // capture body.
17782 SourceLocation DefaultInsertLoc =
17783 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
17784
17785 if (ShouldOfferCopyFix) {
17786 bool CanDefaultCopyCapture = true;
17787 // [=, *this] OK since c++17
17788 // [=, this] OK since c++20
17789 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
17790 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
17791 ? LSI->getCXXThisCapture().isCopyCapture()
17792 : false;
17793 // We can't use default capture by copy if any captures already specified
17794 // capture by copy.
17795 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
17796 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
17797 })) {
17798 FixBuffer.assign({"=", Separator});
17799 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17800 << /*value*/ 0
17801 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17802 }
17803 }
17804
17805 // We can't use default capture by reference if any captures already specified
17806 // capture by reference.
17807 if (llvm::none_of(LSI->Captures, [](Capture &C) {
17808 return !C.isInitCapture() && C.isReferenceCapture() &&
17809 !C.isThisCapture();
17810 })) {
17811 FixBuffer.assign({"&", Separator});
17812 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17813 << /*reference*/ 1
17814 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17815 }
17816}
17817
17818bool Sema::tryCaptureVariable(
17819 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17820 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17821 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17822 // An init-capture is notionally from the context surrounding its
17823 // declaration, but its parent DC is the lambda class.
17824 DeclContext *VarDC = Var->getDeclContext();
17825 if (Var->isInitCapture())
17826 VarDC = VarDC->getParent();
17827
17828 DeclContext *DC = CurContext;
17829 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17830 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17831 // We need to sync up the Declaration Context with the
17832 // FunctionScopeIndexToStopAt
17833 if (FunctionScopeIndexToStopAt) {
17834 unsigned FSIndex = FunctionScopes.size() - 1;
17835 while (FSIndex != MaxFunctionScopesIndex) {
17836 DC = getLambdaAwareParentOfDeclContext(DC);
17837 --FSIndex;
17838 }
17839 }
17840
17841
17842 // If the variable is declared in the current context, there is no need to
17843 // capture it.
17844 if (VarDC == DC) return true;
17845
17846 // Capture global variables if it is required to use private copy of this
17847 // variable.
17848 bool IsGlobal = !Var->hasLocalStorage();
17849 if (IsGlobal &&
17850 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17851 MaxFunctionScopesIndex)))
17852 return true;
17853 Var = Var->getCanonicalDecl();
17854
17855 // Walk up the stack to determine whether we can capture the variable,
17856 // performing the "simple" checks that don't depend on type. We stop when
17857 // we've either hit the declared scope of the variable or find an existing
17858 // capture of that variable. We start from the innermost capturing-entity
17859 // (the DC) and ensure that all intervening capturing-entities
17860 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17861 // declcontext can either capture the variable or have already captured
17862 // the variable.
17863 CaptureType = Var->getType();
17864 DeclRefType = CaptureType.getNonReferenceType();
17865 bool Nested = false;
17866 bool Explicit = (Kind != TryCapture_Implicit);
17867 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17868 do {
17869 // Only block literals, captured statements, and lambda expressions can
17870 // capture; other scopes don't work.
17871 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17872 ExprLoc,
17873 BuildAndDiagnose,
17874 *this);
17875 // We need to check for the parent *first* because, if we *have*
17876 // private-captured a global variable, we need to recursively capture it in
17877 // intermediate blocks, lambdas, etc.
17878 if (!ParentDC) {
17879 if (IsGlobal) {
17880 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17881 break;
17882 }
17883 return true;
17884 }
17885
17886 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
17887 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17888
17889
17890 // Check whether we've already captured it.
17891 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17892 DeclRefType)) {
17893 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17894 break;
17895 }
17896 // If we are instantiating a generic lambda call operator body,
17897 // we do not want to capture new variables. What was captured
17898 // during either a lambdas transformation or initial parsing
17899 // should be used.
17900 if (isGenericLambdaCallOperatorSpecialization(DC)) {
17901 if (BuildAndDiagnose) {
17902 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17903 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17904 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17905 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17906 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17907 buildLambdaCaptureFixit(*this, LSI, Var);
17908 } else
17909 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17910 }
17911 return true;
17912 }
17913
17914 // Try to capture variable-length arrays types.
17915 if (Var->getType()->isVariablyModifiedType()) {
17916 // We're going to walk down into the type and look for VLA
17917 // expressions.
17918 QualType QTy = Var->getType();
17919 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17920 QTy = PVD->getOriginalType();
17921 captureVariablyModifiedType(Context, QTy, CSI);
17922 }
17923
17924 if (getLangOpts().OpenMP) {
17925 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17926 // OpenMP private variables should not be captured in outer scope, so
17927 // just break here. Similarly, global variables that are captured in a
17928 // target region should not be captured outside the scope of the region.
17929 if (RSI->CapRegionKind == CR_OpenMP) {
17930 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17931 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17932 // If the variable is private (i.e. not captured) and has variably
17933 // modified type, we still need to capture the type for correct
17934 // codegen in all regions, associated with the construct. Currently,
17935 // it is captured in the innermost captured region only.
17936 if (IsOpenMPPrivateDecl != OMPC_unknown &&
17937 Var->getType()->isVariablyModifiedType()) {
17938 QualType QTy = Var->getType();
17939 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17940 QTy = PVD->getOriginalType();
17941 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17942 I < E; ++I) {
17943 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17944 FunctionScopes[FunctionScopesIndex - I]);
17945 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&((void)0)
17946 "Wrong number of captured regions associated with the "((void)0)
17947 "OpenMP construct.")((void)0);
17948 captureVariablyModifiedType(Context, QTy, OuterRSI);
17949 }
17950 }
17951 bool IsTargetCap =
17952 IsOpenMPPrivateDecl != OMPC_private &&
17953 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17954 RSI->OpenMPCaptureLevel);
17955 // Do not capture global if it is not privatized in outer regions.
17956 bool IsGlobalCap =
17957 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17958 RSI->OpenMPCaptureLevel);
17959
17960 // When we detect target captures we are looking from inside the
17961 // target region, therefore we need to propagate the capture from the
17962 // enclosing region. Therefore, the capture is not initially nested.
17963 if (IsTargetCap)
17964 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17965
17966 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17967 (IsGlobal && !IsGlobalCap)) {
17968 Nested = !IsTargetCap;
17969 bool HasConst = DeclRefType.isConstQualified();
17970 DeclRefType = DeclRefType.getUnqualifiedType();
17971 // Don't lose diagnostics about assignments to const.
17972 if (HasConst)
17973 DeclRefType.addConst();
17974 CaptureType = Context.getLValueReferenceType(DeclRefType);
17975 break;
17976 }
17977 }
17978 }
17979 }
17980 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17981 // No capture-default, and this is not an explicit capture
17982 // so cannot capture this variable.
17983 if (BuildAndDiagnose) {
17984 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17985 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17986 auto *LSI = cast<LambdaScopeInfo>(CSI);
17987 if (LSI->Lambda) {
17988 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17989 buildLambdaCaptureFixit(*this, LSI, Var);
17990 }
17991 // FIXME: If we error out because an outer lambda can not implicitly
17992 // capture a variable that an inner lambda explicitly captures, we
17993 // should have the inner lambda do the explicit capture - because
17994 // it makes for cleaner diagnostics later. This would purely be done
17995 // so that the diagnostic does not misleadingly claim that a variable
17996 // can not be captured by a lambda implicitly even though it is captured
17997 // explicitly. Suggestion:
17998 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17999 // at the function head
18000 // - cache the StartingDeclContext - this must be a lambda
18001 // - captureInLambda in the innermost lambda the variable.
18002 }
18003 return true;
18004 }
18005
18006 FunctionScopesIndex--;
18007 DC = ParentDC;
18008 Explicit = false;
18009 } while (!VarDC->Equals(DC));
18010
18011 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18012 // computing the type of the capture at each step, checking type-specific
18013 // requirements, and adding captures if requested.
18014 // If the variable had already been captured previously, we start capturing
18015 // at the lambda nested within that one.
18016 bool Invalid = false;
18017 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18018 ++I) {
18019 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18020
18021 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18022 // certain types of variables (unnamed, variably modified types etc.)
18023 // so check for eligibility.
18024 if (!Invalid)
18025 Invalid =
18026 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18027
18028 // After encountering an error, if we're actually supposed to capture, keep
18029 // capturing in nested contexts to suppress any follow-on diagnostics.
18030 if (Invalid && !BuildAndDiagnose)
18031 return true;
18032
18033 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18034 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18035 DeclRefType, Nested, *this, Invalid);
18036 Nested = true;
18037 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18038 Invalid = !captureInCapturedRegion(
18039 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18040 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18041 Nested = true;
18042 } else {
18043 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18044 Invalid =
18045 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18046 DeclRefType, Nested, Kind, EllipsisLoc,
18047 /*IsTopScope*/ I == N - 1, *this, Invalid);
18048 Nested = true;
18049 }
18050
18051 if (Invalid && !BuildAndDiagnose)
18052 return true;
18053 }
18054 return Invalid;
18055}
18056
18057bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18058 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18059 QualType CaptureType;
18060 QualType DeclRefType;
18061 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18062 /*BuildAndDiagnose=*/true, CaptureType,
18063 DeclRefType, nullptr);
18064}
18065
18066bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18067 QualType CaptureType;
18068 QualType DeclRefType;
18069 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18070 /*BuildAndDiagnose=*/false, CaptureType,
18071 DeclRefType, nullptr);
18072}
18073
18074QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18075 QualType CaptureType;
18076 QualType DeclRefType;
18077
18078 // Determine whether we can capture this variable.
18079 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18080 /*BuildAndDiagnose=*/false, CaptureType,
18081 DeclRefType, nullptr))
18082 return QualType();
18083
18084 return DeclRefType;
18085}
18086
18087namespace {
18088// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18089// The produced TemplateArgumentListInfo* points to data stored within this
18090// object, so should only be used in contexts where the pointer will not be
18091// used after the CopiedTemplateArgs object is destroyed.
18092class CopiedTemplateArgs {
18093 bool HasArgs;
18094 TemplateArgumentListInfo TemplateArgStorage;
18095public:
18096 template<typename RefExpr>
18097 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18098 if (HasArgs)
18099 E->copyTemplateArgumentsInto(TemplateArgStorage);
18100 }
18101 operator TemplateArgumentListInfo*()
18102#ifdef __has_cpp_attribute
18103#if0 __has_cpp_attribute(clang::lifetimebound)1
18104 [[clang::lifetimebound]]
18105#endif
18106#endif
18107 {
18108 return HasArgs ? &TemplateArgStorage : nullptr;
18109 }
18110};
18111}
18112
18113/// Walk the set of potential results of an expression and mark them all as
18114/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18115///
18116/// \return A new expression if we found any potential results, ExprEmpty() if
18117/// not, and ExprError() if we diagnosed an error.
18118static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18119 NonOdrUseReason NOUR) {
18120 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18121 // an object that satisfies the requirements for appearing in a
18122 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18123 // is immediately applied." This function handles the lvalue-to-rvalue
18124 // conversion part.
18125 //
18126 // If we encounter a node that claims to be an odr-use but shouldn't be, we
18127 // transform it into the relevant kind of non-odr-use node and rebuild the
18128 // tree of nodes leading to it.
18129 //
18130 // This is a mini-TreeTransform that only transforms a restricted subset of
18131 // nodes (and only certain operands of them).
18132
18133 // Rebuild a subexpression.
18134 auto Rebuild = [&](Expr *Sub) {
18135 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18136 };
18137
18138 // Check whether a potential result satisfies the requirements of NOUR.
18139 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18140 // Any entity other than a VarDecl is always odr-used whenever it's named
18141 // in a potentially-evaluated expression.
18142 auto *VD = dyn_cast<VarDecl>(D);
18143 if (!VD)
18144 return true;
18145
18146 // C++2a [basic.def.odr]p4:
18147 // A variable x whose name appears as a potentially-evalauted expression
18148 // e is odr-used by e unless
18149 // -- x is a reference that is usable in constant expressions, or
18150 // -- x is a variable of non-reference type that is usable in constant
18151 // expressions and has no mutable subobjects, and e is an element of
18152 // the set of potential results of an expression of
18153 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
18154 // conversion is applied, or
18155 // -- x is a variable of non-reference type, and e is an element of the
18156 // set of potential results of a discarded-value expression to which
18157 // the lvalue-to-rvalue conversion is not applied
18158 //
18159 // We check the first bullet and the "potentially-evaluated" condition in
18160 // BuildDeclRefExpr. We check the type requirements in the second bullet
18161 // in CheckLValueToRValueConversionOperand below.
18162 switch (NOUR) {
18163 case NOUR_None:
18164 case NOUR_Unevaluated:
18165 llvm_unreachable("unexpected non-odr-use-reason")__builtin_unreachable();
18166
18167 case NOUR_Constant:
18168 // Constant references were handled when they were built.
18169 if (VD->getType()->isReferenceType())
18170 return true;
18171 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18172 if (RD->hasMutableFields())
18173 return true;
18174 if (!VD->isUsableInConstantExpressions(S.Context))
18175 return true;
18176 break;
18177
18178 case NOUR_Discarded:
18179 if (VD->getType()->isReferenceType())
18180 return true;
18181 break;
18182 }
18183 return false;
18184 };
18185
18186 // Mark that this expression does not constitute an odr-use.
18187 auto MarkNotOdrUsed = [&] {
18188 S.MaybeODRUseExprs.remove(E);
18189 if (LambdaScopeInfo *LSI = S.getCurLambda())
18190 LSI->markVariableExprAsNonODRUsed(E);
18191 };
18192
18193 // C++2a [basic.def.odr]p2:
18194 // The set of potential results of an expression e is defined as follows:
18195 switch (E->getStmtClass()) {
18196 // -- If e is an id-expression, ...
18197 case Expr::DeclRefExprClass: {
18198 auto *DRE = cast<DeclRefExpr>(E);
18199 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18200 break;
18201
18202 // Rebuild as a non-odr-use DeclRefExpr.
18203 MarkNotOdrUsed();
18204 return DeclRefExpr::Create(
18205 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18206 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18207 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18208 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18209 }
18210
18211 case Expr::FunctionParmPackExprClass: {
18212 auto *FPPE = cast<FunctionParmPackExpr>(E);
18213 // If any of the declarations in the pack is odr-used, then the expression
18214 // as a whole constitutes an odr-use.
18215 for (VarDecl *D : *FPPE)
18216 if (IsPotentialResultOdrUsed(D))
18217 return ExprEmpty();
18218
18219 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18220 // nothing cares about whether we marked this as an odr-use, but it might
18221 // be useful for non-compiler tools.
18222 MarkNotOdrUsed();
18223 break;
18224 }
18225
18226 // -- If e is a subscripting operation with an array operand...
18227 case Expr::ArraySubscriptExprClass: {
18228 auto *ASE = cast<ArraySubscriptExpr>(E);
18229 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18230 if (!OldBase->getType()->isArrayType())
18231 break;
18232 ExprResult Base = Rebuild(OldBase);
18233 if (!Base.isUsable())
18234 return Base;
18235 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18236 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18237 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18238 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
18239 ASE->getRBracketLoc());
18240 }
18241
18242 case Expr::MemberExprClass: {
18243 auto *ME = cast<MemberExpr>(E);
18244 // -- If e is a class member access expression [...] naming a non-static
18245 // data member...
18246 if (isa<FieldDecl>(ME->getMemberDecl())) {
18247 ExprResult Base = Rebuild(ME->getBase());
18248 if (!Base.isUsable())
18249 return Base;
18250 return MemberExpr::Create(
18251 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
18252 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
18253 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
18254 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
18255 ME->getObjectKind(), ME->isNonOdrUse());
18256 }
18257
18258 if (ME->getMemberDecl()->isCXXInstanceMember())
18259 break;
18260
18261 // -- If e is a class member access expression naming a static data member,
18262 // ...
18263 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
18264 break;
18265
18266 // Rebuild as a non-odr-use MemberExpr.
18267 MarkNotOdrUsed();
18268 return MemberExpr::Create(
18269 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
18270 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
18271 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
18272 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
18273 return ExprEmpty();
18274 }
18275
18276 case Expr::BinaryOperatorClass: {
18277 auto *BO = cast<BinaryOperator>(E);
18278 Expr *LHS = BO->getLHS();
18279 Expr *RHS = BO->getRHS();
18280 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
18281 if (BO->getOpcode() == BO_PtrMemD) {
18282 ExprResult Sub = Rebuild(LHS);
18283 if (!Sub.isUsable())
18284 return Sub;
18285 LHS = Sub.get();
18286 // -- If e is a comma expression, ...
18287 } else if (BO->getOpcode() == BO_Comma) {
18288 ExprResult Sub = Rebuild(RHS);
18289 if (!Sub.isUsable())
18290 return Sub;
18291 RHS = Sub.get();
18292 } else {
18293 break;
18294 }
18295 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18296 LHS, RHS);
18297 }
18298
18299 // -- If e has the form (e1)...
18300 case Expr::ParenExprClass: {
18301 auto *PE = cast<ParenExpr>(E);
18302 ExprResult Sub = Rebuild(PE->getSubExpr());
18303 if (!Sub.isUsable())
18304 return Sub;
18305 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18306 }
18307
18308 // -- If e is a glvalue conditional expression, ...
18309 // We don't apply this to a binary conditional operator. FIXME: Should we?
18310 case Expr::ConditionalOperatorClass: {
18311 auto *CO = cast<ConditionalOperator>(E);
18312 ExprResult LHS = Rebuild(CO->getLHS());
18313 if (LHS.isInvalid())
18314 return ExprError();
18315 ExprResult RHS = Rebuild(CO->getRHS());
18316 if (RHS.isInvalid())
18317 return ExprError();
18318 if (!LHS.isUsable() && !RHS.isUsable())
18319 return ExprEmpty();
18320 if (!LHS.isUsable())
18321 LHS = CO->getLHS();
18322 if (!RHS.isUsable())
18323 RHS = CO->getRHS();
18324 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18325 CO->getCond(), LHS.get(), RHS.get());
18326 }
18327
18328 // [Clang extension]
18329 // -- If e has the form __extension__ e1...
18330 case Expr::UnaryOperatorClass: {
18331 auto *UO = cast<UnaryOperator>(E);
18332 if (UO->getOpcode() != UO_Extension)
18333 break;
18334 ExprResult Sub = Rebuild(UO->getSubExpr());
18335 if (!Sub.isUsable())
18336 return Sub;
18337 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18338 Sub.get());
18339 }
18340
18341 // [Clang extension]
18342 // -- If e has the form _Generic(...), the set of potential results is the
18343 // union of the sets of potential results of the associated expressions.
18344 case Expr::GenericSelectionExprClass: {
18345 auto *GSE = cast<GenericSelectionExpr>(E);
18346
18347 SmallVector<Expr *, 4> AssocExprs;
18348 bool AnyChanged = false;
18349 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18350 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18351 if (AssocExpr.isInvalid())
18352 return ExprError();
18353 if (AssocExpr.isUsable()) {
18354 AssocExprs.push_back(AssocExpr.get());
18355 AnyChanged = true;
18356 } else {
18357 AssocExprs.push_back(OrigAssocExpr);
18358 }
18359 }
18360
18361 return AnyChanged ? S.CreateGenericSelectionExpr(
18362 GSE->getGenericLoc(), GSE->getDefaultLoc(),
18363 GSE->getRParenLoc(), GSE->getControllingExpr(),
18364 GSE->getAssocTypeSourceInfos(), AssocExprs)
18365 : ExprEmpty();
18366 }
18367
18368 // [Clang extension]
18369 // -- If e has the form __builtin_choose_expr(...), the set of potential
18370 // results is the union of the sets of potential results of the
18371 // second and third subexpressions.
18372 case Expr::ChooseExprClass: {
18373 auto *CE = cast<ChooseExpr>(E);
18374
18375 ExprResult LHS = Rebuild(CE->getLHS());
18376 if (LHS.isInvalid())
18377 return ExprError();
18378
18379 ExprResult RHS = Rebuild(CE->getLHS());
18380 if (RHS.isInvalid())
18381 return ExprError();
18382
18383 if (!LHS.get() && !RHS.get())
18384 return ExprEmpty();
18385 if (!LHS.isUsable())
18386 LHS = CE->getLHS();
18387 if (!RHS.isUsable())
18388 RHS = CE->getRHS();
18389
18390 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18391 RHS.get(), CE->getRParenLoc());
18392 }
18393
18394 // Step through non-syntactic nodes.
18395 case Expr::ConstantExprClass: {
18396 auto *CE = cast<ConstantExpr>(E);
18397 ExprResult Sub = Rebuild(CE->getSubExpr());
18398 if (!Sub.isUsable())
18399 return Sub;
18400 return ConstantExpr::Create(S.Context, Sub.get());
18401 }
18402
18403 // We could mostly rely on the recursive rebuilding to rebuild implicit
18404 // casts, but not at the top level, so rebuild them here.
18405 case Expr::ImplicitCastExprClass: {
18406 auto *ICE = cast<ImplicitCastExpr>(E);
18407 // Only step through the narrow set of cast kinds we expect to encounter.
18408 // Anything else suggests we've left the region in which potential results
18409 // can be found.
18410 switch (ICE->getCastKind()) {
18411 case CK_NoOp:
18412 case CK_DerivedToBase:
18413 case CK_UncheckedDerivedToBase: {
18414 ExprResult Sub = Rebuild(ICE->getSubExpr());
18415 if (!Sub.isUsable())
18416 return Sub;
18417 CXXCastPath Path(ICE->path());
18418 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18419 ICE->getValueKind(), &Path);
18420 }
18421
18422 default:
18423 break;
18424 }
18425 break;
18426 }
18427
18428 default:
18429 break;
18430 }
18431
18432 // Can't traverse through this node. Nothing to do.
18433 return ExprEmpty();
18434}
18435
18436ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18437 // Check whether the operand is or contains an object of non-trivial C union
18438 // type.
18439 if (E->getType().isVolatileQualified() &&
18440 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18441 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18442 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18443 Sema::NTCUC_LValueToRValueVolatile,
18444 NTCUK_Destruct|NTCUK_Copy);
18445
18446 // C++2a [basic.def.odr]p4:
18447 // [...] an expression of non-volatile-qualified non-class type to which
18448 // the lvalue-to-rvalue conversion is applied [...]
18449 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18450 return E;
18451
18452 ExprResult Result =
18453 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18454 if (Result.isInvalid())
18455 return ExprError();
18456 return Result.get() ? Result : E;
18457}
18458
18459ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18460 Res = CorrectDelayedTyposInExpr(Res);
18461
18462 if (!Res.isUsable())
18463 return Res;
18464
18465 // If a constant-expression is a reference to a variable where we delay
18466 // deciding whether it is an odr-use, just assume we will apply the
18467 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
18468 // (a non-type template argument), we have special handling anyway.
18469 return CheckLValueToRValueConversionOperand(Res.get());
18470}
18471
18472void Sema::CleanupVarDeclMarking() {
18473 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18474 // call.
18475 MaybeODRUseExprSet LocalMaybeODRUseExprs;
18476 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18477
18478 for (Expr *E : LocalMaybeODRUseExprs) {
18479 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18480 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18481 DRE->getLocation(), *this);
18482 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18483 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18484 *this);
18485 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18486 for (VarDecl *VD : *FP)
18487 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18488 } else {
18489 llvm_unreachable("Unexpected expression")__builtin_unreachable();
18490 }
18491 }
18492
18493 assert(MaybeODRUseExprs.empty() &&((void)0)
18494 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")((void)0);
18495}
18496
18497static void DoMarkVarDeclReferenced(
18498 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
18499 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18500 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||((void)0)
18501 isa<FunctionParmPackExpr>(E)) &&((void)0)
18502 "Invalid Expr argument to DoMarkVarDeclReferenced")((void)0);
18503 Var->setReferenced();
18504
18505 if (Var->isInvalidDecl())
18506 return;
18507
18508 auto *MSI = Var->getMemberSpecializationInfo();
18509 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18510 : Var->getTemplateSpecializationKind();
18511
18512 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18513 bool UsableInConstantExpr =
18514 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18515
18516 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
18517 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
18518 }
18519
18520 // C++20 [expr.const]p12:
18521 // A variable [...] is needed for constant evaluation if it is [...] a
18522 // variable whose name appears as a potentially constant evaluated
18523 // expression that is either a contexpr variable or is of non-volatile
18524 // const-qualified integral type or of reference type
18525 bool NeededForConstantEvaluation =
18526 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18527
18528 bool NeedDefinition =
18529 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18530
18531 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&((void)0)
18532 "Can't instantiate a partial template specialization.")((void)0);
18533
18534 // If this might be a member specialization of a static data member, check
18535 // the specialization is visible. We already did the checks for variable
18536 // template specializations when we created them.
18537 if (NeedDefinition && TSK != TSK_Undeclared &&
18538 !isa<VarTemplateSpecializationDecl>(Var))
18539 SemaRef.checkSpecializationVisibility(Loc, Var);
18540
18541 // Perform implicit instantiation of static data members, static data member
18542 // templates of class templates, and variable template specializations. Delay
18543 // instantiations of variable templates, except for those that could be used
18544 // in a constant expression.
18545 if (NeedDefinition && isTemplateInstantiation(TSK)) {
18546 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18547 // instantiation declaration if a variable is usable in a constant
18548 // expression (among other cases).
18549 bool TryInstantiating =
18550 TSK == TSK_ImplicitInstantiation ||
18551 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18552
18553 if (TryInstantiating) {
18554 SourceLocation PointOfInstantiation =
18555 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18556 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18557 if (FirstInstantiation) {
18558 PointOfInstantiation = Loc;
18559 if (MSI)
18560 MSI->setPointOfInstantiation(PointOfInstantiation);
18561 // FIXME: Notify listener.
18562 else
18563 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18564 }
18565
18566 if (UsableInConstantExpr) {
18567 // Do not defer instantiations of variables that could be used in a
18568 // constant expression.
18569 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18570 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18571 });
18572
18573 // Re-set the member to trigger a recomputation of the dependence bits
18574 // for the expression.
18575 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18576 DRE->setDecl(DRE->getDecl());
18577 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18578 ME->setMemberDecl(ME->getMemberDecl());
18579 } else if (FirstInstantiation ||
18580 isa<VarTemplateSpecializationDecl>(Var)) {
18581 // FIXME: For a specialization of a variable template, we don't
18582 // distinguish between "declaration and type implicitly instantiated"
18583 // and "implicit instantiation of definition requested", so we have
18584 // no direct way to avoid enqueueing the pending instantiation
18585 // multiple times.
18586 SemaRef.PendingInstantiations
18587 .push_back(std::make_pair(Var, PointOfInstantiation));
18588 }
18589 }
18590 }
18591
18592 // C++2a [basic.def.odr]p4:
18593 // A variable x whose name appears as a potentially-evaluated expression e
18594 // is odr-used by e unless
18595 // -- x is a reference that is usable in constant expressions
18596 // -- x is a variable of non-reference type that is usable in constant
18597 // expressions and has no mutable subobjects [FIXME], and e is an
18598 // element of the set of potential results of an expression of
18599 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
18600 // conversion is applied
18601 // -- x is a variable of non-reference type, and e is an element of the set
18602 // of potential results of a discarded-value expression to which the
18603 // lvalue-to-rvalue conversion is not applied [FIXME]
18604 //
18605 // We check the first part of the second bullet here, and
18606 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18607 // FIXME: To get the third bullet right, we need to delay this even for
18608 // variables that are not usable in constant expressions.
18609
18610 // If we already know this isn't an odr-use, there's nothing more to do.
18611 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18612 if (DRE->isNonOdrUse())
18613 return;
18614 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18615 if (ME->isNonOdrUse())
18616 return;
18617
18618 switch (OdrUse) {
18619 case OdrUseContext::None:
18620 assert((!E || isa<FunctionParmPackExpr>(E)) &&((void)0)
18621 "missing non-odr-use marking for unevaluated decl ref")((void)0);
18622 break;
18623
18624 case OdrUseContext::FormallyOdrUsed:
18625 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18626 // behavior.
18627 break;
18628
18629 case OdrUseContext::Used:
18630 // If we might later find that this expression isn't actually an odr-use,
18631 // delay the marking.
18632 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18633 SemaRef.MaybeODRUseExprs.insert(E);
18634 else
18635 MarkVarDeclODRUsed(Var, Loc, SemaRef);
18636 break;
18637
18638 case OdrUseContext::Dependent:
18639 // If this is a dependent context, we don't need to mark variables as
18640 // odr-used, but we may still need to track them for lambda capture.
18641 // FIXME: Do we also need to do this inside dependent typeid expressions
18642 // (which are modeled as unevaluated at this point)?
18643 const bool RefersToEnclosingScope =
18644 (SemaRef.CurContext != Var->getDeclContext() &&
18645 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18646 if (RefersToEnclosingScope) {
18647 LambdaScopeInfo *const LSI =
18648 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18649 if (LSI && (!LSI->CallOperator ||
18650 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18651 // If a variable could potentially be odr-used, defer marking it so
18652 // until we finish analyzing the full expression for any
18653 // lvalue-to-rvalue
18654 // or discarded value conversions that would obviate odr-use.
18655 // Add it to the list of potential captures that will be analyzed
18656 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18657 // unless the variable is a reference that was initialized by a constant
18658 // expression (this will never need to be captured or odr-used).
18659 //
18660 // FIXME: We can simplify this a lot after implementing P0588R1.
18661 assert(E && "Capture variable should be used in an expression.")((void)0);
18662 if (!Var->getType()->isReferenceType() ||
18663 !Var->isUsableInConstantExpressions(SemaRef.Context))
18664 LSI->addPotentialCapture(E->IgnoreParens());
18665 }
18666 }
18667 break;
18668 }
18669}
18670
18671/// Mark a variable referenced, and check whether it is odr-used
18672/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
18673/// used directly for normal expressions referring to VarDecl.
18674void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18675 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
18676}
18677
18678static void
18679MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
18680 bool MightBeOdrUse,
18681 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18682 if (SemaRef.isInOpenMPDeclareTargetContext())
18683 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18684
18685 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18686 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
18687 return;
18688 }
18689
18690 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18691
18692 // If this is a call to a method via a cast, also mark the method in the
18693 // derived class used in case codegen can devirtualize the call.
18694 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18695 if (!ME)
18696 return;
18697 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18698 if (!MD)
18699 return;
18700 // Only attempt to devirtualize if this is truly a virtual call.
18701 bool IsVirtualCall = MD->isVirtual() &&
18702 ME->performsVirtualDispatch(SemaRef.getLangOpts());
18703 if (!IsVirtualCall)
18704 return;
18705
18706 // If it's possible to devirtualize the call, mark the called function
18707 // referenced.
18708 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18709 ME->getBase(), SemaRef.getLangOpts().AppleKext);
18710 if (DM)
18711 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18712}
18713
18714/// Perform reference-marking and odr-use handling for a DeclRefExpr.
18715///
18716/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
18717/// handled with care if the DeclRefExpr is not newly-created.
18718void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18719 // TODO: update this with DR# once a defect report is filed.
18720 // C++11 defect. The address of a pure member should not be an ODR use, even
18721 // if it's a qualified reference.
18722 bool OdrUse = true;
18723 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18724 if (Method->isVirtual() &&
18725 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18726 OdrUse = false;
18727
18728 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18729 if (!isConstantEvaluated() && FD->isConsteval() &&
18730 !RebuildingImmediateInvocation)
18731 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18732 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
18733 RefsMinusAssignments);
18734}
18735
18736/// Perform reference-marking and odr-use handling for a MemberExpr.
18737void Sema::MarkMemberReferenced(MemberExpr *E) {
18738 // C++11 [basic.def.odr]p2:
18739 // A non-overloaded function whose name appears as a potentially-evaluated
18740 // expression or a member of a set of candidate functions, if selected by
18741 // overload resolution when referred to from a potentially-evaluated
18742 // expression, is odr-used, unless it is a pure virtual function and its
18743 // name is not explicitly qualified.
18744 bool MightBeOdrUse = true;
18745 if (E->performsVirtualDispatch(getLangOpts())) {
18746 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18747 if (Method->isPure())
18748 MightBeOdrUse = false;
18749 }
18750 SourceLocation Loc =
18751 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18752 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
18753 RefsMinusAssignments);
18754}
18755
18756/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18757void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18758 for (VarDecl *VD : *E)
18759 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
18760 RefsMinusAssignments);
18761}
18762
18763/// Perform marking for a reference to an arbitrary declaration. It
18764/// marks the declaration referenced, and performs odr-use checking for
18765/// functions and variables. This method should not be used when building a
18766/// normal expression which refers to a variable.
18767void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18768 bool MightBeOdrUse) {
18769 if (MightBeOdrUse) {
18770 if (auto *VD = dyn_cast<VarDecl>(D)) {
18771 MarkVariableReferenced(Loc, VD);
18772 return;
18773 }
18774 }
18775 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18776 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18777 return;
18778 }
18779 D->setReferenced();
18780}
18781
18782namespace {
18783 // Mark all of the declarations used by a type as referenced.
18784 // FIXME: Not fully implemented yet! We need to have a better understanding
18785 // of when we're entering a context we should not recurse into.
18786 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18787 // TreeTransforms rebuilding the type in a new context. Rather than
18788 // duplicating the TreeTransform logic, we should consider reusing it here.
18789 // Currently that causes problems when rebuilding LambdaExprs.
18790 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18791 Sema &S;
18792 SourceLocation Loc;
18793
18794 public:
18795 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18796
18797 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18798
18799 bool TraverseTemplateArgument(const TemplateArgument &Arg);
18800 };
18801}
18802
18803bool MarkReferencedDecls::TraverseTemplateArgument(
18804 const TemplateArgument &Arg) {
18805 {
18806 // A non-type template argument is a constant-evaluated context.
18807 EnterExpressionEvaluationContext Evaluated(
18808 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18809 if (Arg.getKind() == TemplateArgument::Declaration) {
18810 if (Decl *D = Arg.getAsDecl())
18811 S.MarkAnyDeclReferenced(Loc, D, true);
18812 } else if (Arg.getKind() == TemplateArgument::Expression) {
18813 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18814 }
18815 }
18816
18817 return Inherited::TraverseTemplateArgument(Arg);
18818}
18819
18820void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18821 MarkReferencedDecls Marker(*this, Loc);
18822 Marker.TraverseType(T);
18823}
18824
18825namespace {
18826/// Helper class that marks all of the declarations referenced by
18827/// potentially-evaluated subexpressions as "referenced".
18828class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18829public:
18830 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18831 bool SkipLocalVariables;
18832
18833 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18834 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18835
18836 void visitUsedDecl(SourceLocation Loc, Decl *D) {
18837 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18838 }
18839
18840 void VisitDeclRefExpr(DeclRefExpr *E) {
18841 // If we were asked not to visit local variables, don't.
18842 if (SkipLocalVariables) {
18843 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18844 if (VD->hasLocalStorage())
18845 return;
18846 }
18847
18848 // FIXME: This can trigger the instantiation of the initializer of a
18849 // variable, which can cause the expression to become value-dependent
18850 // or error-dependent. Do we need to propagate the new dependence bits?
18851 S.MarkDeclRefReferenced(E);
18852 }
18853
18854 void VisitMemberExpr(MemberExpr *E) {
18855 S.MarkMemberReferenced(E);
18856 Visit(E->getBase());
18857 }
18858};
18859} // namespace
18860
18861/// Mark any declarations that appear within this expression or any
18862/// potentially-evaluated subexpressions as "referenced".
18863///
18864/// \param SkipLocalVariables If true, don't mark local variables as
18865/// 'referenced'.
18866void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18867 bool SkipLocalVariables) {
18868 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18869}
18870
18871/// Emit a diagnostic that describes an effect on the run-time behavior
18872/// of the program being compiled.
18873///
18874/// This routine emits the given diagnostic when the code currently being
18875/// type-checked is "potentially evaluated", meaning that there is a
18876/// possibility that the code will actually be executable. Code in sizeof()
18877/// expressions, code used only during overload resolution, etc., are not
18878/// potentially evaluated. This routine will suppress such diagnostics or,
18879/// in the absolutely nutty case of potentially potentially evaluated
18880/// expressions (C++ typeid), queue the diagnostic to potentially emit it
18881/// later.
18882///
18883/// This routine should be used for all diagnostics that describe the run-time
18884/// behavior of a program, such as passing a non-POD value through an ellipsis.
18885/// Failure to do so will likely result in spurious diagnostics or failures
18886/// during overload resolution or within sizeof/alignof/typeof/typeid.
18887bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18888 const PartialDiagnostic &PD) {
18889 switch (ExprEvalContexts.back().Context) {
18890 case ExpressionEvaluationContext::Unevaluated:
18891 case ExpressionEvaluationContext::UnevaluatedList:
18892 case ExpressionEvaluationContext::UnevaluatedAbstract:
18893 case ExpressionEvaluationContext::DiscardedStatement:
18894 // The argument will never be evaluated, so don't complain.
18895 break;
18896
18897 case ExpressionEvaluationContext::ConstantEvaluated:
18898 // Relevant diagnostics should be produced by constant evaluation.
18899 break;
18900
18901 case ExpressionEvaluationContext::PotentiallyEvaluated:
18902 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18903 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18904 FunctionScopes.back()->PossiblyUnreachableDiags.
18905 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18906 return true;
18907 }
18908
18909 // The initializer of a constexpr variable or of the first declaration of a
18910 // static data member is not syntactically a constant evaluated constant,
18911 // but nonetheless is always required to be a constant expression, so we
18912 // can skip diagnosing.
18913 // FIXME: Using the mangling context here is a hack.
18914 if (auto *VD = dyn_cast_or_null<VarDecl>(
18915 ExprEvalContexts.back().ManglingContextDecl)) {
18916 if (VD->isConstexpr() ||
18917 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18918 break;
18919 // FIXME: For any other kind of variable, we should build a CFG for its
18920 // initializer and check whether the context in question is reachable.
18921 }
18922
18923 Diag(Loc, PD);
18924 return true;
18925 }
18926
18927 return false;
18928}
18929
18930bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18931 const PartialDiagnostic &PD) {
18932 return DiagRuntimeBehavior(
18933 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18934}
18935
18936bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18937 CallExpr *CE, FunctionDecl *FD) {
18938 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18939 return false;
18940
18941 // If we're inside a decltype's expression, don't check for a valid return
18942 // type or construct temporaries until we know whether this is the last call.
18943 if (ExprEvalContexts.back().ExprContext ==
18944 ExpressionEvaluationContextRecord::EK_Decltype) {
18945 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18946 return false;
18947 }
18948
18949 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18950 FunctionDecl *FD;
18951 CallExpr *CE;
18952
18953 public:
18954 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18955 : FD(FD), CE(CE) { }
18956
18957 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18958 if (!FD) {
18959 S.Diag(Loc, diag::err_call_incomplete_return)
18960 << T << CE->getSourceRange();
18961 return;
18962 }
18963
18964 S.Diag(Loc, diag::err_call_function_incomplete_return)
18965 << CE->getSourceRange() << FD << T;
18966 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18967 << FD->getDeclName();
18968 }
18969 } Diagnoser(FD, CE);
18970
18971 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18972 return true;
18973
18974 return false;
18975}
18976
18977// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18978// will prevent this condition from triggering, which is what we want.
18979void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18980 SourceLocation Loc;
18981
18982 unsigned diagnostic = diag::warn_condition_is_assignment;
18983 bool IsOrAssign = false;
18984
18985 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18986 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18987 return;
18988
18989 IsOrAssign = Op->getOpcode() == BO_OrAssign;
18990
18991 // Greylist some idioms by putting them into a warning subcategory.
18992 if (ObjCMessageExpr *ME
18993 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18994 Selector Sel = ME->getSelector();
18995
18996 // self = [<foo> init...]
18997 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18998 diagnostic = diag::warn_condition_is_idiomatic_assignment;
18999
19000 // <foo> = [<bar> nextObject]
19001 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19002 diagnostic = diag::warn_condition_is_idiomatic_assignment;
19003 }
19004
19005 Loc = Op->getOperatorLoc();
19006 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19007 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19008 return;
19009
19010 IsOrAssign = Op->getOperator() == OO_PipeEqual;
19011 Loc = Op->getOperatorLoc();
19012 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19013 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19014 else {
19015 // Not an assignment.
19016 return;
19017 }
19018
19019 Diag(Loc, diagnostic) << E->getSourceRange();
19020
19021 SourceLocation Open = E->getBeginLoc();
19022 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19023 Diag(Loc, diag::note_condition_assign_silence)
19024 << FixItHint::CreateInsertion(Open, "(")
19025 << FixItHint::CreateInsertion(Close, ")");
19026
19027 if (IsOrAssign)
19028 Diag(Loc, diag::note_condition_or_assign_to_comparison)
19029 << FixItHint::CreateReplacement(Loc, "!=");
19030 else
19031 Diag(Loc, diag::note_condition_assign_to_comparison)
19032 << FixItHint::CreateReplacement(Loc, "==");
19033}
19034
19035/// Redundant parentheses over an equality comparison can indicate
19036/// that the user intended an assignment used as condition.
19037void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19038 // Don't warn if the parens came from a macro.
19039 SourceLocation parenLoc = ParenE->getBeginLoc();
19040 if (parenLoc.isInvalid() || parenLoc.isMacroID())
19041 return;
19042 // Don't warn for dependent expressions.
19043 if (ParenE->isTypeDependent())
19044 return;
19045
19046 Expr *E = ParenE->IgnoreParens();
19047
19048 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19049 if (opE->getOpcode() == BO_EQ &&
19050 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19051 == Expr::MLV_Valid) {
19052 SourceLocation Loc = opE->getOperatorLoc();
19053
19054 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19055 SourceRange ParenERange = ParenE->getSourceRange();
19056 Diag(Loc, diag::note_equality_comparison_silence)
19057 << FixItHint::CreateRemoval(ParenERange.getBegin())
19058 << FixItHint::CreateRemoval(ParenERange.getEnd());
19059 Diag(Loc, diag::note_equality_comparison_to_assign)
19060 << FixItHint::CreateReplacement(Loc, "=");
19061 }
19062}
19063
19064ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19065 bool IsConstexpr) {
19066 DiagnoseAssignmentAsCondition(E);
19067 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19068 DiagnoseEqualityWithExtraParens(parenE);
19069
19070 ExprResult result = CheckPlaceholderExpr(E);
19071 if (result.isInvalid()) return ExprError();
19072 E = result.get();
19073
19074 if (!E->isTypeDependent()) {
19075 if (getLangOpts().CPlusPlus)
19076 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19077
19078 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19079 if (ERes.isInvalid())
19080 return ExprError();
19081 E = ERes.get();
19082
19083 QualType T = E->getType();
19084 if (!T->isScalarType()) { // C99 6.8.4.1p1
19085 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19086 << T << E->getSourceRange();
19087 return ExprError();
19088 }
19089 CheckBoolLikeConversion(E, Loc);
19090 }
19091
19092 return E;
19093}
19094
19095Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19096 Expr *SubExpr, ConditionKind CK) {
19097 // Empty conditions are valid in for-statements.
19098 if (!SubExpr)
19099 return ConditionResult();
19100
19101 ExprResult Cond;
19102 switch (CK) {
19103 case ConditionKind::Boolean:
19104 Cond = CheckBooleanCondition(Loc, SubExpr);
19105 break;
19106
19107 case ConditionKind::ConstexprIf:
19108 Cond = CheckBooleanCondition(Loc, SubExpr, true);
19109 break;
19110
19111 case ConditionKind::Switch:
19112 Cond = CheckSwitchCondition(Loc, SubExpr);
19113 break;
19114 }
19115 if (Cond.isInvalid()) {
19116 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19117 {SubExpr});
19118 if (!Cond.get())
19119 return ConditionError();
19120 }
19121 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19122 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19123 if (!FullExpr.get())
19124 return ConditionError();
19125
19126 return ConditionResult(*this, nullptr, FullExpr,
19127 CK == ConditionKind::ConstexprIf);
19128}
19129
19130namespace {
19131 /// A visitor for rebuilding a call to an __unknown_any expression
19132 /// to have an appropriate type.
19133 struct RebuildUnknownAnyFunction
19134 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19135
19136 Sema &S;
19137
19138 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19139
19140 ExprResult VisitStmt(Stmt *S) {
19141 llvm_unreachable("unexpected statement!")__builtin_unreachable();
19142 }
19143
19144 ExprResult VisitExpr(Expr *E) {
19145 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19146 << E->getSourceRange();
19147 return ExprError();
19148 }
19149
19150 /// Rebuild an expression which simply semantically wraps another
19151 /// expression which it shares the type and value kind of.
19152 template <class T> ExprResult rebuildSugarExpr(T *E) {
19153 ExprResult SubResult = Visit(E->getSubExpr());
19154 if (SubResult.isInvalid()) return ExprError();
19155
19156 Expr *SubExpr = SubResult.get();
19157 E->setSubExpr(SubExpr);
19158 E->setType(SubExpr->getType());
19159 E->setValueKind(SubExpr->getValueKind());
19160 assert(E->getObjectKind() == OK_Ordinary)((void)0);
19161 return E;
19162 }
19163
19164 ExprResult VisitParenExpr(ParenExpr *E) {
19165 return rebuildSugarExpr(E);
19166 }
19167
19168 ExprResult VisitUnaryExtension(UnaryOperator *E) {
19169 return rebuildSugarExpr(E);
19170 }
19171
19172 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19173 ExprResult SubResult = Visit(E->getSubExpr());
19174 if (SubResult.isInvalid()) return ExprError();
19175
19176 Expr *SubExpr = SubResult.get();
19177 E->setSubExpr(SubExpr);
19178 E->setType(S.Context.getPointerType(SubExpr->getType()));
19179 assert(E->isPRValue())((void)0);
19180 assert(E->getObjectKind() == OK_Ordinary)((void)0);
19181 return E;
19182 }
19183
19184 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
19185 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
19186
19187 E->setType(VD->getType());
19188
19189 assert(E->isPRValue())((void)0);
19190 if (S.getLangOpts().CPlusPlus &&
19191 !(isa<CXXMethodDecl>(VD) &&
19192 cast<CXXMethodDecl>(VD)->isInstance()))
19193 E->setValueKind(VK_LValue);
19194
19195 return E;
19196 }
19197
19198 ExprResult VisitMemberExpr(MemberExpr *E) {
19199 return resolveDecl(E, E->getMemberDecl());
19200 }
19201
19202 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19203 return resolveDecl(E, E->getDecl());
19204 }
19205 };
19206}
19207
19208/// Given a function expression of unknown-any type, try to rebuild it
19209/// to have a function type.
19210static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19211 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
19212 if (Result.isInvalid()) return ExprError();
19213 return S.DefaultFunctionArrayConversion(Result.get());
19214}
19215
19216namespace {
19217 /// A visitor for rebuilding an expression of type __unknown_anytype
19218 /// into one which resolves the type directly on the referring
19219 /// expression. Strict preservation of the original source
19220 /// structure is not a goal.
19221 struct RebuildUnknownAnyExpr
19222 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
19223
19224 Sema &S;
19225
19226 /// The current destination type.
19227 QualType DestType;
19228
19229 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
19230 : S(S), DestType(CastType) {}
19231
19232 ExprResult VisitStmt(Stmt *S) {
19233 llvm_unreachable("unexpected statement!")__builtin_unreachable();
19234 }
19235
19236 ExprResult VisitExpr(Expr *E) {
19237 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19238 << E->getSourceRange();
19239 return ExprError();
19240 }
19241
19242 ExprResult VisitCallExpr(CallExpr *E);
19243 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
19244
19245 /// Rebuild an expression which simply semantically wraps another
19246 /// expression which it shares the type and value kind of.
19247 template <class T> ExprResult rebuildSugarExpr(T *E) {
19248 ExprResult SubResult = Visit(E->getSubExpr());
19249 if (SubResult.isInvalid()) return ExprError();
19250 Expr *SubExpr = SubResult.get();
19251 E->setSubExpr(SubExpr);
19252 E->setType(SubExpr->getType());
19253 E->setValueKind(SubExpr->getValueKind());
19254 assert(E->getObjectKind() == OK_Ordinary)((void)0);
19255 return E;
19256 }
19257
19258 ExprResult VisitParenExpr(ParenExpr *E) {
19259 return rebuildSugarExpr(E);
19260 }
19261
19262 ExprResult VisitUnaryExtension(UnaryOperator *E) {
19263 return rebuildSugarExpr(E);
19264 }
19265
19266 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19267 const PointerType *Ptr = DestType->getAs<PointerType>();
19268 if (!Ptr) {
19269 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
19270 << E->getSourceRange();
19271 return ExprError();
19272 }
19273
19274 if (isa<CallExpr>(E->getSubExpr())) {
19275 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
19276 << E->getSourceRange();
19277 return ExprError();
19278 }
19279
19280 assert(E->isPRValue())((void)0);
19281 assert(E->getObjectKind() == OK_Ordinary)((void)0);
19282 E->setType(DestType);
19283
19284 // Build the sub-expression as if it were an object of the pointee type.
19285 DestType = Ptr->getPointeeType();
19286 ExprResult SubResult = Visit(E->getSubExpr());
19287 if (SubResult.isInvalid()) return ExprError();
19288 E->setSubExpr(SubResult.get());
19289 return E;
19290 }
19291
19292 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
19293
19294 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
19295
19296 ExprResult VisitMemberExpr(MemberExpr *E) {
19297 return resolveDecl(E, E->getMemberDecl());
19298 }
19299
19300 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19301 return resolveDecl(E, E->getDecl());
19302 }
19303 };
19304}
19305
19306/// Rebuilds a call expression which yielded __unknown_anytype.
19307ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19308 Expr *CalleeExpr = E->getCallee();
19309
19310 enum FnKind {
19311 FK_MemberFunction,
19312 FK_FunctionPointer,
19313 FK_BlockPointer
19314 };
19315
19316 FnKind Kind;
19317 QualType CalleeType = CalleeExpr->getType();
19318 if (CalleeType == S.Context.BoundMemberTy) {
19319 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))((void)0);
19320 Kind = FK_MemberFunction;
19321 CalleeType = Expr::findBoundMemberType(CalleeExpr);
19322 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19323 CalleeType = Ptr->getPointeeType();
19324 Kind = FK_FunctionPointer;
19325 } else {
19326 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19327 Kind = FK_BlockPointer;
19328 }
19329 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19330
19331 // Verify that this is a legal result type of a function.
19332 if (DestType->isArrayType() || DestType->isFunctionType()) {
19333 unsigned diagID = diag::err_func_returning_array_function;
19334 if (Kind == FK_BlockPointer)
19335 diagID = diag::err_block_returning_array_function;
19336
19337 S.Diag(E->getExprLoc(), diagID)
19338 << DestType->isFunctionType() << DestType;
19339 return ExprError();
19340 }
19341
19342 // Otherwise, go ahead and set DestType as the call's result.
19343 E->setType(DestType.getNonLValueExprType(S.Context));
19344 E->setValueKind(Expr::getValueKindForType(DestType));
19345 assert(E->getObjectKind() == OK_Ordinary)((void)0);
19346
19347 // Rebuild the function type, replacing the result type with DestType.
19348 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19349 if (Proto) {
19350 // __unknown_anytype(...) is a special case used by the debugger when
19351 // it has no idea what a function's signature is.
19352 //
19353 // We want to build this call essentially under the K&R
19354 // unprototyped rules, but making a FunctionNoProtoType in C++
19355 // would foul up all sorts of assumptions. However, we cannot
19356 // simply pass all arguments as variadic arguments, nor can we
19357 // portably just call the function under a non-variadic type; see
19358 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19359 // However, it turns out that in practice it is generally safe to
19360 // call a function declared as "A foo(B,C,D);" under the prototype
19361 // "A foo(B,C,D,...);". The only known exception is with the
19362 // Windows ABI, where any variadic function is implicitly cdecl
19363 // regardless of its normal CC. Therefore we change the parameter
19364 // types to match the types of the arguments.
19365 //
19366 // This is a hack, but it is far superior to moving the
19367 // corresponding target-specific code from IR-gen to Sema/AST.
19368
19369 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19370 SmallVector<QualType, 8> ArgTypes;
19371 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19372 ArgTypes.reserve(E->getNumArgs());
19373 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19374 Expr *Arg = E->getArg(i);
19375 QualType ArgType = Arg->getType();
19376 if (E->isLValue()) {
19377 ArgType = S.Context.getLValueReferenceType(ArgType);
19378 } else if (E->isXValue()) {
19379 ArgType = S.Context.getRValueReferenceType(ArgType);
19380 }
19381 ArgTypes.push_back(ArgType);
19382 }
19383 ParamTypes = ArgTypes;
19384 }
19385 DestType = S.Context.getFunctionType(DestType, ParamTypes,
19386 Proto->getExtProtoInfo());
19387 } else {
19388 DestType = S.Context.getFunctionNoProtoType(DestType,
19389 FnType->getExtInfo());
19390 }
19391
19392 // Rebuild the appropriate pointer-to-function type.
19393 switch (Kind) {
19394 case FK_MemberFunction:
19395 // Nothing to do.
19396 break;
19397
19398 case FK_FunctionPointer:
19399 DestType = S.Context.getPointerType(DestType);
19400 break;
19401
19402 case FK_BlockPointer:
19403 DestType = S.Context.getBlockPointerType(DestType);
19404 break;
19405 }
19406
19407 // Finally, we can recurse.
19408 ExprResult CalleeResult = Visit(CalleeExpr);
19409 if (!CalleeResult.isUsable()) return ExprError();
19410 E->setCallee(CalleeResult.get());
19411
19412 // Bind a temporary if necessary.
19413 return S.MaybeBindToTemporary(E);
19414}
19415
19416ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19417 // Verify that this is a legal result type of a call.
19418 if (DestType->isArrayType() || DestType->isFunctionType()) {
19419 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19420 << DestType->isFunctionType() << DestType;
19421 return ExprError();
19422 }
19423
19424 // Rewrite the method result type if available.
19425 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19426 assert(Method->getReturnType() == S.Context.UnknownAnyTy)((void)0);
19427 Method->setReturnType(DestType);
19428 }
19429
19430 // Change the type of the message.
19431 E->setType(DestType.getNonReferenceType());
19432 E->setValueKind(Expr::getValueKindForType(DestType));
19433
19434 return S.MaybeBindToTemporary(E);
19435}
19436
19437ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19438 // The only case we should ever see here is a function-to-pointer decay.
19439 if (E->getCastKind() == CK_FunctionToPointerDecay) {
19440 assert(E->isPRValue())((void)0);
19441 assert(E->getObjectKind() == OK_Ordinary)((void)0);
19442
19443 E->setType(DestType);
19444
19445 // Rebuild the sub-expression as the pointee (function) type.
19446 DestType = DestType->castAs<PointerType>()->getPointeeType();
19447
19448 ExprResult Result = Visit(E->getSubExpr());
19449 if (!Result.isUsable()) return ExprError();
19450
19451 E->setSubExpr(Result.get());
19452 return E;
19453 } else if (E->getCastKind() == CK_LValueToRValue) {
19454 assert(E->isPRValue())((void)0);
19455 assert(E->getObjectKind() == OK_Ordinary)((void)0);
19456
19457 assert(isa<BlockPointerType>(E->getType()))((void)0);
19458
19459 E->setType(DestType);
19460
19461 // The sub-expression has to be a lvalue reference, so rebuild it as such.
19462 DestType = S.Context.getLValueReferenceType(DestType);
19463
19464 ExprResult Result = Visit(E->getSubExpr());
19465 if (!Result.isUsable()) return ExprError();
19466
19467 E->setSubExpr(Result.get());
19468 return E;
19469 } else {
19470 llvm_unreachable("Unhandled cast type!")__builtin_unreachable();
19471 }
19472}
19473
19474ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19475 ExprValueKind ValueKind = VK_LValue;
19476 QualType Type = DestType;
19477
19478 // We know how to make this work for certain kinds of decls:
19479
19480 // - functions
19481 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19482 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19483 DestType = Ptr->getPointeeType();
19484 ExprResult Result = resolveDecl(E, VD);
19485 if (Result.isInvalid()) return ExprError();
19486 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
19487 VK_PRValue);
19488 }
19489
19490 if (!Type->isFunctionType()) {
19491 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19492 << VD << E->getSourceRange();
19493 return ExprError();
19494 }
19495 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19496 // We must match the FunctionDecl's type to the hack introduced in
19497 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19498 // type. See the lengthy commentary in that routine.
19499 QualType FDT = FD->getType();
19500 const FunctionType *FnType = FDT->castAs<FunctionType>();
19501 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19502 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19503 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19504 SourceLocation Loc = FD->getLocation();
19505 FunctionDecl *NewFD = FunctionDecl::Create(
19506 S.Context, FD->getDeclContext(), Loc, Loc,
19507 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19508 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
19509 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19510
19511 if (FD->getQualifier())
19512 NewFD->setQualifierInfo(FD->getQualifierLoc());
19513
19514 SmallVector<ParmVarDecl*, 16> Params;
19515 for (const auto &AI : FT->param_types()) {
19516 ParmVarDecl *Param =
19517 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19518 Param->setScopeInfo(0, Params.size());
19519 Params.push_back(Param);
19520 }
19521 NewFD->setParams(Params);
19522 DRE->setDecl(NewFD);
19523 VD = DRE->getDecl();
19524 }
19525 }
19526
19527 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19528 if (MD->isInstance()) {
19529 ValueKind = VK_PRValue;
19530 Type = S.Context.BoundMemberTy;
19531 }
19532
19533 // Function references aren't l-values in C.
19534 if (!S.getLangOpts().CPlusPlus)
19535 ValueKind = VK_PRValue;
19536
19537 // - variables
19538 } else if (isa<VarDecl>(VD)) {
19539 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19540 Type = RefTy->getPointeeType();
19541 } else if (Type->isFunctionType()) {
19542 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19543 << VD << E->getSourceRange();
19544 return ExprError();
19545 }
19546
19547 // - nothing else
19548 } else {
19549 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19550 << VD << E->getSourceRange();
19551 return ExprError();
19552 }
19553
19554 // Modifying the declaration like this is friendly to IR-gen but
19555 // also really dangerous.
19556 VD->setType(DestType);
19557 E->setType(Type);
19558 E->setValueKind(ValueKind);
19559 return E;
19560}
19561
19562/// Check a cast of an unknown-any type. We intentionally only
19563/// trigger this for C-style casts.
19564ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19565 Expr *CastExpr, CastKind &CastKind,
19566 ExprValueKind &VK, CXXCastPath &Path) {
19567 // The type we're casting to must be either void or complete.
19568 if (!CastType->isVoidType() &&
19569 RequireCompleteType(TypeRange.getBegin(), CastType,
19570 diag::err_typecheck_cast_to_incomplete))
19571 return ExprError();
19572
19573 // Rewrite the casted expression from scratch.
19574 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19575 if (!result.isUsable()) return ExprError();
19576
19577 CastExpr = result.get();
19578 VK = CastExpr->getValueKind();
19579 CastKind = CK_NoOp;
19580
19581 return CastExpr;
19582}
19583
19584ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19585 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19586}
19587
19588ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19589 Expr *arg, QualType &paramType) {
19590 // If the syntactic form of the argument is not an explicit cast of
19591 // any sort, just do default argument promotion.
19592 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19593 if (!castArg) {
19594 ExprResult result = DefaultArgumentPromotion(arg);
19595 if (result.isInvalid()) return ExprError();
19596 paramType = result.get()->getType();
19597 return result;
19598 }
19599
19600 // Otherwise, use the type that was written in the explicit cast.
19601 assert(!arg->hasPlaceholderType())((void)0);
19602 paramType = castArg->getTypeAsWritten();
19603
19604 // Copy-initialize a parameter of that type.
19605 InitializedEntity entity =
19606 InitializedEntity::InitializeParameter(Context, paramType,
19607 /*consumed*/ false);
19608 return PerformCopyInitialization(entity, callLoc, arg);
19609}
19610
19611static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19612 Expr *orig = E;
19613 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19614 while (true) {
19615 E = E->IgnoreParenImpCasts();
19616 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19617 E = call->getCallee();
19618 diagID = diag::err_uncasted_call_of_unknown_any;
19619 } else {
19620 break;
19621 }
19622 }
19623
19624 SourceLocation loc;
19625 NamedDecl *d;
19626 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19627 loc = ref->getLocation();
19628 d = ref->getDecl();
19629 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19630 loc = mem->getMemberLoc();
19631 d = mem->getMemberDecl();
19632 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19633 diagID = diag::err_uncasted_call_of_unknown_any;
19634 loc = msg->getSelectorStartLoc();
19635 d = msg->getMethodDecl();
19636 if (!d) {
19637 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19638 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19639 << orig->getSourceRange();
19640 return ExprError();
19641 }
19642 } else {
19643 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19644 << E->getSourceRange();
19645 return ExprError();
19646 }
19647
19648 S.Diag(loc, diagID) << d << orig->getSourceRange();
19649
19650 // Never recoverable.
19651 return ExprError();
19652}
19653
19654/// Check for operands with placeholder types and complain if found.
19655/// Returns ExprError() if there was an error and no recovery was possible.
19656ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19657 if (!Context.isDependenceAllowed()) {
19658 // C cannot handle TypoExpr nodes on either side of a binop because it
19659 // doesn't handle dependent types properly, so make sure any TypoExprs have
19660 // been dealt with before checking the operands.
19661 ExprResult Result = CorrectDelayedTyposInExpr(E);
19662 if (!Result.isUsable()) return ExprError();
19663 E = Result.get();
19664 }
19665
19666 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19667 if (!placeholderType) return E;
19668
19669 switch (placeholderType->getKind()) {
19670
19671 // Overloaded expressions.
19672 case BuiltinType::Overload: {
19673 // Try to resolve a single function template specialization.
19674 // This is obligatory.
19675 ExprResult Result = E;
19676 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19677 return Result;
19678
19679 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19680 // leaves Result unchanged on failure.
19681 Result = E;
19682 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19683 return Result;
19684
19685 // If that failed, try to recover with a call.
19686 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19687 /*complain*/ true);
19688 return Result;
19689 }
19690
19691 // Bound member functions.
19692 case BuiltinType::BoundMember: {
19693 ExprResult result = E;
19694 const Expr *BME = E->IgnoreParens();
19695 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19696 // Try to give a nicer diagnostic if it is a bound member that we recognize.
19697 if (isa<CXXPseudoDestructorExpr>(BME)) {
19698 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19699 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19700 if (ME->getMemberNameInfo().getName().getNameKind() ==
19701 DeclarationName::CXXDestructorName)
19702 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19703 }
19704 tryToRecoverWithCall(result, PD,
19705 /*complain*/ true);
19706 return result;
19707 }
19708
19709 // ARC unbridged casts.
19710 case BuiltinType::ARCUnbridgedCast: {
19711 Expr *realCast = stripARCUnbridgedCast(E);
19712 diagnoseARCUnbridgedCast(realCast);
19713 return realCast;
19714 }
19715
19716 // Expressions of unknown type.
19717 case BuiltinType::UnknownAny:
19718 return diagnoseUnknownAnyExpr(*this, E);
19719
19720 // Pseudo-objects.
19721 case BuiltinType::PseudoObject:
19722 return checkPseudoObjectRValue(E);
19723
19724 case BuiltinType::BuiltinFn: {
19725 // Accept __noop without parens by implicitly converting it to a call expr.
19726 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19727 if (DRE) {
19728 auto *FD = cast<FunctionDecl>(DRE->getDecl());
19729 if (FD->getBuiltinID() == Builtin::BI__noop) {
19730 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19731 CK_BuiltinFnToFnPtr)
19732 .get();
19733 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19734 VK_PRValue, SourceLocation(),
19735 FPOptionsOverride());
19736 }
19737 }
19738
19739 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19740 return ExprError();
19741 }
19742
19743 case BuiltinType::IncompleteMatrixIdx:
19744 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19745 ->getRowIdx()
19746 ->getBeginLoc(),
19747 diag::err_matrix_incomplete_index);
19748 return ExprError();
19749
19750 // Expressions of unknown type.
19751 case BuiltinType::OMPArraySection:
19752 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19753 return ExprError();
19754
19755 // Expressions of unknown type.
19756 case BuiltinType::OMPArrayShaping:
19757 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19758
19759 case BuiltinType::OMPIterator:
19760 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19761
19762 // Everything else should be impossible.
19763#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19764 case BuiltinType::Id:
19765#include "clang/Basic/OpenCLImageTypes.def"
19766#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19767 case BuiltinType::Id:
19768#include "clang/Basic/OpenCLExtensionTypes.def"
19769#define SVE_TYPE(Name, Id, SingletonId) \
19770 case BuiltinType::Id:
19771#include "clang/Basic/AArch64SVEACLETypes.def"
19772#define PPC_VECTOR_TYPE(Name, Id, Size) \
19773 case BuiltinType::Id:
19774#include "clang/Basic/PPCTypes.def"
19775#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
19776#include "clang/Basic/RISCVVTypes.def"
19777#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19778#define PLACEHOLDER_TYPE(Id, SingletonId)
19779#include "clang/AST/BuiltinTypes.def"
19780 break;
19781 }
19782
19783 llvm_unreachable("invalid placeholder type!")__builtin_unreachable();
19784}
19785
19786bool Sema::CheckCaseExpression(Expr *E) {
19787 if (E->isTypeDependent())
19788 return true;
19789 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19790 return E->getType()->isIntegralOrEnumerationType();
19791 return false;
19792}
19793
19794/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19795ExprResult
19796Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19797 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&((void)0)
19798 "Unknown Objective-C Boolean value!")((void)0);
19799 QualType BoolT = Context.ObjCBuiltinBoolTy;
19800 if (!Context.getBOOLDecl()) {
19801 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19802 Sema::LookupOrdinaryName);
19803 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19804 NamedDecl *ND = Result.getFoundDecl();
19805 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19806 Context.setBOOLDecl(TD);
19807 }
19808 }
19809 if (Context.getBOOLDecl())
19810 BoolT = Context.getBOOLType();
19811 return new (Context)
19812 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19813}
19814
19815ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19816 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19817 SourceLocation RParen) {
19818 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
19819 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19820 return Spec.getPlatform() == Platform;
19821 });
19822 // Transcribe the "ios" availability check to "maccatalyst" when compiling
19823 // for "maccatalyst" if "maccatalyst" is not specified.
19824 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
19825 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19826 return Spec.getPlatform() == "ios";
19827 });
19828 }
19829 if (Spec == AvailSpecs.end())
19830 return None;
19831 return Spec->getVersion();
19832 };
19833
19834 VersionTuple Version;
19835 if (auto MaybeVersion =
19836 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
19837 Version = *MaybeVersion;
19838
19839 // The use of `@available` in the enclosing context should be analyzed to
19840 // warn when it's used inappropriately (i.e. not if(@available)).
19841 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
19842 Context->HasPotentialAvailabilityViolations = true;
19843
19844 return new (Context)
19845 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19846}
19847
19848ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19849 ArrayRef<Expr *> SubExprs, QualType T) {
19850 if (!Context.getLangOpts().RecoveryAST)
19851 return ExprError();
19852
19853 if (isSFINAEContext())
19854 return ExprError();
19855
19856 if (T.isNull() || T->isUndeducedType() ||
19857 !Context.getLangOpts().RecoveryASTType)
19858 // We don't know the concrete type, fallback to dependent type.
19859 T = Context.DependentTy;
19860
19861 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19862}

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

/usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/include/clang/AST/Expr.h

1//===--- Expr.h - Classes for representing expressions ----------*- 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 Expr interface and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_EXPR_H
14#define LLVM_CLANG_AST_EXPR_H
15
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTVector.h"
18#include "clang/AST/ComputeDependence.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclAccessPair.h"
21#include "clang/AST/DependenceFlags.h"
22#include "clang/AST/OperationKinds.h"
23#include "clang/AST/Stmt.h"
24#include "clang/AST/TemplateBase.h"
25#include "clang/AST/Type.h"
26#include "clang/Basic/CharInfo.h"
27#include "clang/Basic/LangOptions.h"
28#include "clang/Basic/SyncScope.h"
29#include "clang/Basic/TypeTraits.h"
30#include "llvm/ADT/APFloat.h"
31#include "llvm/ADT/APSInt.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/StringRef.h"
34#include "llvm/ADT/iterator.h"
35#include "llvm/ADT/iterator_range.h"
36#include "llvm/Support/AtomicOrdering.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/Support/TrailingObjects.h"
39
40namespace clang {
41 class APValue;
42 class ASTContext;
43 class BlockDecl;
44 class CXXBaseSpecifier;
45 class CXXMemberCallExpr;
46 class CXXOperatorCallExpr;
47 class CastExpr;
48 class Decl;
49 class IdentifierInfo;
50 class MaterializeTemporaryExpr;
51 class NamedDecl;
52 class ObjCPropertyRefExpr;
53 class OpaqueValueExpr;
54 class ParmVarDecl;
55 class StringLiteral;
56 class TargetInfo;
57 class ValueDecl;
58
59/// A simple array of base specifiers.
60typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
61
62/// An adjustment to be made to the temporary created when emitting a
63/// reference binding, which accesses a particular subobject of that temporary.
64struct SubobjectAdjustment {
65 enum {
66 DerivedToBaseAdjustment,
67 FieldAdjustment,
68 MemberPointerAdjustment
69 } Kind;
70
71 struct DTB {
72 const CastExpr *BasePath;
73 const CXXRecordDecl *DerivedClass;
74 };
75
76 struct P {
77 const MemberPointerType *MPT;
78 Expr *RHS;
79 };
80
81 union {
82 struct DTB DerivedToBase;
83 FieldDecl *Field;
84 struct P Ptr;
85 };
86
87 SubobjectAdjustment(const CastExpr *BasePath,
88 const CXXRecordDecl *DerivedClass)
89 : Kind(DerivedToBaseAdjustment) {
90 DerivedToBase.BasePath = BasePath;
91 DerivedToBase.DerivedClass = DerivedClass;
92 }
93
94 SubobjectAdjustment(FieldDecl *Field)
95 : Kind(FieldAdjustment) {
96 this->Field = Field;
97 }
98
99 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
100 : Kind(MemberPointerAdjustment) {
101 this->Ptr.MPT = MPT;
102 this->Ptr.RHS = RHS;
103 }
104};
105
106/// This represents one expression. Note that Expr's are subclasses of Stmt.
107/// This allows an expression to be transparently used any place a Stmt is
108/// required.
109class Expr : public ValueStmt {
110 QualType TR;
111
112public:
113 Expr() = delete;
114 Expr(const Expr&) = delete;
115 Expr(Expr &&) = delete;
116 Expr &operator=(const Expr&) = delete;
117 Expr &operator=(Expr&&) = delete;
118
119protected:
120 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK)
121 : ValueStmt(SC) {
122 ExprBits.Dependent = 0;
123 ExprBits.ValueKind = VK;
124 ExprBits.ObjectKind = OK;
125 assert(ExprBits.ObjectKind == OK && "truncated kind")((void)0);
126 setType(T);
127 }
128
129 /// Construct an empty expression.
130 explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
131
132 /// Each concrete expr subclass is expected to compute its dependence and call
133 /// this in the constructor.
134 void setDependence(ExprDependence Deps) {
135 ExprBits.Dependent = static_cast<unsigned>(Deps);
136 }
137 friend class ASTImporter; // Sets dependence dircetly.
138 friend class ASTStmtReader; // Sets dependence dircetly.
139
140public:
141 QualType getType() const { return TR; }
142 void setType(QualType t) {
143 // In C++, the type of an expression is always adjusted so that it
144 // will not have reference type (C++ [expr]p6). Use
145 // QualType::getNonReferenceType() to retrieve the non-reference
146 // type. Additionally, inspect Expr::isLvalue to determine whether
147 // an expression that is adjusted in this manner should be
148 // considered an lvalue.
149 assert((t.isNull() || !t->isReferenceType()) &&((void)0)
150 "Expressions can't have reference type")((void)0);
151
152 TR = t;
153 }
154
155 ExprDependence getDependence() const {
156 return static_cast<ExprDependence>(ExprBits.Dependent);
157 }
158
159 /// Determines whether the value of this expression depends on
160 /// - a template parameter (C++ [temp.dep.constexpr])
161 /// - or an error, whose resolution is unknown
162 ///
163 /// For example, the array bound of "Chars" in the following example is
164 /// value-dependent.
165 /// @code
166 /// template<int Size, char (&Chars)[Size]> struct meta_string;
167 /// @endcode
168 bool isValueDependent() const {
169 return static_cast<bool>(getDependence() & ExprDependence::Value);
170 }
171
172 /// Determines whether the type of this expression depends on
173 /// - a template paramter (C++ [temp.dep.expr], which means that its type
174 /// could change from one template instantiation to the next)
175 /// - or an error
176 ///
177 /// For example, the expressions "x" and "x + y" are type-dependent in
178 /// the following code, but "y" is not type-dependent:
179 /// @code
180 /// template<typename T>
181 /// void add(T x, int y) {
182 /// x + y;
183 /// }
184 /// @endcode
185 bool isTypeDependent() const {
186 return static_cast<bool>(getDependence() & ExprDependence::Type);
187 }
188
189 /// Whether this expression is instantiation-dependent, meaning that
190 /// it depends in some way on
191 /// - a template parameter (even if neither its type nor (constant) value
192 /// can change due to the template instantiation)
193 /// - or an error
194 ///
195 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
196 /// instantiation-dependent (since it involves a template parameter \c T), but
197 /// is neither type- nor value-dependent, since the type of the inner
198 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
199 /// \c sizeof is known.
200 ///
201 /// \code
202 /// template<typename T>
203 /// void f(T x, T y) {
204 /// sizeof(sizeof(T() + T());
205 /// }
206 /// \endcode
207 ///
208 /// \code
209 /// void func(int) {
210 /// func(); // the expression is instantiation-dependent, because it depends
211 /// // on an error.
212 /// }
213 /// \endcode
214 bool isInstantiationDependent() const {
215 return static_cast<bool>(getDependence() & ExprDependence::Instantiation);
216 }
217
218 /// Whether this expression contains an unexpanded parameter
219 /// pack (for C++11 variadic templates).
220 ///
221 /// Given the following function template:
222 ///
223 /// \code
224 /// template<typename F, typename ...Types>
225 /// void forward(const F &f, Types &&...args) {
226 /// f(static_cast<Types&&>(args)...);
227 /// }
228 /// \endcode
229 ///
230 /// The expressions \c args and \c static_cast<Types&&>(args) both
231 /// contain parameter packs.
232 bool containsUnexpandedParameterPack() const {
233 return static_cast<bool>(getDependence() & ExprDependence::UnexpandedPack);
234 }
235
236 /// Whether this expression contains subexpressions which had errors, e.g. a
237 /// TypoExpr.
238 bool containsErrors() const {
239 return static_cast<bool>(getDependence() & ExprDependence::Error);
240 }
241
242 /// getExprLoc - Return the preferred location for the arrow when diagnosing
243 /// a problem with a generic expression.
244 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__));
245
246 /// Determine whether an lvalue-to-rvalue conversion should implicitly be
247 /// applied to this expression if it appears as a discarded-value expression
248 /// in C++11 onwards. This applies to certain forms of volatile glvalues.
249 bool isReadIfDiscardedInCPlusPlus11() const;
250
251 /// isUnusedResultAWarning - Return true if this immediate expression should
252 /// be warned about if the result is unused. If so, fill in expr, location,
253 /// and ranges with expr to warn on and source locations/ranges appropriate
254 /// for a warning.
255 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
256 SourceRange &R1, SourceRange &R2,
257 ASTContext &Ctx) const;
258
259 /// isLValue - True if this expression is an "l-value" according to
260 /// the rules of the current language. C and C++ give somewhat
261 /// different rules for this concept, but in general, the result of
262 /// an l-value expression identifies a specific object whereas the
263 /// result of an r-value expression is a value detached from any
264 /// specific storage.
265 ///
266 /// C++11 divides the concept of "r-value" into pure r-values
267 /// ("pr-values") and so-called expiring values ("x-values"), which
268 /// identify specific objects that can be safely cannibalized for
269 /// their resources.
270 bool isLValue() const { return getValueKind() == VK_LValue; }
68
Assuming the condition is false
69
Returning zero, which participates in a condition later
271 bool isPRValue() const { return getValueKind() == VK_PRValue; }
272 bool isXValue() const { return getValueKind() == VK_XValue; }
273 bool isGLValue() const { return getValueKind() != VK_PRValue; }
274
275 enum LValueClassification {
276 LV_Valid,
277 LV_NotObjectType,
278 LV_IncompleteVoidType,
279 LV_DuplicateVectorComponents,
280 LV_InvalidExpression,
281 LV_InvalidMessageExpression,
282 LV_MemberFunction,
283 LV_SubObjCPropertySetting,
284 LV_ClassTemporary,
285 LV_ArrayTemporary
286 };
287 /// Reasons why an expression might not be an l-value.
288 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
289
290 enum isModifiableLvalueResult {
291 MLV_Valid,
292 MLV_NotObjectType,
293 MLV_IncompleteVoidType,
294 MLV_DuplicateVectorComponents,
295 MLV_InvalidExpression,
296 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
297 MLV_IncompleteType,
298 MLV_ConstQualified,
299 MLV_ConstQualifiedField,
300 MLV_ConstAddrSpace,
301 MLV_ArrayType,
302 MLV_NoSetterProperty,
303 MLV_MemberFunction,
304 MLV_SubObjCPropertySetting,
305 MLV_InvalidMessageExpression,
306 MLV_ClassTemporary,
307 MLV_ArrayTemporary
308 };
309 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
310 /// does not have an incomplete type, does not have a const-qualified type,
311 /// and if it is a structure or union, does not have any member (including,
312 /// recursively, any member or element of all contained aggregates or unions)
313 /// with a const-qualified type.
314 ///
315 /// \param Loc [in,out] - A source location which *may* be filled
316 /// in with the location of the expression making this a
317 /// non-modifiable lvalue, if specified.
318 isModifiableLvalueResult
319 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
320
321 /// The return type of classify(). Represents the C++11 expression
322 /// taxonomy.
323 class Classification {
324 public:
325 /// The various classification results. Most of these mean prvalue.
326 enum Kinds {
327 CL_LValue,
328 CL_XValue,
329 CL_Function, // Functions cannot be lvalues in C.
330 CL_Void, // Void cannot be an lvalue in C.
331 CL_AddressableVoid, // Void expression whose address can be taken in C.
332 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
333 CL_MemberFunction, // An expression referring to a member function
334 CL_SubObjCPropertySetting,
335 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
336 CL_ArrayTemporary, // A temporary of array type.
337 CL_ObjCMessageRValue, // ObjC message is an rvalue
338 CL_PRValue // A prvalue for any other reason, of any other type
339 };
340 /// The results of modification testing.
341 enum ModifiableType {
342 CM_Untested, // testModifiable was false.
343 CM_Modifiable,
344 CM_RValue, // Not modifiable because it's an rvalue
345 CM_Function, // Not modifiable because it's a function; C++ only
346 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
347 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
348 CM_ConstQualified,
349 CM_ConstQualifiedField,
350 CM_ConstAddrSpace,
351 CM_ArrayType,
352 CM_IncompleteType
353 };
354
355 private:
356 friend class Expr;
357
358 unsigned short Kind;
359 unsigned short Modifiable;
360
361 explicit Classification(Kinds k, ModifiableType m)
362 : Kind(k), Modifiable(m)
363 {}
364
365 public:
366 Classification() {}
367
368 Kinds getKind() const { return static_cast<Kinds>(Kind); }
369 ModifiableType getModifiable() const {
370 assert(Modifiable != CM_Untested && "Did not test for modifiability.")((void)0);
371 return static_cast<ModifiableType>(Modifiable);
372 }
373 bool isLValue() const { return Kind == CL_LValue; }
374 bool isXValue() const { return Kind == CL_XValue; }
375 bool isGLValue() const { return Kind <= CL_XValue; }
376 bool isPRValue() const { return Kind >= CL_Function; }
377 bool isRValue() const { return Kind >= CL_XValue; }
378 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
379
380 /// Create a simple, modifiably lvalue
381 static Classification makeSimpleLValue() {
382 return Classification(CL_LValue, CM_Modifiable);
383 }
384
385 };
386 /// Classify - Classify this expression according to the C++11
387 /// expression taxonomy.
388 ///
389 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
390 /// old lvalue vs rvalue. This function determines the type of expression this
391 /// is. There are three expression types:
392 /// - lvalues are classical lvalues as in C++03.
393 /// - prvalues are equivalent to rvalues in C++03.
394 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
395 /// function returning an rvalue reference.
396 /// lvalues and xvalues are collectively referred to as glvalues, while
397 /// prvalues and xvalues together form rvalues.
398 Classification Classify(ASTContext &Ctx) const {
399 return ClassifyImpl(Ctx, nullptr);
400 }
401
402 /// ClassifyModifiable - Classify this expression according to the
403 /// C++11 expression taxonomy, and see if it is valid on the left side
404 /// of an assignment.
405 ///
406 /// This function extends classify in that it also tests whether the
407 /// expression is modifiable (C99 6.3.2.1p1).
408 /// \param Loc A source location that might be filled with a relevant location
409 /// if the expression is not modifiable.
410 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
411 return ClassifyImpl(Ctx, &Loc);
412 }
413
414 /// Returns the set of floating point options that apply to this expression.
415 /// Only meaningful for operations on floating point values.
416 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const;
417
418 /// getValueKindForType - Given a formal return or parameter type,
419 /// give its value kind.
420 static ExprValueKind getValueKindForType(QualType T) {
421 if (const ReferenceType *RT = T->getAs<ReferenceType>())
422 return (isa<LValueReferenceType>(RT)
423 ? VK_LValue
424 : (RT->getPointeeType()->isFunctionType()
425 ? VK_LValue : VK_XValue));
426 return VK_PRValue;
427 }
428
429 /// getValueKind - The value kind that this expression produces.
430 ExprValueKind getValueKind() const {
431 return static_cast<ExprValueKind>(ExprBits.ValueKind);
432 }
433
434 /// getObjectKind - The object kind that this expression produces.
435 /// Object kinds are meaningful only for expressions that yield an
436 /// l-value or x-value.
437 ExprObjectKind getObjectKind() const {
438 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
439 }
440
441 bool isOrdinaryOrBitFieldObject() const {
442 ExprObjectKind OK = getObjectKind();
443 return (OK == OK_Ordinary || OK == OK_BitField);
444 }
445
446 /// setValueKind - Set the value kind produced by this expression.
447 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
448
449 /// setObjectKind - Set the object kind produced by this expression.
450 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
451
452private:
453 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
454
455public:
456
457 /// Returns true if this expression is a gl-value that
458 /// potentially refers to a bit-field.
459 ///
460 /// In C++, whether a gl-value refers to a bitfield is essentially
461 /// an aspect of the value-kind type system.
462 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
463
464 /// If this expression refers to a bit-field, retrieve the
465 /// declaration of that bit-field.
466 ///
467 /// Note that this returns a non-null pointer in subtly different
468 /// places than refersToBitField returns true. In particular, this can
469 /// return a non-null pointer even for r-values loaded from
470 /// bit-fields, but it will return null for a conditional bit-field.
471 FieldDecl *getSourceBitField();
472
473 const FieldDecl *getSourceBitField() const {
474 return const_cast<Expr*>(this)->getSourceBitField();
475 }
476
477 Decl *getReferencedDeclOfCallee();
478 const Decl *getReferencedDeclOfCallee() const {
479 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
480 }
481
482 /// If this expression is an l-value for an Objective C
483 /// property, find the underlying property reference expression.
484 const ObjCPropertyRefExpr *getObjCProperty() const;
485
486 /// Check if this expression is the ObjC 'self' implicit parameter.
487 bool isObjCSelfExpr() const;
488
489 /// Returns whether this expression refers to a vector element.
490 bool refersToVectorElement() const;
491
492 /// Returns whether this expression refers to a matrix element.
493 bool refersToMatrixElement() const {
494 return getObjectKind() == OK_MatrixComponent;
495 }
496
497 /// Returns whether this expression refers to a global register
498 /// variable.
499 bool refersToGlobalRegisterVar() const;
500
501 /// Returns whether this expression has a placeholder type.
502 bool hasPlaceholderType() const {
503 return getType()->isPlaceholderType();
504 }
505
506 /// Returns whether this expression has a specific placeholder type.
507 bool hasPlaceholderType(BuiltinType::Kind K) const {
508 assert(BuiltinType::isPlaceholderTypeKind(K))((void)0);
509 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
510 return BT->getKind() == K;
511 return false;
512 }
513
514 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
515 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
516 /// but also int expressions which are produced by things like comparisons in
517 /// C.
518 ///
519 /// \param Semantic If true, only return true for expressions that are known
520 /// to be semantically boolean, which might not be true even for expressions
521 /// that are known to evaluate to 0/1. For instance, reading an unsigned
522 /// bit-field with width '1' will evaluate to 0/1, but doesn't necessarily
523 /// semantically correspond to a bool.
524 bool isKnownToHaveBooleanValue(bool Semantic = true) const;
525
526 /// isIntegerConstantExpr - Return the value if this expression is a valid
527 /// integer constant expression. If not a valid i-c-e, return None and fill
528 /// in Loc (if specified) with the location of the invalid expression.
529 ///
530 /// Note: This does not perform the implicit conversions required by C++11
531 /// [expr.const]p5.
532 Optional<llvm::APSInt> getIntegerConstantExpr(const ASTContext &Ctx,
533 SourceLocation *Loc = nullptr,
534 bool isEvaluated = true) const;
535 bool isIntegerConstantExpr(const ASTContext &Ctx,
536 SourceLocation *Loc = nullptr) const;
537
538 /// isCXX98IntegralConstantExpr - Return true if this expression is an
539 /// integral constant expression in C++98. Can only be used in C++.
540 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
541
542 /// isCXX11ConstantExpr - Return true if this expression is a constant
543 /// expression in C++11. Can only be used in C++.
544 ///
545 /// Note: This does not perform the implicit conversions required by C++11
546 /// [expr.const]p5.
547 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
548 SourceLocation *Loc = nullptr) const;
549
550 /// isPotentialConstantExpr - Return true if this function's definition
551 /// might be usable in a constant expression in C++11, if it were marked
552 /// constexpr. Return false if the function can never produce a constant
553 /// expression, along with diagnostics describing why not.
554 static bool isPotentialConstantExpr(const FunctionDecl *FD,
555 SmallVectorImpl<
556 PartialDiagnosticAt> &Diags);
557
558 /// isPotentialConstantExprUnevaluted - Return true if this expression might
559 /// be usable in a constant expression in C++11 in an unevaluated context, if
560 /// it were in function FD marked constexpr. Return false if the function can
561 /// never produce a constant expression, along with diagnostics describing
562 /// why not.
563 static bool isPotentialConstantExprUnevaluated(Expr *E,
564 const FunctionDecl *FD,
565 SmallVectorImpl<
566 PartialDiagnosticAt> &Diags);
567
568 /// isConstantInitializer - Returns true if this expression can be emitted to
569 /// IR as a constant, and thus can be used as a constant initializer in C.
570 /// If this expression is not constant and Culprit is non-null,
571 /// it is used to store the address of first non constant expr.
572 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
573 const Expr **Culprit = nullptr) const;
574
575 /// EvalStatus is a struct with detailed info about an evaluation in progress.
576 struct EvalStatus {
577 /// Whether the evaluated expression has side effects.
578 /// For example, (f() && 0) can be folded, but it still has side effects.
579 bool HasSideEffects;
580
581 /// Whether the evaluation hit undefined behavior.
582 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
583 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
584 bool HasUndefinedBehavior;
585
586 /// Diag - If this is non-null, it will be filled in with a stack of notes
587 /// indicating why evaluation failed (or why it failed to produce a constant
588 /// expression).
589 /// If the expression is unfoldable, the notes will indicate why it's not
590 /// foldable. If the expression is foldable, but not a constant expression,
591 /// the notes will describes why it isn't a constant expression. If the
592 /// expression *is* a constant expression, no notes will be produced.
593 SmallVectorImpl<PartialDiagnosticAt> *Diag;
594
595 EvalStatus()
596 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
597
598 // hasSideEffects - Return true if the evaluated expression has
599 // side effects.
600 bool hasSideEffects() const {
601 return HasSideEffects;
602 }
603 };
604
605 /// EvalResult is a struct with detailed info about an evaluated expression.
606 struct EvalResult : EvalStatus {
607 /// Val - This is the value the expression can be folded to.
608 APValue Val;
609
610 // isGlobalLValue - Return true if the evaluated lvalue expression
611 // is global.
612 bool isGlobalLValue() const;
613 };
614
615 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
616 /// an rvalue using any crazy technique (that has nothing to do with language
617 /// standards) that we want to, even if the expression has side-effects. If
618 /// this function returns true, it returns the folded constant in Result. If
619 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
620 /// applied.
621 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
622 bool InConstantContext = false) const;
623
624 /// EvaluateAsBooleanCondition - Return true if this is a constant
625 /// which we can fold and convert to a boolean condition using
626 /// any crazy technique that we want to, even if the expression has
627 /// side-effects.
628 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
629 bool InConstantContext = false) const;
630
631 enum SideEffectsKind {
632 SE_NoSideEffects, ///< Strictly evaluate the expression.
633 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
634 ///< arbitrary unmodeled side effects.
635 SE_AllowSideEffects ///< Allow any unmodeled side effect.
636 };
637
638 /// EvaluateAsInt - Return true if this is a constant which we can fold and
639 /// convert to an integer, using any crazy technique that we want to.
640 bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
641 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
642 bool InConstantContext = false) const;
643
644 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
645 /// convert to a floating point value, using any crazy technique that we
646 /// want to.
647 bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
648 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
649 bool InConstantContext = false) const;
650
651 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
652 /// convert to a fixed point value.
653 bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
654 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
655 bool InConstantContext = false) const;
656
657 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
658 /// constant folded without side-effects, but discard the result.
659 bool isEvaluatable(const ASTContext &Ctx,
660 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
661
662 /// HasSideEffects - This routine returns true for all those expressions
663 /// which have any effect other than producing a value. Example is a function
664 /// call, volatile variable read, or throwing an exception. If
665 /// IncludePossibleEffects is false, this call treats certain expressions with
666 /// potential side effects (such as function call-like expressions,
667 /// instantiation-dependent expressions, or invocations from a macro) as not
668 /// having side effects.
669 bool HasSideEffects(const ASTContext &Ctx,
670 bool IncludePossibleEffects = true) const;
671
672 /// Determine whether this expression involves a call to any function
673 /// that is not trivial.
674 bool hasNonTrivialCall(const ASTContext &Ctx) const;
675
676 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
677 /// integer. This must be called on an expression that constant folds to an
678 /// integer.
679 llvm::APSInt EvaluateKnownConstInt(
680 const ASTContext &Ctx,
681 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
682
683 llvm::APSInt EvaluateKnownConstIntCheckOverflow(
684 const ASTContext &Ctx,
685 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
686
687 void EvaluateForOverflow(const ASTContext &Ctx) const;
688
689 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
690 /// lvalue with link time known address, with no side-effects.
691 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
692 bool InConstantContext = false) const;
693
694 /// EvaluateAsInitializer - Evaluate an expression as if it were the
695 /// initializer of the given declaration. Returns true if the initializer
696 /// can be folded to a constant, and produces any relevant notes. In C++11,
697 /// notes will be produced if the expression is not a constant expression.
698 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
699 const VarDecl *VD,
700 SmallVectorImpl<PartialDiagnosticAt> &Notes,
701 bool IsConstantInitializer) const;
702
703 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
704 /// of a call to the given function with the given arguments, inside an
705 /// unevaluated context. Returns true if the expression could be folded to a
706 /// constant.
707 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
708 const FunctionDecl *Callee,
709 ArrayRef<const Expr*> Args,
710 const Expr *This = nullptr) const;
711
712 enum class ConstantExprKind {
713 /// An integer constant expression (an array bound, enumerator, case value,
714 /// bit-field width, or similar) or similar.
715 Normal,
716 /// A non-class template argument. Such a value is only used for mangling,
717 /// not for code generation, so can refer to dllimported functions.
718 NonClassTemplateArgument,
719 /// A class template argument. Such a value is used for code generation.
720 ClassTemplateArgument,
721 /// An immediate invocation. The destruction of the end result of this
722 /// evaluation is not part of the evaluation, but all other temporaries
723 /// are destroyed.
724 ImmediateInvocation,
725 };
726
727 /// Evaluate an expression that is required to be a constant expression. Does
728 /// not check the syntactic constraints for C and C++98 constant expressions.
729 bool EvaluateAsConstantExpr(
730 EvalResult &Result, const ASTContext &Ctx,
731 ConstantExprKind Kind = ConstantExprKind::Normal) const;
732
733 /// If the current Expr is a pointer, this will try to statically
734 /// determine the number of bytes available where the pointer is pointing.
735 /// Returns true if all of the above holds and we were able to figure out the
736 /// size, false otherwise.
737 ///
738 /// \param Type - How to evaluate the size of the Expr, as defined by the
739 /// "type" parameter of __builtin_object_size
740 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
741 unsigned Type) const;
742
743 /// Enumeration used to describe the kind of Null pointer constant
744 /// returned from \c isNullPointerConstant().
745 enum NullPointerConstantKind {
746 /// Expression is not a Null pointer constant.
747 NPCK_NotNull = 0,
748
749 /// Expression is a Null pointer constant built from a zero integer
750 /// expression that is not a simple, possibly parenthesized, zero literal.
751 /// C++ Core Issue 903 will classify these expressions as "not pointers"
752 /// once it is adopted.
753 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
754 NPCK_ZeroExpression,
755
756 /// Expression is a Null pointer constant built from a literal zero.
757 NPCK_ZeroLiteral,
758
759 /// Expression is a C++11 nullptr.
760 NPCK_CXX11_nullptr,
761
762 /// Expression is a GNU-style __null constant.
763 NPCK_GNUNull
764 };
765
766 /// Enumeration used to describe how \c isNullPointerConstant()
767 /// should cope with value-dependent expressions.
768 enum NullPointerConstantValueDependence {
769 /// Specifies that the expression should never be value-dependent.
770 NPC_NeverValueDependent = 0,
771
772 /// Specifies that a value-dependent expression of integral or
773 /// dependent type should be considered a null pointer constant.
774 NPC_ValueDependentIsNull,
775
776 /// Specifies that a value-dependent expression should be considered
777 /// to never be a null pointer constant.
778 NPC_ValueDependentIsNotNull
779 };
780
781 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
782 /// a Null pointer constant. The return value can further distinguish the
783 /// kind of NULL pointer constant that was detected.
784 NullPointerConstantKind isNullPointerConstant(
785 ASTContext &Ctx,
786 NullPointerConstantValueDependence NPC) const;
787
788 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
789 /// write barrier.
790 bool isOBJCGCCandidate(ASTContext &Ctx) const;
791
792 /// Returns true if this expression is a bound member function.
793 bool isBoundMemberFunction(ASTContext &Ctx) const;
794
795 /// Given an expression of bound-member type, find the type
796 /// of the member. Returns null if this is an *overloaded* bound
797 /// member expression.
798 static QualType findBoundMemberType(const Expr *expr);
799
800 /// Skip past any invisble AST nodes which might surround this
801 /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes,
802 /// but also injected CXXMemberExpr and CXXConstructExpr which represent
803 /// implicit conversions.
804 Expr *IgnoreUnlessSpelledInSource();
805 const Expr *IgnoreUnlessSpelledInSource() const {
806 return const_cast<Expr *>(this)->IgnoreUnlessSpelledInSource();
807 }
808
809 /// Skip past any implicit casts which might surround this expression until
810 /// reaching a fixed point. Skips:
811 /// * ImplicitCastExpr
812 /// * FullExpr
813 Expr *IgnoreImpCasts() LLVM_READONLY__attribute__((__pure__));
814 const Expr *IgnoreImpCasts() const {
815 return const_cast<Expr *>(this)->IgnoreImpCasts();
816 }
817
818 /// Skip past any casts which might surround this expression until reaching
819 /// a fixed point. Skips:
820 /// * CastExpr
821 /// * FullExpr
822 /// * MaterializeTemporaryExpr
823 /// * SubstNonTypeTemplateParmExpr
824 Expr *IgnoreCasts() LLVM_READONLY__attribute__((__pure__));
825 const Expr *IgnoreCasts() const {
826 return const_cast<Expr *>(this)->IgnoreCasts();
827 }
828
829 /// Skip past any implicit AST nodes which might surround this expression
830 /// until reaching a fixed point. Skips:
831 /// * What IgnoreImpCasts() skips
832 /// * MaterializeTemporaryExpr
833 /// * CXXBindTemporaryExpr
834 Expr *IgnoreImplicit() LLVM_READONLY__attribute__((__pure__));
835 const Expr *IgnoreImplicit() const {
836 return const_cast<Expr *>(this)->IgnoreImplicit();
837 }
838
839 /// Skip past any implicit AST nodes which might surround this expression
840 /// until reaching a fixed point. Same as IgnoreImplicit, except that it
841 /// also skips over implicit calls to constructors and conversion functions.
842 ///
843 /// FIXME: Should IgnoreImplicit do this?
844 Expr *IgnoreImplicitAsWritten() LLVM_READONLY__attribute__((__pure__));
845 const Expr *IgnoreImplicitAsWritten() const {
846 return const_cast<Expr *>(this)->IgnoreImplicitAsWritten();
847 }
848
849 /// Skip past any parentheses which might surround this expression until
850 /// reaching a fixed point. Skips:
851 /// * ParenExpr
852 /// * UnaryOperator if `UO_Extension`
853 /// * GenericSelectionExpr if `!isResultDependent()`
854 /// * ChooseExpr if `!isConditionDependent()`
855 /// * ConstantExpr
856 Expr *IgnoreParens() LLVM_READONLY__attribute__((__pure__));
857 const Expr *IgnoreParens() const {
858 return const_cast<Expr *>(this)->IgnoreParens();
859 }
860
861 /// Skip past any parentheses and implicit casts which might surround this
862 /// expression until reaching a fixed point.
863 /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
864 /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
865 /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
866 /// * What IgnoreParens() skips
867 /// * What IgnoreImpCasts() skips
868 /// * MaterializeTemporaryExpr
869 /// * SubstNonTypeTemplateParmExpr
870 Expr *IgnoreParenImpCasts() LLVM_READONLY__attribute__((__pure__));
871 const Expr *IgnoreParenImpCasts() const {
872 return const_cast<Expr *>(this)->IgnoreParenImpCasts();
873 }
874
875 /// Skip past any parentheses and casts which might surround this expression
876 /// until reaching a fixed point. Skips:
877 /// * What IgnoreParens() skips
878 /// * What IgnoreCasts() skips
879 Expr *IgnoreParenCasts() LLVM_READONLY__attribute__((__pure__));
880 const Expr *IgnoreParenCasts() const {
881 return const_cast<Expr *>(this)->IgnoreParenCasts();
882 }
883
884 /// Skip conversion operators. If this Expr is a call to a conversion
885 /// operator, return the argument.
886 Expr *IgnoreConversionOperatorSingleStep() LLVM_READONLY__attribute__((__pure__));
887 const Expr *IgnoreConversionOperatorSingleStep() const {
888 return const_cast<Expr *>(this)->IgnoreConversionOperatorSingleStep();
889 }
890
891 /// Skip past any parentheses and lvalue casts which might surround this
892 /// expression until reaching a fixed point. Skips:
893 /// * What IgnoreParens() skips
894 /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
895 /// casts are skipped
896 /// FIXME: This is intended purely as a temporary workaround for code
897 /// that hasn't yet been rewritten to do the right thing about those
898 /// casts, and may disappear along with the last internal use.
899 Expr *IgnoreParenLValueCasts() LLVM_READONLY__attribute__((__pure__));
900 const Expr *IgnoreParenLValueCasts() const {
901 return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
902 }
903
904 /// Skip past any parenthese and casts which do not change the value
905 /// (including ptr->int casts of the same size) until reaching a fixed point.
906 /// Skips:
907 /// * What IgnoreParens() skips
908 /// * CastExpr which do not change the value
909 /// * SubstNonTypeTemplateParmExpr
910 Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY__attribute__((__pure__));
911 const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
912 return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
913 }
914
915 /// Skip past any parentheses and derived-to-base casts until reaching a
916 /// fixed point. Skips:
917 /// * What IgnoreParens() skips
918 /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
919 /// CK_UncheckedDerivedToBase and CK_NoOp)
920 Expr *IgnoreParenBaseCasts() LLVM_READONLY__attribute__((__pure__));
921 const Expr *IgnoreParenBaseCasts() const {
922 return const_cast<Expr *>(this)->IgnoreParenBaseCasts();
923 }
924
925 /// Determine whether this expression is a default function argument.
926 ///
927 /// Default arguments are implicitly generated in the abstract syntax tree
928 /// by semantic analysis for function calls, object constructions, etc. in
929 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
930 /// this routine also looks through any implicit casts to determine whether
931 /// the expression is a default argument.
932 bool isDefaultArgument() const;
933
934 /// Determine whether the result of this expression is a
935 /// temporary object of the given class type.
936 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
937
938 /// Whether this expression is an implicit reference to 'this' in C++.
939 bool isImplicitCXXThis() const;
940
941 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
942
943 /// For an expression of class type or pointer to class type,
944 /// return the most derived class decl the expression is known to refer to.
945 ///
946 /// If this expression is a cast, this method looks through it to find the
947 /// most derived decl that can be inferred from the expression.
948 /// This is valid because derived-to-base conversions have undefined
949 /// behavior if the object isn't dynamically of the derived type.
950 const CXXRecordDecl *getBestDynamicClassType() const;
951
952 /// Get the inner expression that determines the best dynamic class.
953 /// If this is a prvalue, we guarantee that it is of the most-derived type
954 /// for the object itself.
955 const Expr *getBestDynamicClassTypeExpr() const;
956
957 /// Walk outwards from an expression we want to bind a reference to and
958 /// find the expression whose lifetime needs to be extended. Record
959 /// the LHSs of comma expressions and adjustments needed along the path.
960 const Expr *skipRValueSubobjectAdjustments(
961 SmallVectorImpl<const Expr *> &CommaLHS,
962 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
963 const Expr *skipRValueSubobjectAdjustments() const {
964 SmallVector<const Expr *, 8> CommaLHSs;
965 SmallVector<SubobjectAdjustment, 8> Adjustments;
966 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
967 }
968
969 /// Checks that the two Expr's will refer to the same value as a comparison
970 /// operand. The caller must ensure that the values referenced by the Expr's
971 /// are not modified between E1 and E2 or the result my be invalid.
972 static bool isSameComparisonOperand(const Expr* E1, const Expr* E2);
973
974 static bool classof(const Stmt *T) {
975 return T->getStmtClass() >= firstExprConstant &&
976 T->getStmtClass() <= lastExprConstant;
977 }
978};
979// PointerLikeTypeTraits is specialized so it can be used with a forward-decl of
980// Expr. Verify that we got it right.
981static_assert(llvm::PointerLikeTypeTraits<Expr *>::NumLowBitsAvailable <=
982 llvm::detail::ConstantLog2<alignof(Expr)>::value,
983 "PointerLikeTypeTraits<Expr*> assumes too much alignment.");
984
985using ConstantExprKind = Expr::ConstantExprKind;
986
987//===----------------------------------------------------------------------===//
988// Wrapper Expressions.
989//===----------------------------------------------------------------------===//
990
991/// FullExpr - Represents a "full-expression" node.
992class FullExpr : public Expr {
993protected:
994 Stmt *SubExpr;
995
996 FullExpr(StmtClass SC, Expr *subexpr)
997 : Expr(SC, subexpr->getType(), subexpr->getValueKind(),
998 subexpr->getObjectKind()),
999 SubExpr(subexpr) {
1000 setDependence(computeDependence(this));
1001 }
1002 FullExpr(StmtClass SC, EmptyShell Empty)
1003 : Expr(SC, Empty) {}
1004public:
1005 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
1006 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1007
1008 /// As with any mutator of the AST, be very careful when modifying an
1009 /// existing AST to preserve its invariants.
1010 void setSubExpr(Expr *E) { SubExpr = E; }
1011
1012 static bool classof(const Stmt *T) {
1013 return T->getStmtClass() >= firstFullExprConstant &&
1014 T->getStmtClass() <= lastFullExprConstant;
1015 }
1016};
1017
1018/// ConstantExpr - An expression that occurs in a constant context and
1019/// optionally the result of evaluating the expression.
1020class ConstantExpr final
1021 : public FullExpr,
1022 private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
1023 static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
1024 "ConstantExpr assumes that llvm::APInt::WordType is uint64_t "
1025 "for tail-allocated storage");
1026 friend TrailingObjects;
1027 friend class ASTStmtReader;
1028 friend class ASTStmtWriter;
1029
1030public:
1031 /// Describes the kind of result that can be tail-allocated.
1032 enum ResultStorageKind { RSK_None, RSK_Int64, RSK_APValue };
1033
1034private:
1035 size_t numTrailingObjects(OverloadToken<APValue>) const {
1036 return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue;
1037 }
1038 size_t numTrailingObjects(OverloadToken<uint64_t>) const {
1039 return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64;
1040 }
1041
1042 uint64_t &Int64Result() {
1043 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&((void)0)
1044 "invalid accessor")((void)0);
1045 return *getTrailingObjects<uint64_t>();
1046 }
1047 const uint64_t &Int64Result() const {
1048 return const_cast<ConstantExpr *>(this)->Int64Result();
1049 }
1050 APValue &APValueResult() {
1051 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&((void)0)
1052 "invalid accessor")((void)0);
1053 return *getTrailingObjects<APValue>();
1054 }
1055 APValue &APValueResult() const {
1056 return const_cast<ConstantExpr *>(this)->APValueResult();
1057 }
1058
1059 ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind,
1060 bool IsImmediateInvocation);
1061 ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind);
1062
1063public:
1064 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1065 const APValue &Result);
1066 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1067 ResultStorageKind Storage = RSK_None,
1068 bool IsImmediateInvocation = false);
1069 static ConstantExpr *CreateEmpty(const ASTContext &Context,
1070 ResultStorageKind StorageKind);
1071
1072 static ResultStorageKind getStorageKind(const APValue &Value);
1073 static ResultStorageKind getStorageKind(const Type *T,
1074 const ASTContext &Context);
1075
1076 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1077 return SubExpr->getBeginLoc();
1078 }
1079 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
1080 return SubExpr->getEndLoc();
1081 }
1082
1083 static bool classof(const Stmt *T) {
1084 return T->getStmtClass() == ConstantExprClass;
1085 }
1086
1087 void SetResult(APValue Value, const ASTContext &Context) {
1088 MoveIntoResult(Value, Context);
1089 }
1090 void MoveIntoResult(APValue &Value, const ASTContext &Context);
1091
1092 APValue::ValueKind getResultAPValueKind() const {
1093 return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
1094 }
1095 ResultStorageKind getResultStorageKind() const {
1096 return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind);
1097 }
1098 bool isImmediateInvocation() const {
1099 return ConstantExprBits.IsImmediateInvocation;
1100 }
1101 bool hasAPValueResult() const {
1102 return ConstantExprBits.APValueKind != APValue::None;
1103 }
1104 APValue getAPValueResult() const;
1105 APValue &getResultAsAPValue() const { return APValueResult(); }
1106 llvm::APSInt getResultAsAPSInt() const;
1107 // Iterators
1108 child_range children() { return child_range(&SubExpr, &SubExpr+1); }
1109 const_child_range children() const {
1110 return const_child_range(&SubExpr, &SubExpr + 1);
1111 }
1112};
1113
1114//===----------------------------------------------------------------------===//
1115// Primary Expressions.
1116//===----------------------------------------------------------------------===//
1117
1118/// OpaqueValueExpr - An expression referring to an opaque object of a
1119/// fixed type and value class. These don't correspond to concrete
1120/// syntax; instead they're used to express operations (usually copy
1121/// operations) on values whose source is generally obvious from
1122/// context.
1123class OpaqueValueExpr : public Expr {
1124 friend class ASTStmtReader;
1125 Expr *SourceExpr;
1126
1127public:
1128 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
1129 ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr)
1130 : Expr(OpaqueValueExprClass, T, VK, OK), SourceExpr(SourceExpr) {
1131 setIsUnique(false);
1132 OpaqueValueExprBits.Loc = Loc;
1133 setDependence(computeDependence(this));
1134 }
1135
1136 /// Given an expression which invokes a copy constructor --- i.e. a
1137 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
1138 /// find the OpaqueValueExpr that's the source of the construction.
1139 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
1140
1141 explicit OpaqueValueExpr(EmptyShell Empty)
1142 : Expr(OpaqueValueExprClass, Empty) {}
1143
1144 /// Retrieve the location of this expression.
1145 SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; }
1146
1147 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1148 return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
1149 }
1150 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
1151 return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
1152 }
1153 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
1154 return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
1155 }
1156
1157 child_range children() {
1158 return child_range(child_iterator(), child_iterator());
1159 }
1160
1161 const_child_range children() const {
1162 return const_child_range(const_child_iterator(), const_child_iterator());
1163 }
1164
1165 /// The source expression of an opaque value expression is the
1166 /// expression which originally generated the value. This is
1167 /// provided as a convenience for analyses that don't wish to
1168 /// precisely model the execution behavior of the program.
1169 ///
1170 /// The source expression is typically set when building the
1171 /// expression which binds the opaque value expression in the first
1172 /// place.
1173 Expr *getSourceExpr() const { return SourceExpr; }
1174
1175 void setIsUnique(bool V) {
1176 assert((!V || SourceExpr) &&((void)0)
1177 "unique OVEs are expected to have source expressions")((void)0);
1178 OpaqueValueExprBits.IsUnique = V;
1179 }
1180
1181 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
1182
1183 static bool classof(const Stmt *T) {
1184 return T->getStmtClass() == OpaqueValueExprClass;
1185 }
1186};
1187
1188/// A reference to a declared variable, function, enum, etc.
1189/// [C99 6.5.1p2]
1190///
1191/// This encodes all the information about how a declaration is referenced
1192/// within an expression.
1193///
1194/// There are several optional constructs attached to DeclRefExprs only when
1195/// they apply in order to conserve memory. These are laid out past the end of
1196/// the object, and flags in the DeclRefExprBitfield track whether they exist:
1197///
1198/// DeclRefExprBits.HasQualifier:
1199/// Specifies when this declaration reference expression has a C++
1200/// nested-name-specifier.
1201/// DeclRefExprBits.HasFoundDecl:
1202/// Specifies when this declaration reference expression has a record of
1203/// a NamedDecl (different from the referenced ValueDecl) which was found
1204/// during name lookup and/or overload resolution.
1205/// DeclRefExprBits.HasTemplateKWAndArgsInfo:
1206/// Specifies when this declaration reference expression has an explicit
1207/// C++ template keyword and/or template argument list.
1208/// DeclRefExprBits.RefersToEnclosingVariableOrCapture
1209/// Specifies when this declaration reference expression (validly)
1210/// refers to an enclosed local or a captured variable.
1211class DeclRefExpr final
1212 : public Expr,
1213 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
1214 NamedDecl *, ASTTemplateKWAndArgsInfo,
1215 TemplateArgumentLoc> {
1216 friend class ASTStmtReader;
1217 friend class ASTStmtWriter;
1218 friend TrailingObjects;
1219
1220 /// The declaration that we are referencing.
1221 ValueDecl *D;
1222
1223 /// Provides source/type location info for the declaration name
1224 /// embedded in D.
1225 DeclarationNameLoc DNLoc;
1226
1227 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1228 return hasQualifier();
1229 }
1230
1231 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1232 return hasFoundDecl();
1233 }
1234
1235 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1236 return hasTemplateKWAndArgsInfo();
1237 }
1238
1239 /// Test whether there is a distinct FoundDecl attached to the end of
1240 /// this DRE.
1241 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1242
1243 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
1244 SourceLocation TemplateKWLoc, ValueDecl *D,
1245 bool RefersToEnlosingVariableOrCapture,
1246 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
1247 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1248 ExprValueKind VK, NonOdrUseReason NOUR);
1249
1250 /// Construct an empty declaration reference expression.
1251 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1252
1253public:
1254 DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
1255 bool RefersToEnclosingVariableOrCapture, QualType T,
1256 ExprValueKind VK, SourceLocation L,
1257 const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
1258 NonOdrUseReason NOUR = NOUR_None);
1259
1260 static DeclRefExpr *
1261 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1262 SourceLocation TemplateKWLoc, ValueDecl *D,
1263 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1264 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1265 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1266 NonOdrUseReason NOUR = NOUR_None);
1267
1268 static DeclRefExpr *
1269 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1270 SourceLocation TemplateKWLoc, ValueDecl *D,
1271 bool RefersToEnclosingVariableOrCapture,
1272 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1273 NamedDecl *FoundD = nullptr,
1274 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1275 NonOdrUseReason NOUR = NOUR_None);
1276
1277 /// Construct an empty declaration reference expression.
1278 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
1279 bool HasFoundDecl,
1280 bool HasTemplateKWAndArgsInfo,
1281 unsigned NumTemplateArgs);
1282
1283 ValueDecl *getDecl() { return D; }
1284 const ValueDecl *getDecl() const { return D; }
1285 void setDecl(ValueDecl *NewD);
1286
1287 DeclarationNameInfo getNameInfo() const {
1288 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
1289 }
1290
1291 SourceLocation getLocation() const { return DeclRefExprBits.Loc; }
1292 void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; }
1293 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
1294 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
1295
1296 /// Determine whether this declaration reference was preceded by a
1297 /// C++ nested-name-specifier, e.g., \c N::foo.
1298 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1299
1300 /// If the name was qualified, retrieves the nested-name-specifier
1301 /// that precedes the name, with source-location information.
1302 NestedNameSpecifierLoc getQualifierLoc() const {
1303 if (!hasQualifier())
1304 return NestedNameSpecifierLoc();
1305 return *getTrailingObjects<NestedNameSpecifierLoc>();
1306 }
1307
1308 /// If the name was qualified, retrieves the nested-name-specifier
1309 /// that precedes the name. Otherwise, returns NULL.
1310 NestedNameSpecifier *getQualifier() const {
1311 return getQualifierLoc().getNestedNameSpecifier();
1312 }
1313
1314 /// Get the NamedDecl through which this reference occurred.
1315 ///
1316 /// This Decl may be different from the ValueDecl actually referred to in the
1317 /// presence of using declarations, etc. It always returns non-NULL, and may
1318 /// simple return the ValueDecl when appropriate.
1319
1320 NamedDecl *getFoundDecl() {
1321 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1322 }
1323
1324 /// Get the NamedDecl through which this reference occurred.
1325 /// See non-const variant.
1326 const NamedDecl *getFoundDecl() const {
1327 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1328 }
1329
1330 bool hasTemplateKWAndArgsInfo() const {
1331 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1332 }
1333
1334 /// Retrieve the location of the template keyword preceding
1335 /// this name, if any.
1336 SourceLocation getTemplateKeywordLoc() const {
1337 if (!hasTemplateKWAndArgsInfo())
1338 return SourceLocation();
1339 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1340 }
1341
1342 /// Retrieve the location of the left angle bracket starting the
1343 /// explicit template argument list following the name, if any.
1344 SourceLocation getLAngleLoc() const {
1345 if (!hasTemplateKWAndArgsInfo())
1346 return SourceLocation();
1347 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1348 }
1349
1350 /// Retrieve the location of the right angle bracket ending the
1351 /// explicit template argument list following the name, if any.
1352 SourceLocation getRAngleLoc() const {
1353 if (!hasTemplateKWAndArgsInfo())
1354 return SourceLocation();
1355 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1356 }
1357
1358 /// Determines whether the name in this declaration reference
1359 /// was preceded by the template keyword.
1360 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1361
1362 /// Determines whether this declaration reference was followed by an
1363 /// explicit template argument list.
1364 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1365
1366 /// Copies the template arguments (if present) into the given
1367 /// structure.
1368 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1369 if (hasExplicitTemplateArgs())
1370 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1371 getTrailingObjects<TemplateArgumentLoc>(), List);
1372 }
1373
1374 /// Retrieve the template arguments provided as part of this
1375 /// template-id.
1376 const TemplateArgumentLoc *getTemplateArgs() const {
1377 if (!hasExplicitTemplateArgs())
1378 return nullptr;
1379 return getTrailingObjects<TemplateArgumentLoc>();
1380 }
1381
1382 /// Retrieve the number of template arguments provided as part of this
1383 /// template-id.
1384 unsigned getNumTemplateArgs() const {
1385 if (!hasExplicitTemplateArgs())
1386 return 0;
1387 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1388 }
1389
1390 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1391 return {getTemplateArgs(), getNumTemplateArgs()};
1392 }
1393
1394 /// Returns true if this expression refers to a function that
1395 /// was resolved from an overloaded set having size greater than 1.
1396 bool hadMultipleCandidates() const {
1397 return DeclRefExprBits.HadMultipleCandidates;
1398 }
1399 /// Sets the flag telling whether this expression refers to
1400 /// a function that was resolved from an overloaded set having size
1401 /// greater than 1.
1402 void setHadMultipleCandidates(bool V = true) {
1403 DeclRefExprBits.HadMultipleCandidates = V;
1404 }
1405
1406 /// Is this expression a non-odr-use reference, and if so, why?
1407 NonOdrUseReason isNonOdrUse() const {
1408 return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
1409 }
1410
1411 /// Does this DeclRefExpr refer to an enclosing local or a captured
1412 /// variable?
1413 bool refersToEnclosingVariableOrCapture() const {
1414 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1415 }
1416
1417 static bool classof(const Stmt *T) {
1418 return T->getStmtClass() == DeclRefExprClass;
1419 }
1420
1421 // Iterators
1422 child_range children() {
1423 return child_range(child_iterator(), child_iterator());
1424 }
1425
1426 const_child_range children() const {
1427 return const_child_range(const_child_iterator(), const_child_iterator());
1428 }
1429};
1430
1431/// Used by IntegerLiteral/FloatingLiteral to store the numeric without
1432/// leaking memory.
1433///
1434/// For large floats/integers, APFloat/APInt will allocate memory from the heap
1435/// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1436/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1437/// the APFloat/APInt values will never get freed. APNumericStorage uses
1438/// ASTContext's allocator for memory allocation.
1439class APNumericStorage {
1440 union {
1441 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1442 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1443 };
1444 unsigned BitWidth;
1445
1446 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1447
1448 APNumericStorage(const APNumericStorage &) = delete;
1449 void operator=(const APNumericStorage &) = delete;
1450
1451protected:
1452 APNumericStorage() : VAL(0), BitWidth(0) { }
1453
1454 llvm::APInt getIntValue() const {
1455 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1456 if (NumWords > 1)
1457 return llvm::APInt(BitWidth, NumWords, pVal);
1458 else
1459 return llvm::APInt(BitWidth, VAL);
1460 }
1461 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1462};
1463
1464class APIntStorage : private APNumericStorage {
1465public:
1466 llvm::APInt getValue() const { return getIntValue(); }
1467 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1468 setIntValue(C, Val);
1469 }
1470};
1471
1472class APFloatStorage : private APNumericStorage {
1473public:
1474 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1475 return llvm::APFloat(Semantics, getIntValue());
1476 }
1477 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1478 setIntValue(C, Val.bitcastToAPInt());
1479 }
1480};
1481
1482class IntegerLiteral : public Expr, public APIntStorage {
1483 SourceLocation Loc;
1484
1485 /// Construct an empty integer literal.
1486 explicit IntegerLiteral(EmptyShell Empty)
1487 : Expr(IntegerLiteralClass, Empty) { }
1488
1489public:
1490 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1491 // or UnsignedLongLongTy
1492 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1493 SourceLocation l);
1494
1495 /// Returns a new integer literal with value 'V' and type 'type'.
1496 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1497 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1498 /// \param V - the value that the returned integer literal contains.
1499 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1500 QualType type, SourceLocation l);
1501 /// Returns a new empty integer literal.
1502 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1503
1504 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1505 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1506
1507 /// Retrieve the location of the literal.
1508 SourceLocation getLocation() const { return Loc; }
1509
1510 void setLocation(SourceLocation Location) { Loc = Location; }
1511
1512 static bool classof(const Stmt *T) {
1513 return T->getStmtClass() == IntegerLiteralClass;
1514 }
1515
1516 // Iterators
1517 child_range children() {
1518 return child_range(child_iterator(), child_iterator());
1519 }
1520 const_child_range children() const {
1521 return const_child_range(const_child_iterator(), const_child_iterator());
1522 }
1523};
1524
1525class FixedPointLiteral : public Expr, public APIntStorage {
1526 SourceLocation Loc;
1527 unsigned Scale;
1528
1529 /// \brief Construct an empty fixed-point literal.
1530 explicit FixedPointLiteral(EmptyShell Empty)
1531 : Expr(FixedPointLiteralClass, Empty) {}
1532
1533 public:
1534 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1535 SourceLocation l, unsigned Scale);
1536
1537 // Store the int as is without any bit shifting.
1538 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1539 const llvm::APInt &V,
1540 QualType type, SourceLocation l,
1541 unsigned Scale);
1542
1543 /// Returns an empty fixed-point literal.
1544 static FixedPointLiteral *Create(const ASTContext &C, EmptyShell Empty);
1545
1546 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1547 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1548
1549 /// \brief Retrieve the location of the literal.
1550 SourceLocation getLocation() const { return Loc; }
1551
1552 void setLocation(SourceLocation Location) { Loc = Location; }
1553
1554 unsigned getScale() const { return Scale; }
1555 void setScale(unsigned S) { Scale = S; }
1556
1557 static bool classof(const Stmt *T) {
1558 return T->getStmtClass() == FixedPointLiteralClass;
1559 }
1560
1561 std::string getValueAsString(unsigned Radix) const;
1562
1563 // Iterators
1564 child_range children() {
1565 return child_range(child_iterator(), child_iterator());
1566 }
1567 const_child_range children() const {
1568 return const_child_range(const_child_iterator(), const_child_iterator());
1569 }
1570};
1571
1572class CharacterLiteral : public Expr {
1573public:
1574 enum CharacterKind {
1575 Ascii,
1576 Wide,
1577 UTF8,
1578 UTF16,
1579 UTF32
1580 };
1581
1582private:
1583 unsigned Value;
1584 SourceLocation Loc;
1585public:
1586 // type should be IntTy
1587 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1588 SourceLocation l)
1589 : Expr(CharacterLiteralClass, type, VK_PRValue, OK_Ordinary),
1590 Value(value), Loc(l) {
1591 CharacterLiteralBits.Kind = kind;
1592 setDependence(ExprDependence::None);
1593 }
1594
1595 /// Construct an empty character literal.
1596 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1597
1598 SourceLocation getLocation() const { return Loc; }
1599 CharacterKind getKind() const {
1600 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1601 }
1602
1603 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1604 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1605
1606 unsigned getValue() const { return Value; }
1607
1608 void setLocation(SourceLocation Location) { Loc = Location; }
1609 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1610 void setValue(unsigned Val) { Value = Val; }
1611
1612 static bool classof(const Stmt *T) {
1613 return T->getStmtClass() == CharacterLiteralClass;
1614 }
1615
1616 static void print(unsigned val, CharacterKind Kind, raw_ostream &OS);
1617
1618 // Iterators
1619 child_range children() {
1620 return child_range(child_iterator(), child_iterator());
1621 }
1622 const_child_range children() const {
1623 return const_child_range(const_child_iterator(), const_child_iterator());
1624 }
1625};
1626
1627class FloatingLiteral : public Expr, private APFloatStorage {
1628 SourceLocation Loc;
1629
1630 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1631 QualType Type, SourceLocation L);
1632
1633 /// Construct an empty floating-point literal.
1634 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1635
1636public:
1637 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1638 bool isexact, QualType Type, SourceLocation L);
1639 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1640
1641 llvm::APFloat getValue() const {
1642 return APFloatStorage::getValue(getSemantics());
1643 }
1644 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1645 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics")((void)0);
1646 APFloatStorage::setValue(C, Val);
1647 }
1648
1649 /// Get a raw enumeration value representing the floating-point semantics of
1650 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1651 llvm::APFloatBase::Semantics getRawSemantics() const {
1652 return static_cast<llvm::APFloatBase::Semantics>(
1653 FloatingLiteralBits.Semantics);
1654 }
1655
1656 /// Set the raw enumeration value representing the floating-point semantics of
1657 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1658 void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
1659 FloatingLiteralBits.Semantics = Sem;
1660 }
1661
1662 /// Return the APFloat semantics this literal uses.
1663 const llvm::fltSemantics &getSemantics() const {
1664 return llvm::APFloatBase::EnumToSemantics(
1665 static_cast<llvm::APFloatBase::Semantics>(
1666 FloatingLiteralBits.Semantics));
1667 }
1668
1669 /// Set the APFloat semantics this literal uses.
1670 void setSemantics(const llvm::fltSemantics &Sem) {
1671 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
1672 }
1673
1674 bool isExact() const { return FloatingLiteralBits.IsExact; }
1675 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1676
1677 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1678 /// double. Note that this may cause loss of precision, but is useful for
1679 /// debugging dumps, etc.
1680 double getValueAsApproximateDouble() const;
1681
1682 SourceLocation getLocation() const { return Loc; }
1683 void setLocation(SourceLocation L) { Loc = L; }
1684
1685 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1686 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1687
1688 static bool classof(const Stmt *T) {
1689 return T->getStmtClass() == FloatingLiteralClass;
1690 }
1691
1692 // Iterators
1693 child_range children() {
1694 return child_range(child_iterator(), child_iterator());
1695 }
1696 const_child_range children() const {
1697 return const_child_range(const_child_iterator(), const_child_iterator());
1698 }
1699};
1700
1701/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1702/// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1703/// IntegerLiteral classes. Instances of this class always have a Complex type
1704/// whose element type matches the subexpression.
1705///
1706class ImaginaryLiteral : public Expr {
1707 Stmt *Val;
1708public:
1709 ImaginaryLiteral(Expr *val, QualType Ty)
1710 : Expr(ImaginaryLiteralClass, Ty, VK_PRValue, OK_Ordinary), Val(val) {
1711 setDependence(ExprDependence::None);
1712 }
1713
1714 /// Build an empty imaginary literal.
1715 explicit ImaginaryLiteral(EmptyShell Empty)
1716 : Expr(ImaginaryLiteralClass, Empty) { }
1717
1718 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1719 Expr *getSubExpr() { return cast<Expr>(Val); }
1720 void setSubExpr(Expr *E) { Val = E; }
1721
1722 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1723 return Val->getBeginLoc();
1724 }
1725 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Val->getEndLoc(); }
1726
1727 static bool classof(const Stmt *T) {
1728 return T->getStmtClass() == ImaginaryLiteralClass;
1729 }
1730
1731 // Iterators
1732 child_range children() { return child_range(&Val, &Val+1); }
1733 const_child_range children() const {
1734 return const_child_range(&Val, &Val + 1);
1735 }
1736};
1737
1738/// StringLiteral - This represents a string literal expression, e.g. "foo"
1739/// or L"bar" (wide strings). The actual string data can be obtained with
1740/// getBytes() and is NOT null-terminated. The length of the string data is
1741/// determined by calling getByteLength().
1742///
1743/// The C type for a string is always a ConstantArrayType. In C++, the char
1744/// type is const qualified, in C it is not.
1745///
1746/// Note that strings in C can be formed by concatenation of multiple string
1747/// literal pptokens in translation phase #6. This keeps track of the locations
1748/// of each of these pieces.
1749///
1750/// Strings in C can also be truncated and extended by assigning into arrays,
1751/// e.g. with constructs like:
1752/// char X[2] = "foobar";
1753/// In this case, getByteLength() will return 6, but the string literal will
1754/// have type "char[2]".
1755class StringLiteral final
1756 : public Expr,
1757 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
1758 char> {
1759 friend class ASTStmtReader;
1760 friend TrailingObjects;
1761
1762 /// StringLiteral is followed by several trailing objects. They are in order:
1763 ///
1764 /// * A single unsigned storing the length in characters of this string. The
1765 /// length in bytes is this length times the width of a single character.
1766 /// Always present and stored as a trailing objects because storing it in
1767 /// StringLiteral would increase the size of StringLiteral by sizeof(void *)
1768 /// due to alignment requirements. If you add some data to StringLiteral,
1769 /// consider moving it inside StringLiteral.
1770 ///
1771 /// * An array of getNumConcatenated() SourceLocation, one for each of the
1772 /// token this string is made of.
1773 ///
1774 /// * An array of getByteLength() char used to store the string data.
1775
1776public:
1777 enum StringKind { Ascii, Wide, UTF8, UTF16, UTF32 };
1778
1779private:
1780 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
1781 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1782 return getNumConcatenated();
1783 }
1784
1785 unsigned numTrailingObjects(OverloadToken<char>) const {
1786 return getByteLength();
1787 }
1788
1789 char *getStrDataAsChar() { return getTrailingObjects<char>(); }
1790 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
1791
1792 const uint16_t *getStrDataAsUInt16() const {
1793 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
1794 }
1795
1796 const uint32_t *getStrDataAsUInt32() const {
1797 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
1798 }
1799
1800 /// Build a string literal.
1801 StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind,
1802 bool Pascal, QualType Ty, const SourceLocation *Loc,
1803 unsigned NumConcatenated);
1804
1805 /// Build an empty string literal.
1806 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
1807 unsigned CharByteWidth);
1808
1809 /// Map a target and string kind to the appropriate character width.
1810 static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK);
1811
1812 /// Set one of the string literal token.
1813 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1814 assert(TokNum < getNumConcatenated() && "Invalid tok number")((void)0);
1815 getTrailingObjects<SourceLocation>()[TokNum] = L;
1816 }
1817
1818public:
1819 /// This is the "fully general" constructor that allows representation of
1820 /// strings formed from multiple concatenated tokens.
1821 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1822 StringKind Kind, bool Pascal, QualType Ty,
1823 const SourceLocation *Loc,
1824 unsigned NumConcatenated);
1825
1826 /// Simple constructor for string literals made from one token.
1827 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1828 StringKind Kind, bool Pascal, QualType Ty,
1829 SourceLocation Loc) {
1830 return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1);
1831 }
1832
1833 /// Construct an empty string literal.
1834 static StringLiteral *CreateEmpty(const ASTContext &Ctx,
1835 unsigned NumConcatenated, unsigned Length,
1836 unsigned CharByteWidth);
1837
1838 StringRef getString() const {
1839 assert(getCharByteWidth() == 1 &&((void)0)
1840 "This function is used in places that assume strings use char")((void)0);
1841 return StringRef(getStrDataAsChar(), getByteLength());
1842 }
1843
1844 /// Allow access to clients that need the byte representation, such as
1845 /// ASTWriterStmt::VisitStringLiteral().
1846 StringRef getBytes() const {
1847 // FIXME: StringRef may not be the right type to use as a result for this.
1848 return StringRef(getStrDataAsChar(), getByteLength());
1849 }
1850
1851 void outputString(raw_ostream &OS) const;
1852
1853 uint32_t getCodeUnit(size_t i) const {
1854 assert(i < getLength() && "out of bounds access")((void)0);
1855 switch (getCharByteWidth()) {
1856 case 1:
1857 return static_cast<unsigned char>(getStrDataAsChar()[i]);
1858 case 2:
1859 return getStrDataAsUInt16()[i];
1860 case 4:
1861 return getStrDataAsUInt32()[i];
1862 }
1863 llvm_unreachable("Unsupported character width!")__builtin_unreachable();
1864 }
1865
1866 unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
1867 unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
1868 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
1869
1870 StringKind getKind() const {
1871 return static_cast<StringKind>(StringLiteralBits.Kind);
1872 }
1873
1874 bool isAscii() const { return getKind() == Ascii; }
1875 bool isWide() const { return getKind() == Wide; }
1876 bool isUTF8() const { return getKind() == UTF8; }
1877 bool isUTF16() const { return getKind() == UTF16; }
1878 bool isUTF32() const { return getKind() == UTF32; }
1879 bool isPascal() const { return StringLiteralBits.IsPascal; }
1880
1881 bool containsNonAscii() const {
1882 for (auto c : getString())
1883 if (!isASCII(c))
1884 return true;
1885 return false;
1886 }
1887
1888 bool containsNonAsciiOrNull() const {
1889 for (auto c : getString())
1890 if (!isASCII(c) || !c)
1891 return true;
1892 return false;
1893 }
1894
1895 /// getNumConcatenated - Get the number of string literal tokens that were
1896 /// concatenated in translation phase #6 to form this string literal.
1897 unsigned getNumConcatenated() const {
1898 return StringLiteralBits.NumConcatenated;
1899 }
1900
1901 /// Get one of the string literal token.
1902 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1903 assert(TokNum < getNumConcatenated() && "Invalid tok number")((void)0);
1904 return getTrailingObjects<SourceLocation>()[TokNum];
1905 }
1906
1907 /// getLocationOfByte - Return a source location that points to the specified
1908 /// byte of this string literal.
1909 ///
1910 /// Strings are amazingly complex. They can be formed from multiple tokens
1911 /// and can have escape sequences in them in addition to the usual trigraph
1912 /// and escaped newline business. This routine handles this complexity.
1913 ///
1914 SourceLocation
1915 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1916 const LangOptions &Features, const TargetInfo &Target,
1917 unsigned *StartToken = nullptr,
1918 unsigned *StartTokenByteOffset = nullptr) const;
1919
1920 typedef const SourceLocation *tokloc_iterator;
1921
1922 tokloc_iterator tokloc_begin() const {
1923 return getTrailingObjects<SourceLocation>();
1924 }
1925
1926 tokloc_iterator tokloc_end() const {
1927 return getTrailingObjects<SourceLocation>() + getNumConcatenated();
1928 }
1929
1930 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return *tokloc_begin(); }
1931 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return *(tokloc_end() - 1); }
1932
1933 static bool classof(const Stmt *T) {
1934 return T->getStmtClass() == StringLiteralClass;
1935 }
1936
1937 // Iterators
1938 child_range children() {
1939 return child_range(child_iterator(), child_iterator());
1940 }
1941 const_child_range children() const {
1942 return const_child_range(const_child_iterator(), const_child_iterator());
1943 }
1944};
1945
1946/// [C99 6.4.2.2] - A predefined identifier such as __func__.
1947class PredefinedExpr final
1948 : public Expr,
1949 private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
1950 friend class ASTStmtReader;
1951 friend TrailingObjects;
1952
1953 // PredefinedExpr is optionally followed by a single trailing
1954 // "Stmt *" for the predefined identifier. It is present if and only if
1955 // hasFunctionName() is true and is always a "StringLiteral *".
1956
1957public:
1958 enum IdentKind {
1959 Func,
1960 Function,
1961 LFunction, // Same as Function, but as wide string.
1962 FuncDName,
1963 FuncSig,
1964 LFuncSig, // Same as FuncSig, but as as wide string
1965 PrettyFunction,
1966 /// The same as PrettyFunction, except that the
1967 /// 'virtual' keyword is omitted for virtual member functions.
1968 PrettyFunctionNoVirtual
1969 };
1970
1971private:
1972 PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
1973 StringLiteral *SL);
1974
1975 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
1976
1977 /// True if this PredefinedExpr has storage for a function name.
1978 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
1979
1980 void setFunctionName(StringLiteral *SL) {
1981 assert(hasFunctionName() &&((void)0)
1982 "This PredefinedExpr has no storage for a function name!")((void)0);
1983 *getTrailingObjects<Stmt *>() = SL;
1984 }
1985
1986public:
1987 /// Create a PredefinedExpr.
1988 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
1989 QualType FNTy, IdentKind IK, StringLiteral *SL);
1990
1991 /// Create an empty PredefinedExpr.
1992 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
1993 bool HasFunctionName);
1994
1995 IdentKind getIdentKind() const {
1996 return static_cast<IdentKind>(PredefinedExprBits.Kind);
1997 }
1998
1999 SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
2000 void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
2001
2002 StringLiteral *getFunctionName() {
2003 return hasFunctionName()
2004 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2005 : nullptr;
2006 }
2007
2008 const StringLiteral *getFunctionName() const {
2009 return hasFunctionName()
2010 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2011 : nullptr;
2012 }
2013
2014 static StringRef getIdentKindName(IdentKind IK);
2015 StringRef getIdentKindName() const {
2016 return getIdentKindName(getIdentKind());
2017 }
2018
2019 static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl);
2020
2021 SourceLocation getBeginLoc() const { return getLocation(); }
2022 SourceLocation getEndLoc() const { return getLocation(); }
2023
2024 static bool classof(const Stmt *T) {
2025 return T->getStmtClass() == PredefinedExprClass;
2026 }
2027
2028 // Iterators
2029 child_range children() {
2030 return child_range(getTrailingObjects<Stmt *>(),
2031 getTrailingObjects<Stmt *>() + hasFunctionName());
2032 }
2033
2034 const_child_range children() const {
2035 return const_child_range(getTrailingObjects<Stmt *>(),
2036 getTrailingObjects<Stmt *>() + hasFunctionName());
2037 }
2038};
2039
2040// This represents a use of the __builtin_sycl_unique_stable_name, which takes a
2041// type-id, and at CodeGen time emits a unique string representation of the
2042// type in a way that permits us to properly encode information about the SYCL
2043// kernels.
2044class SYCLUniqueStableNameExpr final : public Expr {
2045 friend class ASTStmtReader;
2046 SourceLocation OpLoc, LParen, RParen;
2047 TypeSourceInfo *TypeInfo;
2048
2049 SYCLUniqueStableNameExpr(EmptyShell Empty, QualType ResultTy);
2050 SYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen,
2051 SourceLocation RParen, QualType ResultTy,
2052 TypeSourceInfo *TSI);
2053
2054 void setTypeSourceInfo(TypeSourceInfo *Ty) { TypeInfo = Ty; }
2055
2056 void setLocation(SourceLocation L) { OpLoc = L; }
2057 void setLParenLocation(SourceLocation L) { LParen = L; }
2058 void setRParenLocation(SourceLocation L) { RParen = L; }
2059
2060public:
2061 TypeSourceInfo *getTypeSourceInfo() { return TypeInfo; }
2062
2063 const TypeSourceInfo *getTypeSourceInfo() const { return TypeInfo; }
2064
2065 static SYCLUniqueStableNameExpr *
2066 Create(const ASTContext &Ctx, SourceLocation OpLoc, SourceLocation LParen,
2067 SourceLocation RParen, TypeSourceInfo *TSI);
2068
2069 static SYCLUniqueStableNameExpr *CreateEmpty(const ASTContext &Ctx);
2070
2071 SourceLocation getBeginLoc() const { return getLocation(); }
2072 SourceLocation getEndLoc() const { return RParen; }
2073 SourceLocation getLocation() const { return OpLoc; }
2074 SourceLocation getLParenLocation() const { return LParen; }
2075 SourceLocation getRParenLocation() const { return RParen; }
2076
2077 static bool classof(const Stmt *T) {
2078 return T->getStmtClass() == SYCLUniqueStableNameExprClass;
2079 }
2080
2081 // Iterators
2082 child_range children() {
2083 return child_range(child_iterator(), child_iterator());
2084 }
2085
2086 const_child_range children() const {
2087 return const_child_range(const_child_iterator(), const_child_iterator());
2088 }
2089
2090 // Convenience function to generate the name of the currently stored type.
2091 std::string ComputeName(ASTContext &Context) const;
2092
2093 // Get the generated name of the type. Note that this only works after all
2094 // kernels have been instantiated.
2095 static std::string ComputeName(ASTContext &Context, QualType Ty);
2096};
2097
2098/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
2099/// AST node is only formed if full location information is requested.
2100class ParenExpr : public Expr {
2101 SourceLocation L, R;
2102 Stmt *Val;
2103public:
2104 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
2105 : Expr(ParenExprClass, val->getType(), val->getValueKind(),
2106 val->getObjectKind()),
2107 L(l), R(r), Val(val) {
2108 setDependence(computeDependence(this));
2109 }
2110
2111 /// Construct an empty parenthesized expression.
2112 explicit ParenExpr(EmptyShell Empty)
2113 : Expr(ParenExprClass, Empty) { }
2114
2115 const Expr *getSubExpr() const { return cast<Expr>(Val); }
2116 Expr *getSubExpr() { return cast<Expr>(Val); }
2117 void setSubExpr(Expr *E) { Val = E; }
2118
2119 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return L; }
2120 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return R; }
2121
2122 /// Get the location of the left parentheses '('.
2123 SourceLocation getLParen() const { return L; }
2124 void setLParen(SourceLocation Loc) { L = Loc; }
2125
2126 /// Get the location of the right parentheses ')'.
2127 SourceLocation getRParen() const { return R; }
2128 void setRParen(SourceLocation Loc) { R = Loc; }
2129
2130 static bool classof(const Stmt *T) {
2131 return T->getStmtClass() == ParenExprClass;
2132 }
2133
2134 // Iterators
2135 child_range children() { return child_range(&Val, &Val+1); }
2136 const_child_range children() const {
2137 return const_child_range(&Val, &Val + 1);
2138 }
2139};
2140
2141/// UnaryOperator - This represents the unary-expression's (except sizeof and
2142/// alignof), the postinc/postdec operators from postfix-expression, and various
2143/// extensions.
2144///
2145/// Notes on various nodes:
2146///
2147/// Real/Imag - These return the real/imag part of a complex operand. If
2148/// applied to a non-complex value, the former returns its operand and the
2149/// later returns zero in the type of the operand.
2150///
2151class UnaryOperator final
2152 : public Expr,
2153 private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> {
2154 Stmt *Val;
2155
2156 size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const {
2157 return UnaryOperatorBits.HasFPFeatures ? 1 : 0;
2158 }
2159
2160 FPOptionsOverride &getTrailingFPFeatures() {
2161 assert(UnaryOperatorBits.HasFPFeatures)((void)0);
2162 return *getTrailingObjects<FPOptionsOverride>();
2163 }
2164
2165 const FPOptionsOverride &getTrailingFPFeatures() const {
2166 assert(UnaryOperatorBits.HasFPFeatures)((void)0);
2167 return *getTrailingObjects<FPOptionsOverride>();
2168 }
2169
2170public:
2171 typedef UnaryOperatorKind Opcode;
2172
2173protected:
2174 UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type,
2175 ExprValueKind VK, ExprObjectKind OK, SourceLocation l,
2176 bool CanOverflow, FPOptionsOverride FPFeatures);
2177
2178 /// Build an empty unary operator.
2179 explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty)
2180 : Expr(UnaryOperatorClass, Empty) {
2181 UnaryOperatorBits.Opc = UO_AddrOf;
2182 UnaryOperatorBits.HasFPFeatures = HasFPFeatures;
2183 }
2184
2185public:
2186 static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
2187
2188 static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc,
2189 QualType type, ExprValueKind VK,
2190 ExprObjectKind OK, SourceLocation l,
2191 bool CanOverflow, FPOptionsOverride FPFeatures);
2192
2193 Opcode getOpcode() const {
2194 return static_cast<Opcode>(UnaryOperatorBits.Opc);
2195 }
2196 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
2197
2198 Expr *getSubExpr() const { return cast<Expr>(Val); }
2199 void setSubExpr(Expr *E) { Val = E; }
2200
2201 /// getOperatorLoc - Return the location of the operator.
2202 SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; }
2203 void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; }
2204
2205 /// Returns true if the unary operator can cause an overflow. For instance,
2206 /// signed int i = INT_MAX; i++;
2207 /// signed char c = CHAR_MAX; c++;
2208 /// Due to integer promotions, c++ is promoted to an int before the postfix
2209 /// increment, and the result is an int that cannot overflow. However, i++
2210 /// can overflow.
2211 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
2212 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
2213
2214 // Get the FP contractability status of this operator. Only meaningful for
2215 // operations on floating point types.
2216 bool isFPContractableWithinStatement(const LangOptions &LO) const {
2217 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
2218 }
2219
2220 // Get the FENV_ACCESS status of this operator. Only meaningful for
2221 // operations on floating point types.
2222 bool isFEnvAccessOn(const LangOptions &LO) const {
2223 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
2224 }
2225
2226 /// isPostfix - Return true if this is a postfix operation, like x++.
2227 static bool isPostfix(Opcode Op) {
2228 return Op == UO_PostInc || Op == UO_PostDec;
2229 }
2230
2231 /// isPrefix - Return true if this is a prefix operation, like --x.
2232 static bool isPrefix(Opcode Op) {
2233 return Op == UO_PreInc || Op == UO_PreDec;
2234 }
2235
2236 bool isPrefix() const { return isPrefix(getOpcode()); }
2237 bool isPostfix() const { return isPostfix(getOpcode()); }
2238
2239 static bool isIncrementOp(Opcode Op) {
2240 return Op == UO_PreInc || Op == UO_PostInc;
2241 }
2242 bool isIncrementOp() const {
2243 return isIncrementOp(getOpcode());
2244 }
2245
2246 static bool isDecrementOp(Opcode Op) {
2247 return Op == UO_PreDec || Op == UO_PostDec;
2248 }
2249 bool isDecrementOp() const {
2250 return isDecrementOp(getOpcode());
2251 }
2252
2253 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
2254 bool isIncrementDecrementOp() const {
2255 return isIncrementDecrementOp(getOpcode());
2256 }
2257
2258 static bool isArithmeticOp(Opcode Op) {
2259 return Op >= UO_Plus && Op <= UO_LNot;
2260 }
2261 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
2262
2263 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2264 /// corresponds to, e.g. "sizeof" or "[pre]++"
2265 static StringRef getOpcodeStr(Opcode Op);
2266
2267 /// Retrieve the unary opcode that corresponds to the given
2268 /// overloaded operator.
2269 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
2270
2271 /// Retrieve the overloaded operator kind that corresponds to
2272 /// the given unary opcode.
2273 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2274
2275 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
2276 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
2277 }
2278 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
2279 return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
2280 }
2281 SourceLocation getExprLoc() const { return getOperatorLoc(); }
2282
2283 static bool classof(const Stmt *T) {
2284 return T->getStmtClass() == UnaryOperatorClass;
2285 }
2286
2287 // Iterators
2288 child_range children() { return child_range(&Val, &Val+1); }
2289 const_child_range children() const {
2290 return const_child_range(&Val, &Val + 1);
2291 }
2292
2293 /// Is FPFeatures in Trailing Storage?
2294 bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; }
2295
2296 /// Get FPFeatures from trailing storage.
2297 FPOptionsOverride getStoredFPFeatures() const {
2298 return getTrailingFPFeatures();
2299 }
2300
2301protected:
2302 /// Set FPFeatures in trailing storage, used only by Serialization
2303 void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
2304
2305public:
2306 // Get the FP features status of this operator. Only meaningful for
2307 // operations on floating point types.
2308 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
2309 if (UnaryOperatorBits.HasFPFeatures)
2310 return getStoredFPFeatures().applyOverrides(LO);
2311 return FPOptions::defaultWithoutTrailingStorage(LO);
2312 }
2313 FPOptionsOverride getFPOptionsOverride() const {
2314 if (UnaryOperatorBits.HasFPFeatures)
2315 return getStoredFPFeatures();
2316 return FPOptionsOverride();
2317 }
2318
2319 friend TrailingObjects;
2320 friend class ASTReader;
2321 friend class ASTStmtReader;
2322 friend class ASTStmtWriter;
2323};
2324
2325/// Helper class for OffsetOfExpr.
2326
2327// __builtin_offsetof(type, identifier(.identifier|[expr])*)
2328class OffsetOfNode {
2329public:
2330 /// The kind of offsetof node we have.
2331 enum Kind {
2332 /// An index into an array.
2333 Array = 0x00,
2334 /// A field.
2335 Field = 0x01,
2336 /// A field in a dependent type, known only by its name.
2337 Identifier = 0x02,
2338 /// An implicit indirection through a C++ base class, when the
2339 /// field found is in a base class.
2340 Base = 0x03
2341 };
2342
2343private:
2344 enum { MaskBits = 2, Mask = 0x03 };
2345
2346 /// The source range that covers this part of the designator.
2347 SourceRange Range;
2348
2349 /// The data describing the designator, which comes in three
2350 /// different forms, depending on the lower two bits.
2351 /// - An unsigned index into the array of Expr*'s stored after this node
2352 /// in memory, for [constant-expression] designators.
2353 /// - A FieldDecl*, for references to a known field.
2354 /// - An IdentifierInfo*, for references to a field with a given name
2355 /// when the class type is dependent.
2356 /// - A CXXBaseSpecifier*, for references that look at a field in a
2357 /// base class.
2358 uintptr_t Data;
2359
2360public:
2361 /// Create an offsetof node that refers to an array element.
2362 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2363 SourceLocation RBracketLoc)
2364 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2365
2366 /// Create an offsetof node that refers to a field.
2367 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
2368 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2369 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2370
2371 /// Create an offsetof node that refers to an identifier.
2372 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
2373 SourceLocation NameLoc)
2374 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2375 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2376
2377 /// Create an offsetof node that refers into a C++ base class.
2378 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
2379 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2380
2381 /// Determine what kind of offsetof node this is.
2382 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2383
2384 /// For an array element node, returns the index into the array
2385 /// of expressions.
2386 unsigned getArrayExprIndex() const {
2387 assert(getKind() == Array)((void)0);
2388 return Data >> 2;
2389 }
2390
2391 /// For a field offsetof node, returns the field.
2392 FieldDecl *getField() const {
2393 assert(getKind() == Field)((void)0);
2394 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2395 }
2396
2397 /// For a field or identifier offsetof node, returns the name of
2398 /// the field.
2399 IdentifierInfo *getFieldName() const;
2400
2401 /// For a base class node, returns the base specifier.
2402 CXXBaseSpecifier *getBase() const {
2403 assert(getKind() == Base)((void)0);
2404 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2405 }
2406
2407 /// Retrieve the source range that covers this offsetof node.
2408 ///
2409 /// For an array element node, the source range contains the locations of
2410 /// the square brackets. For a field or identifier node, the source range
2411 /// contains the location of the period (if there is one) and the
2412 /// identifier.
2413 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
2414 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
2415 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
2416};
2417
2418/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2419/// offsetof(record-type, member-designator). For example, given:
2420/// @code
2421/// struct S {
2422/// float f;
2423/// double d;
2424/// };
2425/// struct T {
2426/// int i;
2427/// struct S s[10];
2428/// };
2429/// @endcode
2430/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2431
2432class OffsetOfExpr final
2433 : public Expr,
2434 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2435 SourceLocation OperatorLoc, RParenLoc;
2436 // Base type;
2437 TypeSourceInfo *TSInfo;
2438 // Number of sub-components (i.e. instances of OffsetOfNode).
2439 unsigned NumComps;
2440 // Number of sub-expressions (i.e. array subscript expressions).
2441 unsigned NumExprs;
2442
2443 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2444 return NumComps;
2445 }
2446
2447 OffsetOfExpr(const ASTContext &C, QualType type,
2448 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2449 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2450 SourceLocation RParenLoc);
2451
2452 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2453 : Expr(OffsetOfExprClass, EmptyShell()),
2454 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2455
2456public:
2457
2458 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2459 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2460 ArrayRef<OffsetOfNode> comps,
2461 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2462
2463 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2464 unsigned NumComps, unsigned NumExprs);
2465
2466 /// getOperatorLoc - Return the location of the operator.
2467 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2468 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2469
2470 /// Return the location of the right parentheses.
2471 SourceLocation getRParenLoc() const { return RParenLoc; }
2472 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2473
2474 TypeSourceInfo *getTypeSourceInfo() const {
2475 return TSInfo;
2476 }
2477 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2478 TSInfo = tsi;
2479 }
2480
2481 const OffsetOfNode &getComponent(unsigned Idx) const {
2482 assert(Idx < NumComps && "Subscript out of range")((void)0);
2483 return getTrailingObjects<OffsetOfNode>()[Idx];
2484 }
2485
2486 void setComponent(unsigned Idx, OffsetOfNode ON) {
2487 assert(Idx < NumComps && "Subscript out of range")((void)0);
2488 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2489 }
2490
2491 unsigned getNumComponents() const {
2492 return NumComps;
2493 }
2494
2495 Expr* getIndexExpr(unsigned Idx) {
2496 assert(Idx < NumExprs && "Subscript out of range")((void)0);
2497 return getTrailingObjects<Expr *>()[Idx];
2498 }
2499
2500 const Expr *getIndexExpr(unsigned Idx) const {
2501 assert(Idx < NumExprs && "Subscript out of range")((void)0);
2502 return getTrailingObjects<Expr *>()[Idx];
2503 }
2504
2505 void setIndexExpr(unsigned Idx, Expr* E) {
2506 assert(Idx < NumComps && "Subscript out of range")((void)0);
2507 getTrailingObjects<Expr *>()[Idx] = E;
2508 }
2509
2510 unsigned getNumExpressions() const {
2511 return NumExprs;
2512 }
2513
2514 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return OperatorLoc; }
2515 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
2516
2517 static bool classof(const Stmt *T) {
2518 return T->getStmtClass() == OffsetOfExprClass;
2519 }
2520
2521 // Iterators
2522 child_range children() {
2523 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2524 return child_range(begin, begin + NumExprs);
2525 }
2526 const_child_range children() const {
2527 Stmt *const *begin =
2528 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2529 return const_child_range(begin, begin + NumExprs);
2530 }
2531 friend TrailingObjects;
2532};
2533
2534/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2535/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2536/// vec_step (OpenCL 1.1 6.11.12).
2537class UnaryExprOrTypeTraitExpr : public Expr {
2538 union {
2539 TypeSourceInfo *Ty;
2540 Stmt *Ex;
2541 } Argument;
2542 SourceLocation OpLoc, RParenLoc;
2543
2544public:
2545 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2546 QualType resultType, SourceLocation op,
2547 SourceLocation rp)
2548 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue,
2549 OK_Ordinary),
2550 OpLoc(op), RParenLoc(rp) {
2551 assert(ExprKind <= UETT_Last && "invalid enum value!")((void)0);
2552 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2553 assert(static_cast<unsigned>(ExprKind) ==((void)0)
2554 UnaryExprOrTypeTraitExprBits.Kind &&((void)0)
2555 "UnaryExprOrTypeTraitExprBits.Kind overflow!")((void)0);
2556 UnaryExprOrTypeTraitExprBits.IsType = true;
2557 Argument.Ty = TInfo;
2558 setDependence(computeDependence(this));
2559 }
2560
2561 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2562 QualType resultType, SourceLocation op,
2563 SourceLocation rp);
2564
2565 /// Construct an empty sizeof/alignof expression.
2566 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2567 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2568
2569 UnaryExprOrTypeTrait getKind() const {
2570 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2571 }
2572 void setKind(UnaryExprOrTypeTrait K) {
2573 assert(K <= UETT_Last && "invalid enum value!")((void)0);
2574 UnaryExprOrTypeTraitExprBits.Kind = K;
2575 assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind &&((void)0)
2576 "UnaryExprOrTypeTraitExprBits.Kind overflow!")((void)0);
2577 }
2578
2579 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2580 QualType getArgumentType() const {
2581 return getArgumentTypeInfo()->getType();
2582 }
2583 TypeSourceInfo *getArgumentTypeInfo() const {
2584 assert(isArgumentType() && "calling getArgumentType() when arg is expr")((void)0);
2585 return Argument.Ty;
2586 }
2587 Expr *getArgumentExpr() {
2588 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type")((void)0);
2589 return static_cast<Expr*>(Argument.Ex);
2590 }
2591 const Expr *getArgumentExpr() const {
2592 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2593 }
2594
2595 void setArgument(Expr *E) {
2596 Argument.Ex = E;
2597 UnaryExprOrTypeTraitExprBits.IsType = false;
2598 }
2599 void setArgument(TypeSourceInfo *TInfo) {
2600 Argument.Ty = TInfo;
2601 UnaryExprOrTypeTraitExprBits.IsType = true;
2602 }
2603
2604 /// Gets the argument type, or the type of the argument expression, whichever
2605 /// is appropriate.
2606 QualType getTypeOfArgument() const {
2607 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2608 }
2609
2610 SourceLocation getOperatorLoc() const { return OpLoc; }
2611 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2612
2613 SourceLocation getRParenLoc() const { return RParenLoc; }
2614 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2615
2616 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return OpLoc; }
2617 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
2618
2619 static bool classof(const Stmt *T) {
2620 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2621 }
2622
2623 // Iterators
2624 child_range children();
2625 const_child_range children() const;
2626};
2627
2628//===----------------------------------------------------------------------===//
2629// Postfix Operators.
2630//===----------------------------------------------------------------------===//
2631
2632/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2633class ArraySubscriptExpr : public Expr {
2634 enum { LHS, RHS, END_EXPR };
2635 Stmt *SubExprs[END_EXPR];
2636
2637 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
2638
2639public:
2640 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK,
2641 ExprObjectKind OK, SourceLocation rbracketloc)
2642 : Expr(ArraySubscriptExprClass, t, VK, OK) {
2643 SubExprs[LHS] = lhs;
2644 SubExprs[RHS] = rhs;
2645 ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc;
2646 setDependence(computeDependence(this));
2647 }
2648
2649 /// Create an empty array subscript expression.
2650 explicit ArraySubscriptExpr(EmptyShell Shell)
2651 : Expr(ArraySubscriptExprClass, Shell) { }
2652
2653 /// An array access can be written A[4] or 4[A] (both are equivalent).
2654 /// - getBase() and getIdx() always present the normalized view: A[4].
2655 /// In this case getBase() returns "A" and getIdx() returns "4".
2656 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2657 /// 4[A] getLHS() returns "4".
2658 /// Note: Because vector element access is also written A[4] we must
2659 /// predicate the format conversion in getBase and getIdx only on the
2660 /// the type of the RHS, as it is possible for the LHS to be a vector of
2661 /// integer type
2662 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2663 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2664 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2665
2666 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2667 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2668 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2669
2670 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
2671 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
2672
2673 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
2674 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
2675
2676 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
2677 return getLHS()->getBeginLoc();
2678 }
2679 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2680
2681 SourceLocation getRBracketLoc() const {
2682 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2683 }
2684 void setRBracketLoc(SourceLocation L) {
2685 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2686 }
2687
2688 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
2689 return getBase()->getExprLoc();
2690 }
2691
2692 static bool classof(const Stmt *T) {
2693 return T->getStmtClass() == ArraySubscriptExprClass;
2694 }
2695
2696 // Iterators
2697 child_range children() {
2698 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2699 }
2700 const_child_range children() const {
2701 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2702 }
2703};
2704
2705/// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType
2706/// extension.
2707/// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set
2708/// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and
2709/// ColumnIdx refer to valid expressions). Incomplete matrix expressions only
2710/// exist during the initial construction of the AST.
2711class MatrixSubscriptExpr : public Expr {
2712 enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR };
2713 Stmt *SubExprs[END_EXPR];
2714
2715public:
2716 MatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, QualType T,
2717 SourceLocation RBracketLoc)
2718 : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(),
2719 OK_MatrixComponent) {
2720 SubExprs[BASE] = Base;
2721 SubExprs[ROW_IDX] = RowIdx;
2722 SubExprs[COLUMN_IDX] = ColumnIdx;
2723 ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc;
2724 setDependence(computeDependence(this));
2725 }
2726
2727 /// Create an empty matrix subscript expression.
2728 explicit MatrixSubscriptExpr(EmptyShell Shell)
2729 : Expr(MatrixSubscriptExprClass, Shell) {}
2730
2731 bool isIncomplete() const {
2732 bool IsIncomplete = hasPlaceholderType(BuiltinType::IncompleteMatrixIdx);
2733 assert((SubExprs[COLUMN_IDX] || IsIncomplete) &&((void)0)
2734 "expressions without column index must be marked as incomplete")((void)0);
2735 return IsIncomplete;
2736 }
2737 Expr *getBase() { return cast<Expr>(SubExprs[BASE]); }
2738 const Expr *getBase() const { return cast<Expr>(SubExprs[BASE]); }
2739 void setBase(Expr *E) { SubExprs[BASE] = E; }
2740
2741 Expr *getRowIdx() { return cast<Expr>(SubExprs[ROW_IDX]); }
2742 const Expr *getRowIdx() const { return cast<Expr>(SubExprs[ROW_IDX]); }
2743 void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; }
2744
2745 Expr *getColumnIdx() { return cast_or_null<Expr>(SubExprs[COLUMN_IDX]); }
2746 const Expr *getColumnIdx() const {
2747 assert(!isIncomplete() &&((void)0)
2748 "cannot get the column index of an incomplete expression")((void)0);
2749 return cast<Expr>(SubExprs[COLUMN_IDX]);
2750 }
2751 void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; }
2752
2753 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
2754 return getBase()->getBeginLoc();
2755 }
2756
2757 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2758
2759 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
2760 return getBase()->getExprLoc();
2761 }
2762
2763 SourceLocation getRBracketLoc() const {
2764 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2765 }
2766 void setRBracketLoc(SourceLocation L) {
2767 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2768 }
2769
2770 static bool classof(const Stmt *T) {
2771 return T->getStmtClass() == MatrixSubscriptExprClass;
2772 }
2773
2774 // Iterators
2775 child_range children() {
2776 return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2777 }
2778 const_child_range children() const {
2779 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2780 }
2781};
2782
2783/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2784/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2785/// while its subclasses may represent alternative syntax that (semantically)
2786/// results in a function call. For example, CXXOperatorCallExpr is
2787/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2788/// "str1 + str2" to resolve to a function call.
2789class CallExpr : public Expr {
2790 enum { FN = 0, PREARGS_START = 1 };
2791
2792 /// The number of arguments in the call expression.
2793 unsigned NumArgs;
2794
2795 /// The location of the right parenthese. This has a different meaning for
2796 /// the derived classes of CallExpr.
2797 SourceLocation RParenLoc;
2798
2799 // CallExpr store some data in trailing objects. However since CallExpr
2800 // is used a base of other expression classes we cannot use
2801 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
2802 // and casts.
2803 //
2804 // The trailing objects are in order:
2805 //
2806 // * A single "Stmt *" for the callee expression.
2807 //
2808 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
2809 //
2810 // * An array of getNumArgs() "Stmt *" for the argument expressions.
2811 //
2812 // * An optional of type FPOptionsOverride.
2813 //
2814 // Note that we store the offset in bytes from the this pointer to the start
2815 // of the trailing objects. It would be perfectly possible to compute it
2816 // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
2817 // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
2818 // compute this once and then load the offset from the bit-fields of Stmt,
2819 // instead of re-computing the offset each time the trailing objects are
2820 // accessed.
2821
2822 /// Return a pointer to the start of the trailing array of "Stmt *".
2823 Stmt **getTrailingStmts() {
2824 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
2825 CallExprBits.OffsetToTrailingObjects);
2826 }
2827 Stmt *const *getTrailingStmts() const {
2828 return const_cast<CallExpr *>(this)->getTrailingStmts();
2829 }
2830
2831 /// Map a statement class to the appropriate offset in bytes from the
2832 /// this pointer to the trailing objects.
2833 static unsigned offsetToTrailingObjects(StmtClass SC);
2834
2835 unsigned getSizeOfTrailingStmts() const {
2836 return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *);
2837 }
2838
2839 size_t getOffsetOfTrailingFPFeatures() const {
2840 assert(hasStoredFPFeatures())((void)0);
2841 return CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts();
2842 }
2843
2844public:
2845 enum class ADLCallKind : bool { NotADL, UsesADL };
2846 static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
2847 static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL;
2848
2849protected:
2850 /// Build a call expression, assuming that appropriate storage has been
2851 /// allocated for the trailing objects.
2852 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
2853 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2854 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
2855 unsigned MinNumArgs, ADLCallKind UsesADL);
2856
2857 /// Build an empty call expression, for deserialization.
2858 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
2859 bool hasFPFeatures, EmptyShell Empty);
2860
2861 /// Return the size in bytes needed for the trailing objects.
2862 /// Used by the derived classes to allocate the right amount of storage.
2863 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs,
2864 bool HasFPFeatures) {
2865 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) +
2866 HasFPFeatures * sizeof(FPOptionsOverride);
2867 }
2868
2869 Stmt *getPreArg(unsigned I) {
2870 assert(I < getNumPreArgs() && "Prearg access out of range!")((void)0);
2871 return getTrailingStmts()[PREARGS_START + I];
2872 }
2873 const Stmt *getPreArg(unsigned I) const {
2874 assert(I < getNumPreArgs() && "Prearg access out of range!")((void)0);
2875 return getTrailingStmts()[PREARGS_START + I];
2876 }
2877 void setPreArg(unsigned I, Stmt *PreArg) {
2878 assert(I < getNumPreArgs() && "Prearg access out of range!")((void)0);
2879 getTrailingStmts()[PREARGS_START + I] = PreArg;
2880 }
2881
2882 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2883
2884 /// Return a pointer to the trailing FPOptions
2885 FPOptionsOverride *getTrailingFPFeatures() {
2886 assert(hasStoredFPFeatures())((void)0);
2887 return reinterpret_cast<FPOptionsOverride *>(
2888 reinterpret_cast<char *>(this) + CallExprBits.OffsetToTrailingObjects +
2889 getSizeOfTrailingStmts());
2890 }
2891 const FPOptionsOverride *getTrailingFPFeatures() const {
2892 assert(hasStoredFPFeatures())((void)0);
2893 return reinterpret_cast<const FPOptionsOverride *>(
2894 reinterpret_cast<const char *>(this) +
2895 CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts());
2896 }
2897
2898public:
2899 /// Create a call expression.
2900 /// \param Fn The callee expression,
2901 /// \param Args The argument array,
2902 /// \param Ty The type of the call expression (which is *not* the return
2903 /// type in general),
2904 /// \param VK The value kind of the call expression (lvalue, rvalue, ...),
2905 /// \param RParenLoc The location of the right parenthesis in the call
2906 /// expression.
2907 /// \param FPFeatures Floating-point features associated with the call,
2908 /// \param MinNumArgs Specifies the minimum number of arguments. The actual
2909 /// number of arguments will be the greater of Args.size()
2910 /// and MinNumArgs. This is used in a few places to allocate
2911 /// enough storage for the default arguments.
2912 /// \param UsesADL Specifies whether the callee was found through
2913 /// argument-dependent lookup.
2914 ///
2915 /// Note that you can use CreateTemporary if you need a temporary call
2916 /// expression on the stack.
2917 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
2918 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2919 SourceLocation RParenLoc,
2920 FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0,
2921 ADLCallKind UsesADL = NotADL);
2922
2923 /// Create a temporary call expression with no arguments in the memory
2924 /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
2925 /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
2926 ///
2927 /// \code{.cpp}
2928 /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
2929 /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc);
2930 /// \endcode
2931 static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
2932 ExprValueKind VK, SourceLocation RParenLoc,
2933 ADLCallKind UsesADL = NotADL);
2934
2935 /// Create an empty call expression, for deserialization.
2936 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
2937 bool HasFPFeatures, EmptyShell Empty);
2938
2939 Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
2940 const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
2941 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
2942
2943 ADLCallKind getADLCallKind() const {
2944 return static_cast<ADLCallKind>(CallExprBits.UsesADL);
2945 }
2946 void setADLCallKind(ADLCallKind V = UsesADL) {
2947 CallExprBits.UsesADL = static_cast<bool>(V);
2948 }
2949 bool usesADL() const { return getADLCallKind() == UsesADL; }
2950
2951 bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
2952
2953 Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
2954 const Decl *getCalleeDecl() const {
2955 return getCallee()->getReferencedDeclOfCallee();
2956 }
2957
2958 /// If the callee is a FunctionDecl, return it. Otherwise return null.
2959 FunctionDecl *getDirectCallee() {
2960 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2961 }
2962 const FunctionDecl *getDirectCallee() const {
2963 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2964 }
2965
2966 /// getNumArgs - Return the number of actual arguments to this call.
2967 unsigned getNumArgs() const { return NumArgs; }
2968
2969 /// Retrieve the call arguments.
2970 Expr **getArgs() {
2971 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
2972 getNumPreArgs());
2973 }
2974 const Expr *const *getArgs() const {
2975 return reinterpret_cast<const Expr *const *>(
2976 getTrailingStmts() + PREARGS_START + getNumPreArgs());
2977 }
2978
2979 /// getArg - Return the specified argument.
2980 Expr *getArg(unsigned Arg) {
2981 assert(Arg < getNumArgs() && "Arg access out of range!")((void)0);
2982 return getArgs()[Arg];
2983 }
2984 const Expr *getArg(unsigned Arg) const {
2985 assert(Arg < getNumArgs() && "Arg access out of range!")((void)0);
2986 return getArgs()[Arg];
2987 }
2988
2989 /// setArg - Set the specified argument.
2990 /// ! the dependence bits might be stale after calling this setter, it is
2991 /// *caller*'s responsibility to recompute them by calling
2992 /// computeDependence().
2993 void setArg(unsigned Arg, Expr *ArgExpr) {
2994 assert(Arg < getNumArgs() && "Arg access out of range!")((void)0);
2995 getArgs()[Arg] = ArgExpr;
2996 }
2997
2998 /// Compute and set dependence bits.
2999 void computeDependence() {
3000 setDependence(clang::computeDependence(
3001 this, llvm::makeArrayRef(
3002 reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START),
3003 getNumPreArgs())));
3004 }
3005
3006 /// Reduce the number of arguments in this call expression. This is used for
3007 /// example during error recovery to drop extra arguments. There is no way
3008 /// to perform the opposite because: 1.) We don't track how much storage
3009 /// we have for the argument array 2.) This would potentially require growing
3010 /// the argument array, something we cannot support since the arguments are
3011 /// stored in a trailing array.
3012 void shrinkNumArgs(unsigned NewNumArgs) {
3013 assert((NewNumArgs <= getNumArgs()) &&((void)0)
3014 "shrinkNumArgs cannot increase the number of arguments!")((void)0);
3015 NumArgs = NewNumArgs;
3016 }
3017
3018 /// Bluntly set a new number of arguments without doing any checks whatsoever.
3019 /// Only used during construction of a CallExpr in a few places in Sema.
3020 /// FIXME: Find a way to remove it.
3021 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
3022
3023 typedef ExprIterator arg_iterator;
3024 typedef ConstExprIterator const_arg_iterator;
3025 typedef llvm::iterator_range<arg_iterator> arg_range;
3026 typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
3027
3028 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
3029 const_arg_range arguments() const {
3030 return const_arg_range(arg_begin(), arg_end());
3031 }
3032
3033 arg_iterator arg_begin() {
3034 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3035 }
3036 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
3037
3038 const_arg_iterator arg_begin() const {
3039 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3040 }
3041 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
3042
3043 /// This method provides fast access to all the subexpressions of
3044 /// a CallExpr without going through the slower virtual child_iterator
3045 /// interface. This provides efficient reverse iteration of the
3046 /// subexpressions. This is currently used for CFG construction.
3047 ArrayRef<Stmt *> getRawSubExprs() {
3048 return llvm::makeArrayRef(getTrailingStmts(),
3049 PREARGS_START + getNumPreArgs() + getNumArgs());
3050 }
3051
3052 /// getNumCommas - Return the number of commas that must have been present in
3053 /// this function call.
3054 unsigned getNumCommas() const { return getNumArgs() ? getNumArgs() - 1 : 0; }
3055
3056 /// Get FPOptionsOverride from trailing storage.
3057 FPOptionsOverride getStoredFPFeatures() const {
3058 assert(hasStoredFPFeatures())((void)0);
3059 return *getTrailingFPFeatures();
3060 }
3061 /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
3062 void setStoredFPFeatures(FPOptionsOverride F) {
3063 assert(hasStoredFPFeatures())((void)0);
3064 *getTrailingFPFeatures() = F;
3065 }
3066
3067 // Get the FP features status of this operator. Only meaningful for
3068 // operations on floating point types.
3069 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3070 if (hasStoredFPFeatures())
3071 return getStoredFPFeatures().applyOverrides(LO);
3072 return FPOptions::defaultWithoutTrailingStorage(LO);
3073 }
3074
3075 FPOptionsOverride getFPFeatures() const {
3076 if (hasStoredFPFeatures())
3077 return getStoredFPFeatures();
3078 return FPOptionsOverride();
3079 }
3080
3081 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
3082 /// of the callee. If not, return 0.
3083 unsigned getBuiltinCallee() const;
3084
3085 /// Returns \c true if this is a call to a builtin which does not
3086 /// evaluate side-effects within its arguments.
3087 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
3088
3089 /// getCallReturnType - Get the return type of the call expr. This is not
3090 /// always the type of the expr itself, if the return type is a reference
3091 /// type.
3092 QualType getCallReturnType(const ASTContext &Ctx) const;
3093
3094 /// Returns the WarnUnusedResultAttr that is either declared on the called
3095 /// function, or its return type declaration.
3096 const Attr *getUnusedResultAttr(const ASTContext &Ctx) const;
3097
3098 /// Returns true if this call expression should warn on unused results.
3099 bool hasUnusedResultAttr(const ASTContext &Ctx) const {
3100 return getUnusedResultAttr(Ctx) != nullptr;
3101 }
3102
3103 SourceLocation getRParenLoc() const { return RParenLoc; }
3104 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3105
3106 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
3107 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
3108
3109 /// Return true if this is a call to __assume() or __builtin_assume() with
3110 /// a non-value-dependent constant parameter evaluating as false.
3111 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
3112
3113 /// Used by Sema to implement MSVC-compatible delayed name lookup.
3114 /// (Usually Exprs themselves should set dependence).
3115 void markDependentForPostponedNameLookup() {
3116 setDependence(getDependence() | ExprDependence::TypeValueInstantiation);
3117 }
3118
3119 bool isCallToStdMove() const {
3120 const FunctionDecl *FD = getDirectCallee();
3121 return getNumArgs() == 1 && FD && FD->isInStdNamespace() &&
3122 FD->getIdentifier() && FD->getIdentifier()->isStr("move");
3123 }
3124
3125 static bool classof(const Stmt *T) {
3126 return T->getStmtClass() >= firstCallExprConstant &&
3127 T->getStmtClass() <= lastCallExprConstant;
3128 }
3129
3130 // Iterators
3131 child_range children() {
3132 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
3133 getNumPreArgs() + getNumArgs());
3134 }
3135
3136 const_child_range children() const {
3137 return const_child_range(getTrailingStmts(),
3138 getTrailingStmts() + PREARGS_START +
3139 getNumPreArgs() + getNumArgs());
3140 }
3141};
3142
3143/// Extra data stored in some MemberExpr objects.
3144struct MemberExprNameQualifier {
3145 /// The nested-name-specifier that qualifies the name, including
3146 /// source-location information.
3147 NestedNameSpecifierLoc QualifierLoc;
3148
3149 /// The DeclAccessPair through which the MemberDecl was found due to
3150 /// name qualifiers.
3151 DeclAccessPair FoundDecl;
3152};
3153
3154/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
3155///
3156class MemberExpr final
3157 : public Expr,
3158 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
3159 ASTTemplateKWAndArgsInfo,
3160 TemplateArgumentLoc> {
3161 friend class ASTReader;
3162 friend class ASTStmtReader;
3163 friend class ASTStmtWriter;
3164 friend TrailingObjects;
3165
3166 /// Base - the expression for the base pointer or structure references. In
3167 /// X.F, this is "X".
3168 Stmt *Base;
3169
3170 /// MemberDecl - This is the decl being referenced by the field/member name.
3171 /// In X.F, this is the decl referenced by F.
3172 ValueDecl *MemberDecl;
3173
3174 /// MemberDNLoc - Provides source/type location info for the
3175 /// declaration name embedded in MemberDecl.
3176 DeclarationNameLoc MemberDNLoc;
3177
3178 /// MemberLoc - This is the location of the member name.
3179 SourceLocation MemberLoc;
3180
3181 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
3182 return hasQualifierOrFoundDecl();
3183 }
3184
3185 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3186 return hasTemplateKWAndArgsInfo();
3187 }
3188
3189 bool hasQualifierOrFoundDecl() const {
3190 return MemberExprBits.HasQualifierOrFoundDecl;
3191 }
3192
3193 bool hasTemplateKWAndArgsInfo() const {
3194 return MemberExprBits.HasTemplateKWAndArgsInfo;
3195 }
3196
3197 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
3198 ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo,
3199 QualType T, ExprValueKind VK, ExprObjectKind OK,
3200 NonOdrUseReason NOUR);
3201 MemberExpr(EmptyShell Empty)
3202 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
3203
3204public:
3205 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
3206 SourceLocation OperatorLoc,
3207 NestedNameSpecifierLoc QualifierLoc,
3208 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
3209 DeclAccessPair FoundDecl,
3210 DeclarationNameInfo MemberNameInfo,
3211 const TemplateArgumentListInfo *TemplateArgs,
3212 QualType T, ExprValueKind VK, ExprObjectKind OK,
3213 NonOdrUseReason NOUR);
3214
3215 /// Create an implicit MemberExpr, with no location, qualifier, template
3216 /// arguments, and so on. Suitable only for non-static member access.
3217 static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base,
3218 bool IsArrow, ValueDecl *MemberDecl,
3219 QualType T, ExprValueKind VK,
3220 ExprObjectKind OK) {
3221 return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
3222 SourceLocation(), MemberDecl,
3223 DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()),
3224 DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None);
3225 }
3226
3227 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
3228 bool HasFoundDecl,
3229 bool HasTemplateKWAndArgsInfo,
3230 unsigned NumTemplateArgs);
3231
3232 void setBase(Expr *E) { Base = E; }
3233 Expr *getBase() const { return cast<Expr>(Base); }
3234
3235 /// Retrieve the member declaration to which this expression refers.
3236 ///
3237 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
3238 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
3239 ValueDecl *getMemberDecl() const { return MemberDecl; }
3240 void setMemberDecl(ValueDecl *D);
3241
3242 /// Retrieves the declaration found by lookup.
3243 DeclAccessPair getFoundDecl() const {
3244 if (!hasQualifierOrFoundDecl())
3245 return DeclAccessPair::make(getMemberDecl(),
3246 getMemberDecl()->getAccess());
3247 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
3248 }
3249
3250 /// Determines whether this member expression actually had
3251 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
3252 /// x->Base::foo.
3253 bool hasQualifier() const { return getQualifier() != nullptr; }
3254
3255 /// If the member name was qualified, retrieves the
3256 /// nested-name-specifier that precedes the member name, with source-location
3257 /// information.
3258 NestedNameSpecifierLoc getQualifierLoc() const {
3259 if (!hasQualifierOrFoundDecl())
3260 return NestedNameSpecifierLoc();
3261 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
3262 }
3263
3264 /// If the member name was qualified, retrieves the
3265 /// nested-name-specifier that precedes the member name. Otherwise, returns
3266 /// NULL.
3267 NestedNameSpecifier *getQualifier() const {
3268 return getQualifierLoc().getNestedNameSpecifier();
3269 }
3270
3271 /// Retrieve the location of the template keyword preceding
3272 /// the member name, if any.
3273 SourceLocation getTemplateKeywordLoc() const {
3274 if (!hasTemplateKWAndArgsInfo())
3275 return SourceLocation();
3276 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3277 }
3278
3279 /// Retrieve the location of the left angle bracket starting the
3280 /// explicit template argument list following the member name, if any.
3281 SourceLocation getLAngleLoc() const {
3282 if (!hasTemplateKWAndArgsInfo())
3283 return SourceLocation();
3284 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3285 }
3286
3287 /// Retrieve the location of the right angle bracket ending the
3288 /// explicit template argument list following the member name, if any.
3289 SourceLocation getRAngleLoc() const {
3290 if (!hasTemplateKWAndArgsInfo())
3291 return SourceLocation();
3292 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3293 }
3294
3295 /// Determines whether the member name was preceded by the template keyword.
3296 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3297
3298 /// Determines whether the member name was followed by an
3299 /// explicit template argument list.
3300 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3301
3302 /// Copies the template arguments (if present) into the given
3303 /// structure.
3304 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3305 if (hasExplicitTemplateArgs())
3306 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3307 getTrailingObjects<TemplateArgumentLoc>(), List);
3308 }
3309
3310 /// Retrieve the template arguments provided as part of this
3311 /// template-id.
3312 const TemplateArgumentLoc *getTemplateArgs() const {
3313 if (!hasExplicitTemplateArgs())
3314 return nullptr;
3315
3316 return getTrailingObjects<TemplateArgumentLoc>();
3317 }
3318
3319 /// Retrieve the number of template arguments provided as part of this
3320 /// template-id.
3321 unsigned getNumTemplateArgs() const {
3322 if (!hasExplicitTemplateArgs())
3323 return 0;
3324
3325 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3326 }
3327
3328 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3329 return {getTemplateArgs(), getNumTemplateArgs()};
3330 }
3331
3332 /// Retrieve the member declaration name info.
3333 DeclarationNameInfo getMemberNameInfo() const {
3334 return DeclarationNameInfo(MemberDecl->getDeclName(),
3335 MemberLoc, MemberDNLoc);
3336 }
3337
3338 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
3339
3340 bool isArrow() const { return MemberExprBits.IsArrow; }
3341 void setArrow(bool A) { MemberExprBits.IsArrow = A; }
3342
3343 /// getMemberLoc - Return the location of the "member", in X->F, it is the
3344 /// location of 'F'.
3345 SourceLocation getMemberLoc() const { return MemberLoc; }
3346 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
3347
3348 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
3349 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
3350
3351 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { return MemberLoc; }
3352
3353 /// Determine whether the base of this explicit is implicit.
3354 bool isImplicitAccess() const {
3355 return getBase() && getBase()->isImplicitCXXThis();
3356 }
3357
3358 /// Returns true if this member expression refers to a method that
3359 /// was resolved from an overloaded set having size greater than 1.
3360 bool hadMultipleCandidates() const {
3361 return MemberExprBits.HadMultipleCandidates;
3362 }
3363 /// Sets the flag telling whether this expression refers to
3364 /// a method that was resolved from an overloaded set having size
3365 /// greater than 1.
3366 void setHadMultipleCandidates(bool V = true) {
3367 MemberExprBits.HadMultipleCandidates = V;
3368 }
3369
3370 /// Returns true if virtual dispatch is performed.
3371 /// If the member access is fully qualified, (i.e. X::f()), virtual
3372 /// dispatching is not performed. In -fapple-kext mode qualified
3373 /// calls to virtual method will still go through the vtable.
3374 bool performsVirtualDispatch(const LangOptions &LO) const {
3375 return LO.AppleKext || !hasQualifier();
3376 }
3377
3378 /// Is this expression a non-odr-use reference, and if so, why?
3379 /// This is only meaningful if the named member is a static member.
3380 NonOdrUseReason isNonOdrUse() const {
3381 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
3382 }
3383
3384 static bool classof(const Stmt *T) {
3385 return T->getStmtClass() == MemberExprClass;
3386 }
3387
3388 // Iterators
3389 child_range children() { return child_range(&Base, &Base+1); }
3390 const_child_range children() const {
3391 return const_child_range(&Base, &Base + 1);
3392 }
3393};
3394
3395/// CompoundLiteralExpr - [C99 6.5.2.5]
3396///
3397class CompoundLiteralExpr : public Expr {
3398 /// LParenLoc - If non-null, this is the location of the left paren in a
3399 /// compound literal like "(int){4}". This can be null if this is a
3400 /// synthesized compound expression.
3401 SourceLocation LParenLoc;
3402
3403 /// The type as written. This can be an incomplete array type, in
3404 /// which case the actual expression type will be different.
3405 /// The int part of the pair stores whether this expr is file scope.
3406 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
3407 Stmt *Init;
3408public:
3409 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
3410 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
3411 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary),
3412 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {
3413 setDependence(computeDependence(this));
3414 }
3415
3416 /// Construct an empty compound literal.
3417 explicit CompoundLiteralExpr(EmptyShell Empty)
3418 : Expr(CompoundLiteralExprClass, Empty) { }
3419
3420 const Expr *getInitializer() const { return cast<Expr>(Init); }
3421 Expr *getInitializer() { return cast<Expr>(Init); }
3422 void setInitializer(Expr *E) { Init = E; }
3423
3424 bool isFileScope() const { return TInfoAndScope.getInt(); }
3425 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
3426
3427 SourceLocation getLParenLoc() const { return LParenLoc; }
3428 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3429
3430 TypeSourceInfo *getTypeSourceInfo() const {
3431 return TInfoAndScope.getPointer();
3432 }
3433 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
3434 TInfoAndScope.setPointer(tinfo);
3435 }
3436
3437 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3438 // FIXME: Init should never be null.
3439 if (!Init)
3440 return SourceLocation();
3441 if (LParenLoc.isInvalid())
3442 return Init->getBeginLoc();
3443 return LParenLoc;
3444 }
3445 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3446 // FIXME: Init should never be null.
3447 if (!Init)
3448 return SourceLocation();
3449 return Init->getEndLoc();
3450 }
3451
3452 static bool classof(const Stmt *T) {
3453 return T->getStmtClass() == CompoundLiteralExprClass;
3454 }
3455
3456 // Iterators
3457 child_range children() { return child_range(&Init, &Init+1); }
3458 const_child_range children() const {
3459 return const_child_range(&Init, &Init + 1);
3460 }
3461};
3462
3463/// CastExpr - Base class for type casts, including both implicit
3464/// casts (ImplicitCastExpr) and explicit casts that have some
3465/// representation in the source code (ExplicitCastExpr's derived
3466/// classes).
3467class CastExpr : public Expr {
3468 Stmt *Op;
3469
3470 bool CastConsistency() const;
3471
3472 const CXXBaseSpecifier * const *path_buffer() const {
3473 return const_cast<CastExpr*>(this)->path_buffer();
3474 }
3475 CXXBaseSpecifier **path_buffer();
3476
3477 friend class ASTStmtReader;
3478
3479protected:
3480 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
3481 Expr *op, unsigned BasePathSize, bool HasFPFeatures)
3482 : Expr(SC, ty, VK, OK_Ordinary), Op(op) {
3483 CastExprBits.Kind = kind;
3484 CastExprBits.PartOfExplicitCast = false;
3485 CastExprBits.BasePathSize = BasePathSize;
3486 assert((CastExprBits.BasePathSize == BasePathSize) &&((void)0)
3487 "BasePathSize overflow!")((void)0);
3488 setDependence(computeDependence(this));
3489 assert(CastConsistency())((void)0);
3490 CastExprBits.HasFPFeatures = HasFPFeatures;
3491 }
3492
3493 /// Construct an empty cast.
3494 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize,
3495 bool HasFPFeatures)
3496 : Expr(SC, Empty) {
3497 CastExprBits.PartOfExplicitCast = false;
3498 CastExprBits.BasePathSize = BasePathSize;
3499 CastExprBits.HasFPFeatures = HasFPFeatures;
3500 assert((CastExprBits.BasePathSize == BasePathSize) &&((void)0)
3501 "BasePathSize overflow!")((void)0);
3502 }
3503
3504 /// Return a pointer to the trailing FPOptions.
3505 /// \pre hasStoredFPFeatures() == true
3506 FPOptionsOverride *getTrailingFPFeatures();
3507 const FPOptionsOverride *getTrailingFPFeatures() const {
3508 return const_cast<CastExpr *>(this)->getTrailingFPFeatures();
3509 }
3510
3511public:
3512 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
3513 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
3514
3515 static const char *getCastKindName(CastKind CK);
3516 const char *getCastKindName() const { return getCastKindName(getCastKind()); }
3517
3518 Expr *getSubExpr() { return cast<Expr>(Op); }
3519 const Expr *getSubExpr() const { return cast<Expr>(Op); }
3520 void setSubExpr(Expr *E) { Op = E; }
3521
3522 /// Retrieve the cast subexpression as it was written in the source
3523 /// code, looking through any implicit casts or other intermediate nodes
3524 /// introduced by semantic analysis.
3525 Expr *getSubExprAsWritten();
3526 const Expr *getSubExprAsWritten() const {
3527 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
3528 }
3529
3530 /// If this cast applies a user-defined conversion, retrieve the conversion
3531 /// function that it invokes.
3532 NamedDecl *getConversionFunction() const;
3533
3534 typedef CXXBaseSpecifier **path_iterator;
3535 typedef const CXXBaseSpecifier *const *path_const_iterator;
3536 bool path_empty() const { return path_size() == 0; }
3537 unsigned path_size() const { return CastExprBits.BasePathSize; }
3538 path_iterator path_begin() { return path_buffer(); }
3539 path_iterator path_end() { return path_buffer() + path_size(); }
3540 path_const_iterator path_begin() const { return path_buffer(); }
3541 path_const_iterator path_end() const { return path_buffer() + path_size(); }
3542
3543 llvm::iterator_range<path_iterator> path() {
3544 return llvm::make_range(path_begin(), path_end());
3545 }
3546 llvm::iterator_range<path_const_iterator> path() const {
3547 return llvm::make_range(path_begin(), path_end());
3548 }
3549
3550 const FieldDecl *getTargetUnionField() const {
3551 assert(getCastKind() == CK_ToUnion)((void)0);
3552 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
3553 }
3554
3555 bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; }
3556
3557 /// Get FPOptionsOverride from trailing storage.
3558 FPOptionsOverride getStoredFPFeatures() const {
3559 assert(hasStoredFPFeatures())((void)0);
3560 return *getTrailingFPFeatures();
3561 }
3562
3563 // Get the FP features status of this operation. Only meaningful for
3564 // operations on floating point types.
3565 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3566 if (hasStoredFPFeatures())
3567 return getStoredFPFeatures().applyOverrides(LO);
3568 return FPOptions::defaultWithoutTrailingStorage(LO);
3569 }
3570
3571 FPOptionsOverride getFPFeatures() const {
3572 if (hasStoredFPFeatures())
3573 return getStoredFPFeatures();
3574 return FPOptionsOverride();
3575 }
3576
3577 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
3578 QualType opType);
3579 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
3580 QualType opType);
3581
3582 static bool classof(const Stmt *T) {
3583 return T->getStmtClass() >= firstCastExprConstant &&
3584 T->getStmtClass() <= lastCastExprConstant;
3585 }
3586
3587 // Iterators
3588 child_range children() { return child_range(&Op, &Op+1); }
3589 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
3590};
3591
3592/// ImplicitCastExpr - Allows us to explicitly represent implicit type
3593/// conversions, which have no direct representation in the original
3594/// source code. For example: converting T[]->T*, void f()->void
3595/// (*f)(), float->double, short->int, etc.
3596///
3597/// In C, implicit casts always produce rvalues. However, in C++, an
3598/// implicit cast whose result is being bound to a reference will be
3599/// an lvalue or xvalue. For example:
3600///
3601/// @code
3602/// class Base { };
3603/// class Derived : public Base { };
3604/// Derived &&ref();
3605/// void f(Derived d) {
3606/// Base& b = d; // initializer is an ImplicitCastExpr
3607/// // to an lvalue of type Base
3608/// Base&& r = ref(); // initializer is an ImplicitCastExpr
3609/// // to an xvalue of type Base
3610/// }
3611/// @endcode
3612class ImplicitCastExpr final
3613 : public CastExpr,
3614 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *,
3615 FPOptionsOverride> {
3616
3617 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
3618 unsigned BasePathLength, FPOptionsOverride FPO,
3619 ExprValueKind VK)
3620 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength,
3621 FPO.requiresTrailingStorage()) {
3622 if (hasStoredFPFeatures())
3623 *getTrailingFPFeatures() = FPO;
3624 }
3625
3626 /// Construct an empty implicit cast.
3627 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize,
3628 bool HasFPFeatures)
3629 : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {}
3630
3631 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3632 return path_size();
3633 }
3634
3635public:
3636 enum OnStack_t { OnStack };
3637 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
3638 ExprValueKind VK, FPOptionsOverride FPO)
3639 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0,
3640 FPO.requiresTrailingStorage()) {
3641 if (hasStoredFPFeatures())
3642 *getTrailingFPFeatures() = FPO;
3643 }
3644
3645 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
3646 void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
3647 CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
3648 }
3649
3650 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
3651 CastKind Kind, Expr *Operand,
3652 const CXXCastPath *BasePath,
3653 ExprValueKind Cat, FPOptionsOverride FPO);
3654
3655 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
3656 unsigned PathSize, bool HasFPFeatures);
3657
3658 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3659 return getSubExpr()->getBeginLoc();
3660 }
3661 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3662 return getSubExpr()->getEndLoc();
3663 }
3664
3665 static bool classof(const Stmt *T) {
3666 return T->getStmtClass() == ImplicitCastExprClass;
3667 }
3668
3669 friend TrailingObjects;
3670 friend class CastExpr;
3671};
3672
3673/// ExplicitCastExpr - An explicit cast written in the source
3674/// code.
3675///
3676/// This class is effectively an abstract class, because it provides
3677/// the basic representation of an explicitly-written cast without
3678/// specifying which kind of cast (C cast, functional cast, static
3679/// cast, etc.) was written; specific derived classes represent the
3680/// particular style of cast and its location information.
3681///
3682/// Unlike implicit casts, explicit cast nodes have two different
3683/// types: the type that was written into the source code, and the
3684/// actual type of the expression as determined by semantic
3685/// analysis. These types may differ slightly. For example, in C++ one
3686/// can cast to a reference type, which indicates that the resulting
3687/// expression will be an lvalue or xvalue. The reference type, however,
3688/// will not be used as the type of the expression.
3689class ExplicitCastExpr : public CastExpr {
3690 /// TInfo - Source type info for the (written) type
3691 /// this expression is casting to.
3692 TypeSourceInfo *TInfo;
3693
3694protected:
3695 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
3696 CastKind kind, Expr *op, unsigned PathSize,
3697 bool HasFPFeatures, TypeSourceInfo *writtenTy)
3698 : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures),
3699 TInfo(writtenTy) {}
3700
3701 /// Construct an empty explicit cast.
3702 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
3703 bool HasFPFeatures)
3704 : CastExpr(SC, Shell, PathSize, HasFPFeatures) {}
3705
3706public:
3707 /// getTypeInfoAsWritten - Returns the type source info for the type
3708 /// that this expression is casting to.
3709 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
3710 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3711
3712 /// getTypeAsWritten - Returns the type that this expression is
3713 /// casting to, as written in the source code.
3714 QualType getTypeAsWritten() const { return TInfo->getType(); }
3715
3716 static bool classof(const Stmt *T) {
3717 return T->getStmtClass() >= firstExplicitCastExprConstant &&
3718 T->getStmtClass() <= lastExplicitCastExprConstant;
3719 }
3720};
3721
3722/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3723/// cast in C++ (C++ [expr.cast]), which uses the syntax
3724/// (Type)expr. For example: @c (int)f.
3725class CStyleCastExpr final
3726 : public ExplicitCastExpr,
3727 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *,
3728 FPOptionsOverride> {
3729 SourceLocation LPLoc; // the location of the left paren
3730 SourceLocation RPLoc; // the location of the right paren
3731
3732 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3733 unsigned PathSize, FPOptionsOverride FPO,
3734 TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r)
3735 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3736 FPO.requiresTrailingStorage(), writtenTy),
3737 LPLoc(l), RPLoc(r) {
3738 if (hasStoredFPFeatures())
3739 *getTrailingFPFeatures() = FPO;
3740 }
3741
3742 /// Construct an empty C-style explicit cast.
3743 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize,
3744 bool HasFPFeatures)
3745 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {}
3746
3747 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3748 return path_size();
3749 }
3750
3751public:
3752 static CStyleCastExpr *
3753 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
3754 Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
3755 TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R);
3756
3757 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3758 unsigned PathSize, bool HasFPFeatures);
3759
3760 SourceLocation getLParenLoc() const { return LPLoc; }
3761 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3762
3763 SourceLocation getRParenLoc() const { return RPLoc; }
3764 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3765
3766 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LPLoc; }
3767 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3768 return getSubExpr()->getEndLoc();
3769 }
3770
3771 static bool classof(const Stmt *T) {
3772 return T->getStmtClass() == CStyleCastExprClass;
3773 }
3774
3775 friend TrailingObjects;
3776 friend class CastExpr;
3777};
3778
3779/// A builtin binary operation expression such as "x + y" or "x <= y".
3780///
3781/// This expression node kind describes a builtin binary operation,
3782/// such as "x + y" for integer values "x" and "y". The operands will
3783/// already have been converted to appropriate types (e.g., by
3784/// performing promotions or conversions).
3785///
3786/// In C++, where operators may be overloaded, a different kind of
3787/// expression node (CXXOperatorCallExpr) is used to express the
3788/// invocation of an overloaded operator with operator syntax. Within
3789/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3790/// used to store an expression "x + y" depends on the subexpressions
3791/// for x and y. If neither x or y is type-dependent, and the "+"
3792/// operator resolves to a built-in operation, BinaryOperator will be
3793/// used to express the computation (x and y may still be
3794/// value-dependent). If either x or y is type-dependent, or if the
3795/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3796/// be used to express the computation.
3797class BinaryOperator : public Expr {
3798 enum { LHS, RHS, END_EXPR };
3799 Stmt *SubExprs[END_EXPR];
3800
3801public:
3802 typedef BinaryOperatorKind Opcode;
3803
3804protected:
3805 size_t offsetOfTrailingStorage() const;
3806
3807 /// Return a pointer to the trailing FPOptions
3808 FPOptionsOverride *getTrailingFPFeatures() {
3809 assert(BinaryOperatorBits.HasFPFeatures)((void)0);
3810 return reinterpret_cast<FPOptionsOverride *>(
3811 reinterpret_cast<char *>(this) + offsetOfTrailingStorage());
3812 }
3813 const FPOptionsOverride *getTrailingFPFeatures() const {
3814 assert(BinaryOperatorBits.HasFPFeatures)((void)0);
3815 return reinterpret_cast<const FPOptionsOverride *>(
3816 reinterpret_cast<const char *>(this) + offsetOfTrailingStorage());
3817 }
3818
3819 /// Build a binary operator, assuming that appropriate storage has been
3820 /// allocated for the trailing objects when needed.
3821 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
3822 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
3823 SourceLocation opLoc, FPOptionsOverride FPFeatures);
3824
3825 /// Construct an empty binary operator.
3826 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
3827 BinaryOperatorBits.Opc = BO_Comma;
3828 }
3829
3830public:
3831 static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
3832
3833 static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs,
3834 Opcode opc, QualType ResTy, ExprValueKind VK,
3835 ExprObjectKind OK, SourceLocation opLoc,
3836 FPOptionsOverride FPFeatures);
3837 SourceLocation getExprLoc() const { return getOperatorLoc(); }
3838 SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; }
3839 void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; }
3840
3841 Opcode getOpcode() const {
3842 return static_cast<Opcode>(BinaryOperatorBits.Opc);
3843 }
3844 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
3845
3846 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3847 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3848 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3849 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3850
3851 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3852 return getLHS()->getBeginLoc();
3853 }
3854 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3855 return getRHS()->getEndLoc();
3856 }
3857
3858 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3859 /// corresponds to, e.g. "<<=".
3860 static StringRef getOpcodeStr(Opcode Op);
3861
3862 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3863
3864 /// Retrieve the binary opcode that corresponds to the given
3865 /// overloaded operator.
3866 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3867
3868 /// Retrieve the overloaded operator kind that corresponds to
3869 /// the given binary opcode.
3870 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3871
3872 /// predicates to categorize the respective opcodes.
3873 static bool isPtrMemOp(Opcode Opc) {
3874 return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
3875 }
3876 bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); }
3877
3878 static bool isMultiplicativeOp(Opcode Opc) {
3879 return Opc >= BO_Mul && Opc <= BO_Rem;
3880 }
3881 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
3882 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3883 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3884 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3885 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3886
3887 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3888 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3889
3890 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3891 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3892
3893 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3894 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3895
3896 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
3897 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3898
3899 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
3900 bool isCommaOp() const { return isCommaOp(getOpcode()); }
3901
3902 static Opcode negateComparisonOp(Opcode Opc) {
3903 switch (Opc) {
3904 default:
3905 llvm_unreachable("Not a comparison operator.")__builtin_unreachable();
3906 case BO_LT: return BO_GE;
3907 case BO_GT: return BO_LE;
3908 case BO_LE: return BO_GT;
3909 case BO_GE: return BO_LT;
3910 case BO_EQ: return BO_NE;
3911 case BO_NE: return BO_EQ;
3912 }
3913 }
3914
3915 static Opcode reverseComparisonOp(Opcode Opc) {
3916 switch (Opc) {
3917 default:
3918 llvm_unreachable("Not a comparison operator.")__builtin_unreachable();
3919 case BO_LT: return BO_GT;
3920 case BO_GT: return BO_LT;
3921 case BO_LE: return BO_GE;
3922 case BO_GE: return BO_LE;
3923 case BO_EQ:
3924 case BO_NE:
3925 return Opc;
3926 }
3927 }
3928
3929 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3930 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3931
3932 static bool isAssignmentOp(Opcode Opc) {
3933 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3934 }
3935 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3936
3937 static bool isCompoundAssignmentOp(Opcode Opc) {
3938 return Opc > BO_Assign && Opc <= BO_OrAssign;
3939 }
3940 bool isCompoundAssignmentOp() const {
3941 return isCompoundAssignmentOp(getOpcode());
3942 }
3943 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3944 assert(isCompoundAssignmentOp(Opc))((void)0);
3945 if (Opc >= BO_AndAssign)
3946 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3947 else
3948 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3949 }
3950
3951 static bool isShiftAssignOp(Opcode Opc) {
3952 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3953 }
3954 bool isShiftAssignOp() const {
3955 return isShiftAssignOp(getOpcode());
3956 }
3957
3958 // Return true if a binary operator using the specified opcode and operands
3959 // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3960 // integer to a pointer.
3961 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3962 Expr *LHS, Expr *RHS);
3963
3964 static bool classof(const Stmt *S) {
3965 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3966 S->getStmtClass() <= lastBinaryOperatorConstant;
3967 }
3968
3969 // Iterators
3970 child_range children() {
3971 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3972 }
3973 const_child_range children() const {
3974 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3975 }
3976
3977 /// Set and fetch the bit that shows whether FPFeatures needs to be
3978 /// allocated in Trailing Storage
3979 void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; }
3980 bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; }
3981
3982 /// Get FPFeatures from trailing storage
3983 FPOptionsOverride getStoredFPFeatures() const {
3984 assert(hasStoredFPFeatures())((void)0);
3985 return *getTrailingFPFeatures();
3986 }
3987 /// Set FPFeatures in trailing storage, used only by Serialization
3988 void setStoredFPFeatures(FPOptionsOverride F) {
3989 assert(BinaryOperatorBits.HasFPFeatures)((void)0);
3990 *getTrailingFPFeatures() = F;
3991 }
3992
3993 // Get the FP features status of this operator. Only meaningful for
3994 // operations on floating point types.
3995 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3996 if (BinaryOperatorBits.HasFPFeatures)
3997 return getStoredFPFeatures().applyOverrides(LO);
3998 return FPOptions::defaultWithoutTrailingStorage(LO);
3999 }
4000
4001 // This is used in ASTImporter
4002 FPOptionsOverride getFPFeatures(const LangOptions &LO) const {
4003 if (BinaryOperatorBits.HasFPFeatures)
4004 return getStoredFPFeatures();
4005 return FPOptionsOverride();
4006 }
4007
4008 // Get the FP contractability status of this operator. Only meaningful for
4009 // operations on floating point types.
4010 bool isFPContractableWithinStatement(const LangOptions &LO) const {
4011 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
4012 }
4013
4014 // Get the FENV_ACCESS status of this operator. Only meaningful for
4015 // operations on floating point types.
4016 bool isFEnvAccessOn(const LangOptions &LO) const {
4017 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
4018 }
4019
4020protected:
4021 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
4022 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
4023 SourceLocation opLoc, FPOptionsOverride FPFeatures,
4024 bool dead2);
4025
4026 /// Construct an empty BinaryOperator, SC is CompoundAssignOperator.
4027 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
4028 BinaryOperatorBits.Opc = BO_MulAssign;
4029 }
4030
4031 /// Return the size in bytes needed for the trailing objects.
4032 /// Used to allocate the right amount of storage.
4033 static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
4034 return HasFPFeatures * sizeof(FPOptionsOverride);
4035 }
4036};
4037
4038/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
4039/// track of the type the operation is performed in. Due to the semantics of
4040/// these operators, the operands are promoted, the arithmetic performed, an
4041/// implicit conversion back to the result type done, then the assignment takes
4042/// place. This captures the intermediate type which the computation is done
4043/// in.
4044class CompoundAssignOperator : public BinaryOperator {
4045 QualType ComputationLHSType;
4046 QualType ComputationResultType;
4047
4048 /// Construct an empty CompoundAssignOperator.
4049 explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty,
4050 bool hasFPFeatures)
4051 : BinaryOperator(CompoundAssignOperatorClass, Empty) {}
4052
4053protected:
4054 CompoundAssignOperator(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc,
4055 QualType ResType, ExprValueKind VK, ExprObjectKind OK,
4056 SourceLocation OpLoc, FPOptionsOverride FPFeatures,
4057 QualType CompLHSType, QualType CompResultType)
4058 : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
4059 true),
4060 ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) {
4061 assert(isCompoundAssignmentOp() &&((void)0)
4062 "Only should be used for compound assignments")((void)0);
4063 }
4064
4065public:
4066 static CompoundAssignOperator *CreateEmpty(const ASTContext &C,
4067 bool hasFPFeatures);
4068
4069 static CompoundAssignOperator *
4070 Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
4071 ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc,
4072 FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(),
4073 QualType CompResultType = QualType());
4074
4075 // The two computation types are the type the LHS is converted
4076 // to for the computation and the type of the result; the two are
4077 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
4078 QualType getComputationLHSType() const { return ComputationLHSType; }
4079 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
4080
4081 QualType getComputationResultType() const { return ComputationResultType; }
4082 void setComputationResultType(QualType T) { ComputationResultType = T; }
4083
4084 static bool classof(const Stmt *S) {
4085 return S->getStmtClass() == CompoundAssignOperatorClass;
4086 }
4087};
4088
4089inline size_t BinaryOperator::offsetOfTrailingStorage() const {
4090 assert(BinaryOperatorBits.HasFPFeatures)((void)0);
4091 return isa<CompoundAssignOperator>(this) ? sizeof(CompoundAssignOperator)
4092 : sizeof(BinaryOperator);
4093}
4094
4095/// AbstractConditionalOperator - An abstract base class for
4096/// ConditionalOperator and BinaryConditionalOperator.
4097class AbstractConditionalOperator : public Expr {
4098 SourceLocation QuestionLoc, ColonLoc;
4099 friend class ASTStmtReader;
4100
4101protected:
4102 AbstractConditionalOperator(StmtClass SC, QualType T, ExprValueKind VK,
4103 ExprObjectKind OK, SourceLocation qloc,
4104 SourceLocation cloc)
4105 : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {}
4106
4107 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
4108 : Expr(SC, Empty) { }
4109
4110public:
4111 // getCond - Return the expression representing the condition for
4112 // the ?: operator.
4113 Expr *getCond() const;
4114
4115 // getTrueExpr - Return the subexpression representing the value of
4116 // the expression if the condition evaluates to true.
4117 Expr *getTrueExpr() const;
4118
4119 // getFalseExpr - Return the subexpression representing the value of
4120 // the expression if the condition evaluates to false. This is
4121 // the same as getRHS.
4122 Expr *getFalseExpr() const;
4123
4124 SourceLocation getQuestionLoc() const { return QuestionLoc; }
4125 SourceLocation getColonLoc() const { return ColonLoc; }
4126
4127 static bool classof(const Stmt *T) {
4128 return T->getStmtClass() == ConditionalOperatorClass ||
4129 T->getStmtClass() == BinaryConditionalOperatorClass;
4130 }
4131};
4132
4133/// ConditionalOperator - The ?: ternary operator. The GNU "missing
4134/// middle" extension is a BinaryConditionalOperator.
4135class ConditionalOperator : public AbstractConditionalOperator {
4136 enum { COND, LHS, RHS, END_EXPR };
4137 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4138
4139 friend class ASTStmtReader;
4140public:
4141 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
4142 SourceLocation CLoc, Expr *rhs, QualType t,
4143 ExprValueKind VK, ExprObjectKind OK)
4144 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
4145 CLoc) {
4146 SubExprs[COND] = cond;
4147 SubExprs[LHS] = lhs;
4148 SubExprs[RHS] = rhs;
4149 setDependence(computeDependence(this));
4150 }
4151
4152 /// Build an empty conditional operator.
4153 explicit ConditionalOperator(EmptyShell Empty)
4154 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
4155
4156 // getCond - Return the expression representing the condition for
4157 // the ?: operator.
4158 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4159
4160 // getTrueExpr - Return the subexpression representing the value of
4161 // the expression if the condition evaluates to true.
4162 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
4163
4164 // getFalseExpr - Return the subexpression representing the value of
4165 // the expression if the condition evaluates to false. This is
4166 // the same as getRHS.
4167 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
4168
4169 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
4170 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
4171
4172 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
4173 return getCond()->getBeginLoc();
4174 }
4175 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4176 return getRHS()->getEndLoc();
4177 }
4178
4179 static bool classof(const Stmt *T) {
4180 return T->getStmtClass() == ConditionalOperatorClass;
4181 }
4182
4183 // Iterators
4184 child_range children() {
4185 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4186 }
4187 const_child_range children() const {
4188 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4189 }
4190};
4191
4192/// BinaryConditionalOperator - The GNU extension to the conditional
4193/// operator which allows the middle operand to be omitted.
4194///
4195/// This is a different expression kind on the assumption that almost
4196/// every client ends up needing to know that these are different.
4197class BinaryConditionalOperator : public AbstractConditionalOperator {
4198 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
4199
4200 /// - the common condition/left-hand-side expression, which will be
4201 /// evaluated as the opaque value
4202 /// - the condition, expressed in terms of the opaque value
4203 /// - the left-hand-side, expressed in terms of the opaque value
4204 /// - the right-hand-side
4205 Stmt *SubExprs[NUM_SUBEXPRS];
4206 OpaqueValueExpr *OpaqueValue;
4207
4208 friend class ASTStmtReader;
4209public:
4210 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
4211 Expr *cond, Expr *lhs, Expr *rhs,
4212 SourceLocation qloc, SourceLocation cloc,
4213 QualType t, ExprValueKind VK, ExprObjectKind OK)
4214 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
4215 qloc, cloc),
4216 OpaqueValue(opaqueValue) {
4217 SubExprs[COMMON] = common;
4218 SubExprs[COND] = cond;
4219 SubExprs[LHS] = lhs;
4220 SubExprs[RHS] = rhs;
4221 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value")((void)0);
4222 setDependence(computeDependence(this));
4223 }
4224
4225 /// Build an empty conditional operator.
4226 explicit BinaryConditionalOperator(EmptyShell Empty)
4227 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
4228
4229 /// getCommon - Return the common expression, written to the
4230 /// left of the condition. The opaque value will be bound to the
4231 /// result of this expression.
4232 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
4233
4234 /// getOpaqueValue - Return the opaque value placeholder.
4235 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
4236
4237 /// getCond - Return the condition expression; this is defined
4238 /// in terms of the opaque value.
4239 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4240
4241 /// getTrueExpr - Return the subexpression which will be
4242 /// evaluated if the condition evaluates to true; this is defined
4243 /// in terms of the opaque value.
4244 Expr *getTrueExpr() const {
4245 return cast<Expr>(SubExprs[LHS]);
4246 }
4247
4248 /// getFalseExpr - Return the subexpression which will be
4249 /// evaluated if the condnition evaluates to false; this is
4250 /// defined in terms of the opaque value.
4251 Expr *getFalseExpr() const {
4252 return cast<Expr>(SubExprs[RHS]);
4253 }
4254
4255 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
4256 return getCommon()->getBeginLoc();
4257 }
4258 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4259 return getFalseExpr()->getEndLoc();
4260 }
4261
4262 static bool classof(const Stmt *T) {
4263 return T->getStmtClass() == BinaryConditionalOperatorClass;
4264 }
4265
4266 // Iterators
4267 child_range children() {
4268 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4269 }
4270 const_child_range children() const {
4271 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4272 }
4273};
4274
4275inline Expr *AbstractConditionalOperator::getCond() const {
4276 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4277 return co->getCond();
4278 return cast<BinaryConditionalOperator>(this)->getCond();
4279}
4280
4281inline Expr *AbstractConditionalOperator::getTrueExpr() const {
4282 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4283 return co->getTrueExpr();
4284 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
4285}
4286
4287inline Expr *AbstractConditionalOperator::getFalseExpr() const {
4288 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4289 return co->getFalseExpr();
4290 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
4291}
4292
4293/// AddrLabelExpr - The GNU address of label extension, representing &&label.
4294class AddrLabelExpr : public Expr {
4295 SourceLocation AmpAmpLoc, LabelLoc;
4296 LabelDecl *Label;
4297public:
4298 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
4299 QualType t)
4300 : Expr(AddrLabelExprClass, t, VK_PRValue, OK_Ordinary), AmpAmpLoc(AALoc),
4301 LabelLoc(LLoc), Label(L) {
4302 setDependence(ExprDependence::None);
4303 }
4304
4305 /// Build an empty address of a label expression.
4306 explicit AddrLabelExpr(EmptyShell Empty)
4307 : Expr(AddrLabelExprClass, Empty) { }
4308
4309 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
4310 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
4311 SourceLocation getLabelLoc() const { return LabelLoc; }
4312 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
4313
4314 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return AmpAmpLoc; }
4315 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return LabelLoc; }
4316
4317 LabelDecl *getLabel() const { return Label; }
4318 void setLabel(LabelDecl *L) { Label = L; }
4319
4320 static bool classof(const Stmt *T) {
4321 return T->getStmtClass() == AddrLabelExprClass;
4322 }
4323
4324 // Iterators
4325 child_range children() {
4326 return child_range(child_iterator(), child_iterator());
4327 }
4328 const_child_range children() const {
4329 return const_child_range(const_child_iterator(), const_child_iterator());
4330 }
4331};
4332
4333/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
4334/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
4335/// takes the value of the last subexpression.
4336///
4337/// A StmtExpr is always an r-value; values "returned" out of a
4338/// StmtExpr will be copied.
4339class StmtExpr : public Expr {
4340 Stmt *SubStmt;
4341 SourceLocation LParenLoc, RParenLoc;
4342public:
4343 StmtExpr(CompoundStmt *SubStmt, QualType T, SourceLocation LParenLoc,
4344 SourceLocation RParenLoc, unsigned TemplateDepth)
4345 : Expr(StmtExprClass, T, VK_PRValue, OK_Ordinary), SubStmt(SubStmt),
4346 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4347 setDependence(computeDependence(this, TemplateDepth));
4348 // FIXME: A templated statement expression should have an associated
4349 // DeclContext so that nested declarations always have a dependent context.
4350 StmtExprBits.TemplateDepth = TemplateDepth;
4351 }
4352
4353 /// Build an empty statement expression.
4354 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
4355
4356 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
4357 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
4358 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
4359
4360 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LParenLoc; }
4361 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4362
4363 SourceLocation getLParenLoc() const { return LParenLoc; }
4364 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
4365 SourceLocation getRParenLoc() const { return RParenLoc; }
4366 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4367
4368 unsigned getTemplateDepth() const { return StmtExprBits.TemplateDepth; }
4369
4370 static bool classof(const Stmt *T) {
4371 return T->getStmtClass() == StmtExprClass;
4372 }
4373
4374 // Iterators
4375 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
4376 const_child_range children() const {
4377 return const_child_range(&SubStmt, &SubStmt + 1);
4378 }
4379};
4380
4381/// ShuffleVectorExpr - clang-specific builtin-in function
4382/// __builtin_shufflevector.
4383/// This AST node represents a operator that does a constant
4384/// shuffle, similar to LLVM's shufflevector instruction. It takes
4385/// two vectors and a variable number of constant indices,
4386/// and returns the appropriately shuffled vector.
4387class ShuffleVectorExpr : public Expr {
4388 SourceLocation BuiltinLoc, RParenLoc;
4389
4390 // SubExprs - the list of values passed to the __builtin_shufflevector
4391 // function. The first two are vectors, and the rest are constant
4392 // indices. The number of values in this list is always
4393 // 2+the number of indices in the vector type.
4394 Stmt **SubExprs;
4395 unsigned NumExprs;
4396
4397public:
4398 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
4399 SourceLocation BLoc, SourceLocation RP);
4400
4401 /// Build an empty vector-shuffle expression.
4402 explicit ShuffleVectorExpr(EmptyShell Empty)
4403 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
4404
4405 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4406 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4407
4408 SourceLocation getRParenLoc() const { return RParenLoc; }
4409 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4410
4411 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
4412 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4413
4414 static bool classof(const Stmt *T) {
4415 return T->getStmtClass() == ShuffleVectorExprClass;
4416 }
4417
4418 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
4419 /// constant expression, the actual arguments passed in, and the function
4420 /// pointers.
4421 unsigned getNumSubExprs() const { return NumExprs; }
4422
4423 /// Retrieve the array of expressions.
4424 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4425
4426 /// getExpr - Return the Expr at the specified index.
4427 Expr *getExpr(unsigned Index) {
4428 assert((Index < NumExprs) && "Arg access out of range!")((void)0);
4429 return cast<Expr>(SubExprs[Index]);
4430 }
4431 const Expr *getExpr(unsigned Index) const {
4432 assert((Index < NumExprs) && "Arg access out of range!")((void)0);
4433 return cast<Expr>(SubExprs[Index]);
4434 }
4435
4436 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
4437
4438 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
4439 assert((N < NumExprs - 2) && "Shuffle idx out of range!")((void)0);
4440 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
4441 }
4442
4443 // Iterators
4444 child_range children() {
4445 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
4446 }
4447 const_child_range children() const {
4448 return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
4449 }
4450};
4451
4452/// ConvertVectorExpr - Clang builtin function __builtin_convertvector
4453/// This AST node provides support for converting a vector type to another
4454/// vector type of the same arity.
4455class ConvertVectorExpr : public Expr {
4456private:
4457 Stmt *SrcExpr;
4458 TypeSourceInfo *TInfo;
4459 SourceLocation BuiltinLoc, RParenLoc;
4460
4461 friend class ASTReader;
4462 friend class ASTStmtReader;
4463 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
4464
4465public:
4466 ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
4467 ExprValueKind VK, ExprObjectKind OK,
4468 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4469 : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
4470 TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
4471 setDependence(computeDependence(this));
4472 }
4473
4474 /// getSrcExpr - Return the Expr to be converted.
4475 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4476
4477 /// getTypeSourceInfo - Return the destination type.
4478 TypeSourceInfo *getTypeSourceInfo() const {
4479 return TInfo;
4480 }
4481 void setTypeSourceInfo(TypeSourceInfo *ti) {
4482 TInfo = ti;
4483 }
4484
4485 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
4486 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4487
4488 /// getRParenLoc - Return the location of final right parenthesis.
4489 SourceLocation getRParenLoc() const { return RParenLoc; }
4490
4491 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
4492 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4493
4494 static bool classof(const Stmt *T) {
4495 return T->getStmtClass() == ConvertVectorExprClass;
4496 }
4497
4498 // Iterators
4499 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4500 const_child_range children() const {
4501 return const_child_range(&SrcExpr, &SrcExpr + 1);
4502 }
4503};
4504
4505/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
4506/// This AST node is similar to the conditional operator (?:) in C, with
4507/// the following exceptions:
4508/// - the test expression must be a integer constant expression.
4509/// - the expression returned acts like the chosen subexpression in every
4510/// visible way: the type is the same as that of the chosen subexpression,
4511/// and all predicates (whether it's an l-value, whether it's an integer
4512/// constant expression, etc.) return the same result as for the chosen
4513/// sub-expression.
4514class ChooseExpr : public Expr {
4515 enum { COND, LHS, RHS, END_EXPR };
4516 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4517 SourceLocation BuiltinLoc, RParenLoc;
4518 bool CondIsTrue;
4519public:
4520 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
4521 ExprValueKind VK, ExprObjectKind OK, SourceLocation RP,
4522 bool condIsTrue)
4523 : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP),
4524 CondIsTrue(condIsTrue) {
4525 SubExprs[COND] = cond;
4526 SubExprs[LHS] = lhs;
4527 SubExprs[RHS] = rhs;
4528
4529 setDependence(computeDependence(this));
4530 }
4531
4532 /// Build an empty __builtin_choose_expr.
4533 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
4534
4535 /// isConditionTrue - Return whether the condition is true (i.e. not
4536 /// equal to zero).
4537 bool isConditionTrue() const {
4538 assert(!isConditionDependent() &&((void)0)
4539 "Dependent condition isn't true or false")((void)0);
4540 return CondIsTrue;
4541 }
4542 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
4543
4544 bool isConditionDependent() const {
4545 return getCond()->isTypeDependent() || getCond()->isValueDependent();
4546 }
4547
4548 /// getChosenSubExpr - Return the subexpression chosen according to the
4549 /// condition.
4550 Expr *getChosenSubExpr() const {
4551 return isConditionTrue() ? getLHS() : getRHS();
4552 }
4553
4554 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4555 void setCond(Expr *E) { SubExprs[COND] = E; }
4556 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
4557 void setLHS(Expr *E) { SubExprs[LHS] = E; }
4558 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
4559 void setRHS(Expr *E) { SubExprs[RHS] = E; }
4560
4561 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4562 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4563
4564 SourceLocation getRParenLoc() const { return RParenLoc; }
4565 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4566
4567 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
4568 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4569
4570 static bool classof(const Stmt *T) {
4571 return T->getStmtClass() == ChooseExprClass;
4572 }
4573
4574 // Iterators
4575 child_range children() {
4576 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4577 }
4578 const_child_range children() const {
4579 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4580 }
4581};
4582
4583/// GNUNullExpr - Implements the GNU __null extension, which is a name
4584/// for a null pointer constant that has integral type (e.g., int or
4585/// long) and is the same size and alignment as a pointer. The __null
4586/// extension is typically only used by system headers, which define
4587/// NULL as __null in C++ rather than using 0 (which is an integer
4588/// that may not match the size of a pointer).
4589class GNUNullExpr : public Expr {
4590 /// TokenLoc - The location of the __null keyword.
4591 SourceLocation TokenLoc;
4592
4593public:
4594 GNUNullExpr(QualType Ty, SourceLocation Loc)
4595 : Expr(GNUNullExprClass, Ty, VK_PRValue, OK_Ordinary), TokenLoc(Loc) {
4596 setDependence(ExprDependence::None);
4597 }
4598
4599 /// Build an empty GNU __null expression.
4600 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
4601
4602 /// getTokenLocation - The location of the __null token.
4603 SourceLocation getTokenLocation() const { return TokenLoc; }
4604 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
4605
4606 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return TokenLoc; }
4607 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return TokenLoc; }
4608
4609 static bool classof(const Stmt *T) {
4610 return T->getStmtClass() == GNUNullExprClass;
4611 }
4612
4613 // Iterators
4614 child_range children() {
4615 return child_range(child_iterator(), child_iterator());
4616 }
4617 const_child_range children() const {
4618 return const_child_range(const_child_iterator(), const_child_iterator());
4619 }
4620};
4621
4622/// Represents a call to the builtin function \c __builtin_va_arg.
4623class VAArgExpr : public Expr {
4624 Stmt *Val;
4625 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
4626 SourceLocation BuiltinLoc, RParenLoc;
4627public:
4628 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
4629 SourceLocation RPLoc, QualType t, bool IsMS)
4630 : Expr(VAArgExprClass, t, VK_PRValue, OK_Ordinary), Val(e),
4631 TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {
4632 setDependence(computeDependence(this));
4633 }
4634
4635 /// Create an empty __builtin_va_arg expression.
4636 explicit VAArgExpr(EmptyShell Empty)
4637 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
4638
4639 const Expr *getSubExpr() const { return cast<Expr>(Val); }
4640 Expr *getSubExpr() { return cast<Expr>(Val); }
4641 void setSubExpr(Expr *E) { Val = E; }
4642
4643 /// Returns whether this is really a Win64 ABI va_arg expression.
4644 bool isMicrosoftABI() const { return TInfo.getInt(); }
4645 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
4646
4647 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
4648 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
4649
4650 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4651 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4652
4653 SourceLocation getRParenLoc() const { return RParenLoc; }
4654 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4655
4656 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
4657 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4658
4659 static bool classof(const Stmt *T) {
4660 return T->getStmtClass() == VAArgExprClass;
4661 }
4662
4663 // Iterators
4664 child_range children() { return child_range(&Val, &Val+1); }
4665 const_child_range children() const {
4666 return const_child_range(&Val, &Val + 1);
4667 }
4668};
4669
4670/// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(),
4671/// __builtin_FUNCTION(), or __builtin_FILE().
4672class SourceLocExpr final : public Expr {
4673 SourceLocation BuiltinLoc, RParenLoc;
4674 DeclContext *ParentContext;
4675
4676public:
4677 enum IdentKind { Function, File, Line, Column };
4678
4679 SourceLocExpr(const ASTContext &Ctx, IdentKind Type, SourceLocation BLoc,
4680 SourceLocation RParenLoc, DeclContext *Context);
4681
4682 /// Build an empty call expression.
4683 explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
4684
4685 /// Return the result of evaluating this SourceLocExpr in the specified
4686 /// (and possibly null) default argument or initialization context.
4687 APValue EvaluateInContext(const ASTContext &Ctx,
4688 const Expr *DefaultExpr) const;
4689
4690 /// Return a string representing the name of the specific builtin function.
4691 StringRef getBuiltinStr() const;
4692
4693 IdentKind getIdentKind() const {
4694 return static_cast<IdentKind>(SourceLocExprBits.Kind);
4695 }
4696
4697 bool isStringType() const {
4698 switch (getIdentKind()) {
4699 case File:
4700 case Function:
4701 return true;
4702 case Line:
4703 case Column:
4704 return false;
4705 }
4706 llvm_unreachable("unknown source location expression kind")__builtin_unreachable();
4707 }
4708 bool isIntType() const LLVM_READONLY__attribute__((__pure__)) { return !isStringType(); }
4709
4710 /// If the SourceLocExpr has been resolved return the subexpression
4711 /// representing the resolved value. Otherwise return null.
4712 const DeclContext *getParentContext() const { return ParentContext; }
4713 DeclContext *getParentContext() { return ParentContext; }
4714
4715 SourceLocation getLocation() const { return BuiltinLoc; }
4716 SourceLocation getBeginLoc() const { return BuiltinLoc; }
4717 SourceLocation getEndLoc() const { return RParenLoc; }
4718
4719 child_range children() {
4720 return child_range(child_iterator(), child_iterator());
4721 }
4722
4723 const_child_range children() const {
4724 return const_child_range(child_iterator(), child_iterator());
4725 }
4726
4727 static bool classof(const Stmt *T) {
4728 return T->getStmtClass() == SourceLocExprClass;
4729 }
4730
4731private:
4732 friend class ASTStmtReader;
4733};
4734
4735/// Describes an C or C++ initializer list.
4736///
4737/// InitListExpr describes an initializer list, which can be used to
4738/// initialize objects of different types, including
4739/// struct/class/union types, arrays, and vectors. For example:
4740///
4741/// @code
4742/// struct foo x = { 1, { 2, 3 } };
4743/// @endcode
4744///
4745/// Prior to semantic analysis, an initializer list will represent the
4746/// initializer list as written by the user, but will have the
4747/// placeholder type "void". This initializer list is called the
4748/// syntactic form of the initializer, and may contain C99 designated
4749/// initializers (represented as DesignatedInitExprs), initializations
4750/// of subobject members without explicit braces, and so on. Clients
4751/// interested in the original syntax of the initializer list should
4752/// use the syntactic form of the initializer list.
4753///
4754/// After semantic analysis, the initializer list will represent the
4755/// semantic form of the initializer, where the initializations of all
4756/// subobjects are made explicit with nested InitListExpr nodes and
4757/// C99 designators have been eliminated by placing the designated
4758/// initializations into the subobject they initialize. Additionally,
4759/// any "holes" in the initialization, where no initializer has been
4760/// specified for a particular subobject, will be replaced with
4761/// implicitly-generated ImplicitValueInitExpr expressions that
4762/// value-initialize the subobjects. Note, however, that the
4763/// initializer lists may still have fewer initializers than there are
4764/// elements to initialize within the object.
4765///
4766/// After semantic analysis has completed, given an initializer list,
4767/// method isSemanticForm() returns true if and only if this is the
4768/// semantic form of the initializer list (note: the same AST node
4769/// may at the same time be the syntactic form).
4770/// Given the semantic form of the initializer list, one can retrieve
4771/// the syntactic form of that initializer list (when different)
4772/// using method getSyntacticForm(); the method returns null if applied
4773/// to a initializer list which is already in syntactic form.
4774/// Similarly, given the syntactic form (i.e., an initializer list such
4775/// that isSemanticForm() returns false), one can retrieve the semantic
4776/// form using method getSemanticForm().
4777/// Since many initializer lists have the same syntactic and semantic forms,
4778/// getSyntacticForm() may return NULL, indicating that the current
4779/// semantic initializer list also serves as its syntactic form.
4780class InitListExpr : public Expr {
4781 // FIXME: Eliminate this vector in favor of ASTContext allocation
4782 typedef ASTVector<Stmt *> InitExprsTy;
4783 InitExprsTy InitExprs;
4784 SourceLocation LBraceLoc, RBraceLoc;
4785
4786 /// The alternative form of the initializer list (if it exists).
4787 /// The int part of the pair stores whether this initializer list is
4788 /// in semantic form. If not null, the pointer points to:
4789 /// - the syntactic form, if this is in semantic form;
4790 /// - the semantic form, if this is in syntactic form.
4791 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
4792
4793 /// Either:
4794 /// If this initializer list initializes an array with more elements than
4795 /// there are initializers in the list, specifies an expression to be used
4796 /// for value initialization of the rest of the elements.
4797 /// Or
4798 /// If this initializer list initializes a union, specifies which
4799 /// field within the union will be initialized.
4800 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
4801
4802public:
4803 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
4804 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
4805
4806 /// Build an empty initializer list.
4807 explicit InitListExpr(EmptyShell Empty)
4808 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
4809
4810 unsigned getNumInits() const { return InitExprs.size(); }
4811
4812 /// Retrieve the set of initializers.
4813 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
4814
4815 /// Retrieve the set of initializers.
4816 Expr * const *getInits() const {
4817 return reinterpret_cast<Expr * const *>(InitExprs.data());
4818 }
4819
4820 ArrayRef<Expr *> inits() {
4821 return llvm::makeArrayRef(getInits(), getNumInits());
4822 }
4823
4824 ArrayRef<Expr *> inits() const {
4825 return llvm::makeArrayRef(getInits(), getNumInits());
4826 }
4827
4828 const Expr *getInit(unsigned Init) const {
4829 assert(Init < getNumInits() && "Initializer access out of range!")((void)0);
4830 return cast_or_null<Expr>(InitExprs[Init]);
4831 }
4832
4833 Expr *getInit(unsigned Init) {
4834 assert(Init < getNumInits() && "Initializer access out of range!")((void)0);
4835 return cast_or_null<Expr>(InitExprs[Init]);
4836 }
4837
4838 void setInit(unsigned Init, Expr *expr) {
4839 assert(Init < getNumInits() && "Initializer access out of range!")((void)0);
4840 InitExprs[Init] = expr;
4841
4842 if (expr)
4843 setDependence(getDependence() | expr->getDependence());
4844 }
4845
4846 /// Mark the semantic form of the InitListExpr as error when the semantic
4847 /// analysis fails.
4848 void markError() {
4849 assert(isSemanticForm())((void)0);
4850 setDependence(getDependence() | ExprDependence::ErrorDependent);
4851 }
4852
4853 /// Reserve space for some number of initializers.
4854 void reserveInits(const ASTContext &C, unsigned NumInits);
4855
4856 /// Specify the number of initializers
4857 ///
4858 /// If there are more than @p NumInits initializers, the remaining
4859 /// initializers will be destroyed. If there are fewer than @p
4860 /// NumInits initializers, NULL expressions will be added for the
4861 /// unknown initializers.
4862 void resizeInits(const ASTContext &Context, unsigned NumInits);
4863
4864 /// Updates the initializer at index @p Init with the new
4865 /// expression @p expr, and returns the old expression at that
4866 /// location.
4867 ///
4868 /// When @p Init is out of range for this initializer list, the
4869 /// initializer list will be extended with NULL expressions to
4870 /// accommodate the new entry.
4871 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
4872
4873 /// If this initializer list initializes an array with more elements
4874 /// than there are initializers in the list, specifies an expression to be
4875 /// used for value initialization of the rest of the elements.
4876 Expr *getArrayFiller() {
4877 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
4878 }
4879 const Expr *getArrayFiller() const {
4880 return const_cast<InitListExpr *>(this)->getArrayFiller();
4881 }
4882 void setArrayFiller(Expr *filler);
4883
4884 /// Return true if this is an array initializer and its array "filler"
4885 /// has been set.
4886 bool hasArrayFiller() const { return getArrayFiller(); }
4887
4888 /// If this initializes a union, specifies which field in the
4889 /// union to initialize.
4890 ///
4891 /// Typically, this field is the first named field within the
4892 /// union. However, a designated initializer can specify the
4893 /// initialization of a different field within the union.
4894 FieldDecl *getInitializedFieldInUnion() {
4895 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
4896 }
4897 const FieldDecl *getInitializedFieldInUnion() const {
4898 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
4899 }
4900 void setInitializedFieldInUnion(FieldDecl *FD) {
4901 assert((FD == nullptr((void)0)
4902 || getInitializedFieldInUnion() == nullptr((void)0)
4903 || getInitializedFieldInUnion() == FD)((void)0)
4904 && "Only one field of a union may be initialized at a time!")((void)0);
4905 ArrayFillerOrUnionFieldInit = FD;
4906 }
4907
4908 // Explicit InitListExpr's originate from source code (and have valid source
4909 // locations). Implicit InitListExpr's are created by the semantic analyzer.
4910 // FIXME: This is wrong; InitListExprs created by semantic analysis have
4911 // valid source locations too!
4912 bool isExplicit() const {
4913 return LBraceLoc.isValid() && RBraceLoc.isValid();
4914 }
4915
4916 // Is this an initializer for an array of characters, initialized by a string
4917 // literal or an @encode?
4918 bool isStringLiteralInit() const;
4919
4920 /// Is this a transparent initializer list (that is, an InitListExpr that is
4921 /// purely syntactic, and whose semantics are that of the sole contained
4922 /// initializer)?
4923 bool isTransparent() const;
4924
4925 /// Is this the zero initializer {0} in a language which considers it
4926 /// idiomatic?
4927 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
4928
4929 SourceLocation getLBraceLoc() const { return LBraceLoc; }
4930 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
4931 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4932 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
4933
4934 bool isSemanticForm() const { return AltForm.getInt(); }
4935 InitListExpr *getSemanticForm() const {
4936 return isSemanticForm() ? nullptr : AltForm.getPointer();
4937 }
4938 bool isSyntacticForm() const {
4939 return !AltForm.getInt() || !AltForm.getPointer();
4940 }
4941 InitListExpr *getSyntacticForm() const {
4942 return isSemanticForm() ? AltForm.getPointer() : nullptr;
4943 }
4944
4945 void setSyntacticForm(InitListExpr *Init) {
4946 AltForm.setPointer(Init);
4947 AltForm.setInt(true);
4948 Init->AltForm.setPointer(this);
4949 Init->AltForm.setInt(false);
4950 }
4951
4952 bool hadArrayRangeDesignator() const {
4953 return InitListExprBits.HadArrayRangeDesignator != 0;
4954 }
4955 void sawArrayRangeDesignator(bool ARD = true) {
4956 InitListExprBits.HadArrayRangeDesignator = ARD;
4957 }
4958
4959 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
4960 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
4961
4962 static bool classof(const Stmt *T) {
4963 return T->getStmtClass() == InitListExprClass;
4964 }
4965
4966 // Iterators
4967 child_range children() {
4968 const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
4969 return child_range(cast_away_const(CCR.begin()),
4970 cast_away_const(CCR.end()));
4971 }
4972
4973 const_child_range children() const {
4974 // FIXME: This does not include the array filler expression.
4975 if (InitExprs.empty())
4976 return const_child_range(const_child_iterator(), const_child_iterator());
4977 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
4978 }
4979
4980 typedef InitExprsTy::iterator iterator;
4981 typedef InitExprsTy::const_iterator const_iterator;
4982 typedef InitExprsTy::reverse_iterator reverse_iterator;
4983 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
4984
4985 iterator begin() { return InitExprs.begin(); }
4986 const_iterator begin() const { return InitExprs.begin(); }
4987 iterator end() { return InitExprs.end(); }
4988 const_iterator end() const { return InitExprs.end(); }
4989 reverse_iterator rbegin() { return InitExprs.rbegin(); }
4990 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
4991 reverse_iterator rend() { return InitExprs.rend(); }
4992 const_reverse_iterator rend() const { return InitExprs.rend(); }
4993
4994 friend class ASTStmtReader;
4995 friend class ASTStmtWriter;
4996};
4997
4998/// Represents a C99 designated initializer expression.
4999///
5000/// A designated initializer expression (C99 6.7.8) contains one or
5001/// more designators (which can be field designators, array
5002/// designators, or GNU array-range designators) followed by an
5003/// expression that initializes the field or element(s) that the
5004/// designators refer to. For example, given:
5005///
5006/// @code
5007/// struct point {
5008/// double x;
5009/// double y;
5010/// };
5011/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
5012/// @endcode
5013///
5014/// The InitListExpr contains three DesignatedInitExprs, the first of
5015/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
5016/// designators, one array designator for @c [2] followed by one field
5017/// designator for @c .y. The initialization expression will be 1.0.
5018class DesignatedInitExpr final
5019 : public Expr,
5020 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
5021public:
5022 /// Forward declaration of the Designator class.
5023 class Designator;
5024
5025private:
5026 /// The location of the '=' or ':' prior to the actual initializer
5027 /// expression.
5028 SourceLocation EqualOrColonLoc;
5029
5030 /// Whether this designated initializer used the GNU deprecated
5031 /// syntax rather than the C99 '=' syntax.
5032 unsigned GNUSyntax : 1;
5033
5034 /// The number of designators in this initializer expression.
5035 unsigned NumDesignators : 15;
5036
5037 /// The number of subexpressions of this initializer expression,
5038 /// which contains both the initializer and any additional
5039 /// expressions used by array and array-range designators.
5040 unsigned NumSubExprs : 16;
5041
5042 /// The designators in this designated initialization
5043 /// expression.
5044 Designator *Designators;
5045
5046 DesignatedInitExpr(const ASTContext &C, QualType Ty,
5047 llvm::ArrayRef<Designator> Designators,
5048 SourceLocation EqualOrColonLoc, bool GNUSyntax,
5049 ArrayRef<Expr *> IndexExprs, Expr *Init);
5050
5051 explicit DesignatedInitExpr(unsigned NumSubExprs)
5052 : Expr(DesignatedInitExprClass, EmptyShell()),
5053 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
5054
5055public:
5056 /// A field designator, e.g., ".x".
5057 struct FieldDesignator {
5058 /// Refers to the field that is being initialized. The low bit
5059 /// of this field determines whether this is actually a pointer
5060 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
5061 /// initially constructed, a field designator will store an
5062 /// IdentifierInfo*. After semantic analysis has resolved that
5063 /// name, the field designator will instead store a FieldDecl*.
5064 uintptr_t NameOrField;
5065
5066 /// The location of the '.' in the designated initializer.
5067 SourceLocation DotLoc;
5068
5069 /// The location of the field name in the designated initializer.
5070 SourceLocation FieldLoc;
5071 };
5072
5073 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
5074 struct ArrayOrRangeDesignator {
5075 /// Location of the first index expression within the designated
5076 /// initializer expression's list of subexpressions.
5077 unsigned Index;
5078 /// The location of the '[' starting the array range designator.
5079 SourceLocation LBracketLoc;
5080 /// The location of the ellipsis separating the start and end
5081 /// indices. Only valid for GNU array-range designators.
5082 SourceLocation EllipsisLoc;
5083 /// The location of the ']' terminating the array range designator.
5084 SourceLocation RBracketLoc;
5085 };
5086
5087 /// Represents a single C99 designator.
5088 ///
5089 /// @todo This class is infuriatingly similar to clang::Designator,
5090 /// but minor differences (storing indices vs. storing pointers)
5091 /// keep us from reusing it. Try harder, later, to rectify these
5092 /// differences.
5093 class Designator {
5094 /// The kind of designator this describes.
5095 enum {
5096 FieldDesignator,
5097 ArrayDesignator,
5098 ArrayRangeDesignator
5099 } Kind;
5100
5101 union {
5102 /// A field designator, e.g., ".x".
5103 struct FieldDesignator Field;
5104 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
5105 struct ArrayOrRangeDesignator ArrayOrRange;
5106 };
5107 friend class DesignatedInitExpr;
5108
5109 public:
5110 Designator() {}
5111
5112 /// Initializes a field designator.
5113 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
5114 SourceLocation FieldLoc)
5115 : Kind(FieldDesignator) {
5116 new (&Field) DesignatedInitExpr::FieldDesignator;
5117 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
5118 Field.DotLoc = DotLoc;
5119 Field.FieldLoc = FieldLoc;
5120 }
5121
5122 /// Initializes an array designator.
5123 Designator(unsigned Index, SourceLocation LBracketLoc,
5124 SourceLocation RBracketLoc)
5125 : Kind(ArrayDesignator) {
5126 new (&ArrayOrRange) DesignatedInitExpr::ArrayOrRangeDesignator;
5127 ArrayOrRange.Index = Index;
5128 ArrayOrRange.LBracketLoc = LBracketLoc;
5129 ArrayOrRange.EllipsisLoc = SourceLocation();
5130 ArrayOrRange.RBracketLoc = RBracketLoc;
5131 }
5132
5133 /// Initializes a GNU array-range designator.
5134 Designator(unsigned Index, SourceLocation LBracketLoc,
5135 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
5136 : Kind(ArrayRangeDesignator) {
5137 new (&ArrayOrRange) DesignatedInitExpr::ArrayOrRangeDesignator;
5138 ArrayOrRange.Index = Index;
5139 ArrayOrRange.LBracketLoc = LBracketLoc;
5140 ArrayOrRange.EllipsisLoc = EllipsisLoc;
5141 ArrayOrRange.RBracketLoc = RBracketLoc;
5142 }
5143
5144 bool isFieldDesignator() const { return Kind == FieldDesignator; }
5145 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
5146 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
5147
5148 IdentifierInfo *getFieldName() const;
5149
5150 FieldDecl *getField() const {
5151 assert(Kind == FieldDesignator && "Only valid on a field designator")((void)0);
5152 if (Field.NameOrField & 0x01)
5153 return nullptr;
5154 else
5155 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
5156 }
5157
5158 void setField(FieldDecl *FD) {
5159 assert(Kind == FieldDesignator && "Only valid on a field designator")((void)0);
5160 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
5161 }
5162
5163 SourceLocation getDotLoc() const {
5164 assert(Kind == FieldDesignator && "Only valid on a field designator")((void)0);
5165 return Field.DotLoc;
5166 }
5167
5168 SourceLocation getFieldLoc() const {
5169 assert(Kind == FieldDesignator && "Only valid on a field designator")((void)0);
5170 return Field.FieldLoc;
5171 }
5172
5173 SourceLocation getLBracketLoc() const {
5174 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&((void)0)
5175 "Only valid on an array or array-range designator")((void)0);
5176 return ArrayOrRange.LBracketLoc;
5177 }
5178
5179 SourceLocation getRBracketLoc() const {
5180 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&((void)0)
5181 "Only valid on an array or array-range designator")((void)0);
5182 return ArrayOrRange.RBracketLoc;
5183 }
5184
5185 SourceLocation getEllipsisLoc() const {
5186 assert(Kind == ArrayRangeDesignator &&((void)0)
5187 "Only valid on an array-range designator")((void)0);
5188 return ArrayOrRange.EllipsisLoc;
5189 }
5190
5191 unsigned getFirstExprIndex() const {
5192 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&((void)0)
5193 "Only valid on an array or array-range designator")((void)0);
5194 return ArrayOrRange.Index;
5195 }
5196
5197 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
5198 if (Kind == FieldDesignator)
5199 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
5200 else
5201 return getLBracketLoc();
5202 }
5203 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
5204 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
5205 }
5206 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
5207 return SourceRange(getBeginLoc(), getEndLoc());
5208 }
5209 };
5210
5211 static DesignatedInitExpr *Create(const ASTContext &C,
5212 llvm::ArrayRef<Designator> Designators,
5213 ArrayRef<Expr*> IndexExprs,
5214 SourceLocation EqualOrColonLoc,
5215 bool GNUSyntax, Expr *Init);
5216
5217 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
5218 unsigned NumIndexExprs);
5219
5220 /// Returns the number of designators in this initializer.
5221 unsigned size() const { return NumDesignators; }
5222
5223 // Iterator access to the designators.
5224 llvm::MutableArrayRef<Designator> designators() {
5225 return {Designators, NumDesignators};
5226 }
5227
5228 llvm::ArrayRef<Designator> designators() const {
5229 return {Designators, NumDesignators};
5230 }
5231
5232 Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
5233 const Designator *getDesignator(unsigned Idx) const {
5234 return &designators()[Idx];
5235 }
5236
5237 void setDesignators(const ASTContext &C, const Designator *Desigs,
5238 unsigned NumDesigs);
5239
5240 Expr *getArrayIndex(const Designator &D) const;
5241 Expr *getArrayRangeStart(const Designator &D) const;
5242 Expr *getArrayRangeEnd(const Designator &D) const;
5243
5244 /// Retrieve the location of the '=' that precedes the
5245 /// initializer value itself, if present.
5246 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
5247 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
5248
5249 /// Whether this designated initializer should result in direct-initialization
5250 /// of the designated subobject (eg, '{.foo{1, 2, 3}}').
5251 bool isDirectInit() const { return EqualOrColonLoc.isInvalid(); }
5252
5253 /// Determines whether this designated initializer used the
5254 /// deprecated GNU syntax for designated initializers.
5255 bool usesGNUSyntax() const { return GNUSyntax; }
5256 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
5257
5258 /// Retrieve the initializer value.
5259 Expr *getInit() const {
5260 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
5261 }
5262
5263 void setInit(Expr *init) {
5264 *child_begin() = init;
5265 }
5266
5267 /// Retrieve the total number of subexpressions in this
5268 /// designated initializer expression, including the actual
5269 /// initialized value and any expressions that occur within array
5270 /// and array-range designators.
5271 unsigned getNumSubExprs() const { return NumSubExprs; }
5272
5273 Expr *getSubExpr(unsigned Idx) const {
5274 assert(Idx < NumSubExprs && "Subscript out of range")((void)0);
5275 return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
5276 }
5277
5278 void setSubExpr(unsigned Idx, Expr *E) {
5279 assert(Idx < NumSubExprs && "Subscript out of range")((void)0);
5280 getTrailingObjects<Stmt *>()[Idx] = E;
5281 }
5282
5283 /// Replaces the designator at index @p Idx with the series
5284 /// of designators in [First, Last).
5285 void ExpandDesignator(const ASTContext &C, unsigned Idx,
5286 const Designator *First, const Designator *Last);
5287
5288 SourceRange getDesignatorsSourceRange() const;
5289
5290 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
5291 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
5292
5293 static bool classof(const Stmt *T) {
5294 return T->getStmtClass() == DesignatedInitExprClass;
5295 }
5296
5297 // Iterators
5298 child_range children() {
5299 Stmt **begin = getTrailingObjects<Stmt *>();
5300 return child_range(begin, begin + NumSubExprs);
5301 }
5302 const_child_range children() const {
5303 Stmt * const *begin = getTrailingObjects<Stmt *>();
5304 return const_child_range(begin, begin + NumSubExprs);
5305 }
5306
5307 friend TrailingObjects;
5308};
5309
5310/// Represents a place-holder for an object not to be initialized by
5311/// anything.
5312///
5313/// This only makes sense when it appears as part of an updater of a
5314/// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
5315/// initializes a big object, and the NoInitExpr's mark the spots within the
5316/// big object not to be overwritten by the updater.
5317///
5318/// \see DesignatedInitUpdateExpr
5319class NoInitExpr : public Expr {
5320public:
5321 explicit NoInitExpr(QualType ty)
5322 : Expr(NoInitExprClass, ty, VK_PRValue, OK_Ordinary) {
5323 setDependence(computeDependence(this));
5324 }
5325
5326 explicit NoInitExpr(EmptyShell Empty)
5327 : Expr(NoInitExprClass, Empty) { }
5328
5329 static bool classof(const Stmt *T) {
5330 return T->getStmtClass() == NoInitExprClass;
5331 }
5332
5333 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5334 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5335
5336 // Iterators
5337 child_range children() {
5338 return child_range(child_iterator(), child_iterator());
5339 }
5340 const_child_range children() const {
5341 return const_child_range(const_child_iterator(), const_child_iterator());
5342 }
5343};
5344
5345// In cases like:
5346// struct Q { int a, b, c; };
5347// Q *getQ();
5348// void foo() {
5349// struct A { Q q; } a = { *getQ(), .q.b = 3 };
5350// }
5351//
5352// We will have an InitListExpr for a, with type A, and then a
5353// DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
5354// is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
5355//
5356class DesignatedInitUpdateExpr : public Expr {
5357 // BaseAndUpdaterExprs[0] is the base expression;
5358 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
5359 Stmt *BaseAndUpdaterExprs[2];
5360
5361public:
5362 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
5363 Expr *baseExprs, SourceLocation rBraceLoc);
5364
5365 explicit DesignatedInitUpdateExpr(EmptyShell Empty)
5366 : Expr(DesignatedInitUpdateExprClass, Empty) { }
5367
5368 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
5369 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
5370
5371 static bool classof(const Stmt *T) {
5372 return T->getStmtClass() == DesignatedInitUpdateExprClass;
5373 }
5374
5375 Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
5376 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
5377
5378 InitListExpr *getUpdater() const {
5379 return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
5380 }
5381 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
5382
5383 // Iterators
5384 // children = the base and the updater
5385 child_range children() {
5386 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
5387 }
5388 const_child_range children() const {
5389 return const_child_range(&BaseAndUpdaterExprs[0],
5390 &BaseAndUpdaterExprs[0] + 2);
5391 }
5392};
5393
5394/// Represents a loop initializing the elements of an array.
5395///
5396/// The need to initialize the elements of an array occurs in a number of
5397/// contexts:
5398///
5399/// * in the implicit copy/move constructor for a class with an array member
5400/// * when a lambda-expression captures an array by value
5401/// * when a decomposition declaration decomposes an array
5402///
5403/// There are two subexpressions: a common expression (the source array)
5404/// that is evaluated once up-front, and a per-element initializer that
5405/// runs once for each array element.
5406///
5407/// Within the per-element initializer, the common expression may be referenced
5408/// via an OpaqueValueExpr, and the current index may be obtained via an
5409/// ArrayInitIndexExpr.
5410class ArrayInitLoopExpr : public Expr {
5411 Stmt *SubExprs[2];
5412
5413 explicit ArrayInitLoopExpr(EmptyShell Empty)
5414 : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
5415
5416public:
5417 explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
5418 : Expr(ArrayInitLoopExprClass, T, VK_PRValue, OK_Ordinary),
5419 SubExprs{CommonInit, ElementInit} {
5420 setDependence(computeDependence(this));
5421 }
5422
5423 /// Get the common subexpression shared by all initializations (the source
5424 /// array).
5425 OpaqueValueExpr *getCommonExpr() const {
5426 return cast<OpaqueValueExpr>(SubExprs[0]);
5427 }
5428
5429 /// Get the initializer to use for each array element.
5430 Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); }
5431
5432 llvm::APInt getArraySize() const {
5433 return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
5434 ->getSize();
5435 }
5436
5437 static bool classof(const Stmt *S) {
5438 return S->getStmtClass() == ArrayInitLoopExprClass;
5439 }
5440
5441 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
5442 return getCommonExpr()->getBeginLoc();
5443 }
5444 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
5445 return getCommonExpr()->getEndLoc();
5446 }
5447
5448 child_range children() {
5449 return child_range(SubExprs, SubExprs + 2);
5450 }
5451 const_child_range children() const {
5452 return const_child_range(SubExprs, SubExprs + 2);
5453 }
5454
5455 friend class ASTReader;
5456 friend class ASTStmtReader;
5457 friend class ASTStmtWriter;
5458};
5459
5460/// Represents the index of the current element of an array being
5461/// initialized by an ArrayInitLoopExpr. This can only appear within the
5462/// subexpression of an ArrayInitLoopExpr.
5463class ArrayInitIndexExpr : public Expr {
5464 explicit ArrayInitIndexExpr(EmptyShell Empty)
5465 : Expr(ArrayInitIndexExprClass, Empty) {}
5466
5467public:
5468 explicit ArrayInitIndexExpr(QualType T)
5469 : Expr(ArrayInitIndexExprClass, T, VK_PRValue, OK_Ordinary) {
5470 setDependence(ExprDependence::None);
5471 }
5472
5473 static bool classof(const Stmt *S) {
5474 return S->getStmtClass() == ArrayInitIndexExprClass;
5475 }
5476
5477 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5478 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5479
5480 child_range children() {
5481 return child_range(child_iterator(), child_iterator());
5482 }
5483 const_child_range children() const {
5484 return const_child_range(const_child_iterator(), const_child_iterator());
5485 }
5486
5487 friend class ASTReader;
5488 friend class ASTStmtReader;
5489};
5490
5491/// Represents an implicitly-generated value initialization of
5492/// an object of a given type.
5493///
5494/// Implicit value initializations occur within semantic initializer
5495/// list expressions (InitListExpr) as placeholders for subobject
5496/// initializations not explicitly specified by the user.
5497///
5498/// \see InitListExpr
5499class ImplicitValueInitExpr : public Expr {
5500public:
5501 explicit ImplicitValueInitExpr(QualType ty)
5502 : Expr(ImplicitValueInitExprClass, ty, VK_PRValue, OK_Ordinary) {
5503 setDependence(computeDependence(this));
5504 }
5505
5506 /// Construct an empty implicit value initialization.
5507 explicit ImplicitValueInitExpr(EmptyShell Empty)
5508 : Expr(ImplicitValueInitExprClass, Empty) { }
5509
5510 static bool classof(const Stmt *T) {
5511 return T->getStmtClass() == ImplicitValueInitExprClass;
5512 }
5513
5514 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5515 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5516
5517 // Iterators
5518 child_range children() {
5519 return child_range(child_iterator(), child_iterator());
5520 }
5521 const_child_range children() const {
5522 return const_child_range(const_child_iterator(), const_child_iterator());
5523 }
5524};
5525
5526class ParenListExpr final
5527 : public Expr,
5528 private llvm::TrailingObjects<ParenListExpr, Stmt *> {
5529 friend class ASTStmtReader;
5530 friend TrailingObjects;
5531
5532 /// The location of the left and right parentheses.
5533 SourceLocation LParenLoc, RParenLoc;
5534
5535 /// Build a paren list.
5536 ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
5537 SourceLocation RParenLoc);
5538
5539 /// Build an empty paren list.
5540 ParenListExpr(EmptyShell Empty, unsigned NumExprs);
5541
5542public:
5543 /// Create a paren list.
5544 static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc,
5545 ArrayRef<Expr *> Exprs,
5546 SourceLocation RParenLoc);
5547
5548 /// Create an empty paren list.
5549 static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs);
5550
5551 /// Return the number of expressions in this paren list.
5552 unsigned getNumExprs() const { return ParenListExprBits.NumExprs; }
5553
5554 Expr *getExpr(unsigned Init) {
5555 assert(Init < getNumExprs() && "Initializer access out of range!")((void)0);
5556 return getExprs()[Init];
5557 }
5558
5559 const Expr *getExpr(unsigned Init) const {
5560 return const_cast<ParenListExpr *>(this)->getExpr(Init);
5561 }
5562
5563 Expr **getExprs() {
5564 return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>());
5565 }
5566
5567 ArrayRef<Expr *> exprs() {
5568 return llvm::makeArrayRef(getExprs(), getNumExprs());
5569 }
5570
5571 SourceLocation getLParenLoc() const { return LParenLoc; }
5572 SourceLocation getRParenLoc() const { return RParenLoc; }
5573 SourceLocation getBeginLoc() const { return getLParenLoc(); }
5574 SourceLocation getEndLoc() const { return getRParenLoc(); }
5575
5576 static bool classof(const Stmt *T) {
5577 return T->getStmtClass() == ParenListExprClass;
5578 }
5579
5580 // Iterators
5581 child_range children() {
5582 return child_range(getTrailingObjects<Stmt *>(),
5583 getTrailingObjects<Stmt *>() + getNumExprs());
5584 }
5585 const_child_range children() const {
5586 return const_child_range(getTrailingObjects<Stmt *>(),
5587 getTrailingObjects<Stmt *>() + getNumExprs());
5588 }
5589};
5590
5591/// Represents a C11 generic selection.
5592///
5593/// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
5594/// expression, followed by one or more generic associations. Each generic
5595/// association specifies a type name and an expression, or "default" and an
5596/// expression (in which case it is known as a default generic association).
5597/// The type and value of the generic selection are identical to those of its
5598/// result expression, which is defined as the expression in the generic
5599/// association with a type name that is compatible with the type of the
5600/// controlling expression, or the expression in the default generic association
5601/// if no types are compatible. For example:
5602///
5603/// @code
5604/// _Generic(X, double: 1, float: 2, default: 3)
5605/// @endcode
5606///
5607/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
5608/// or 3 if "hello".
5609///
5610/// As an extension, generic selections are allowed in C++, where the following
5611/// additional semantics apply:
5612///
5613/// Any generic selection whose controlling expression is type-dependent or
5614/// which names a dependent type in its association list is result-dependent,
5615/// which means that the choice of result expression is dependent.
5616/// Result-dependent generic associations are both type- and value-dependent.
5617class GenericSelectionExpr final
5618 : public Expr,
5619 private llvm::TrailingObjects<GenericSelectionExpr, Stmt *,
5620 TypeSourceInfo *> {
5621 friend class ASTStmtReader;
5622 friend class ASTStmtWriter;
5623 friend TrailingObjects;
5624
5625 /// The number of association expressions and the index of the result
5626 /// expression in the case where the generic selection expression is not
5627 /// result-dependent. The result index is equal to ResultDependentIndex
5628 /// if and only if the generic selection expression is result-dependent.
5629 unsigned NumAssocs, ResultIndex;
5630 enum : unsigned {
5631 ResultDependentIndex = std::numeric_limits<unsigned>::max(),
5632 ControllingIndex = 0,
5633 AssocExprStartIndex = 1
5634 };
5635
5636 /// The location of the "default" and of the right parenthesis.
5637 SourceLocation DefaultLoc, RParenLoc;
5638
5639 // GenericSelectionExpr is followed by several trailing objects.
5640 // They are (in order):
5641 //
5642 // * A single Stmt * for the controlling expression.
5643 // * An array of getNumAssocs() Stmt * for the association expressions.
5644 // * An array of getNumAssocs() TypeSourceInfo *, one for each of the
5645 // association expressions.
5646 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
5647 // Add one to account for the controlling expression; the remainder
5648 // are the associated expressions.
5649 return 1 + getNumAssocs();
5650 }
5651
5652 unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
5653 return getNumAssocs();
5654 }
5655
5656 template <bool Const> class AssociationIteratorTy;
5657 /// Bundle together an association expression and its TypeSourceInfo.
5658 /// The Const template parameter is for the const and non-const versions
5659 /// of AssociationTy.
5660 template <bool Const> class AssociationTy {
5661 friend class GenericSelectionExpr;
5662 template <bool OtherConst> friend class AssociationIteratorTy;
5663 using ExprPtrTy = std::conditional_t<Const, const Expr *, Expr *>;
5664 using TSIPtrTy =
5665 std::conditional_t<Const, const TypeSourceInfo *, TypeSourceInfo *>;
5666 ExprPtrTy E;
5667 TSIPtrTy TSI;
5668 bool Selected;
5669 AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected)
5670 : E(E), TSI(TSI), Selected(Selected) {}
5671
5672 public:
5673 ExprPtrTy getAssociationExpr() const { return E; }
5674 TSIPtrTy getTypeSourceInfo() const { return TSI; }
5675 QualType getType() const { return TSI ? TSI->getType() : QualType(); }
5676 bool isSelected() const { return Selected; }
5677 AssociationTy *operator->() { return this; }
5678 const AssociationTy *operator->() const { return this; }
5679 }; // class AssociationTy
5680
5681 /// Iterator over const and non-const Association objects. The Association
5682 /// objects are created on the fly when the iterator is dereferenced.
5683 /// This abstract over how exactly the association expressions and the
5684 /// corresponding TypeSourceInfo * are stored.
5685 template <bool Const>
5686 class AssociationIteratorTy
5687 : public llvm::iterator_facade_base<
5688 AssociationIteratorTy<Const>, std::input_iterator_tag,
5689 AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>,
5690 AssociationTy<Const>> {
5691 friend class GenericSelectionExpr;
5692 // FIXME: This iterator could conceptually be a random access iterator, and
5693 // it would be nice if we could strengthen the iterator category someday.
5694 // However this iterator does not satisfy two requirements of forward
5695 // iterators:
5696 // a) reference = T& or reference = const T&
5697 // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only
5698 // if *It1 and *It2 are bound to the same objects.
5699 // An alternative design approach was discussed during review;
5700 // store an Association object inside the iterator, and return a reference
5701 // to it when dereferenced. This idea was discarded beacuse of nasty
5702 // lifetime issues:
5703 // AssociationIterator It = ...;
5704 // const Association &Assoc = *It++; // Oops, Assoc is dangling.
5705 using BaseTy = typename AssociationIteratorTy::iterator_facade_base;
5706 using StmtPtrPtrTy =
5707 std::conditional_t<Const, const Stmt *const *, Stmt **>;
5708 using TSIPtrPtrTy = std::conditional_t<Const, const TypeSourceInfo *const *,
5709 TypeSourceInfo **>;
5710 StmtPtrPtrTy E; // = nullptr; FIXME: Once support for gcc 4.8 is dropped.
5711 TSIPtrPtrTy TSI; // Kept in sync with E.
5712 unsigned Offset = 0, SelectedOffset = 0;
5713 AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset,
5714 unsigned SelectedOffset)
5715 : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {}
5716
5717 public:
5718 AssociationIteratorTy() : E(nullptr), TSI(nullptr) {}
5719 typename BaseTy::reference operator*() const {
5720 return AssociationTy<Const>(cast<Expr>(*E), *TSI,
5721 Offset == SelectedOffset);
5722 }
5723 typename BaseTy::pointer operator->() const { return **this; }
5724 using BaseTy::operator++;
5725 AssociationIteratorTy &operator++() {
5726 ++E;
5727 ++TSI;
5728 ++Offset;
5729 return *this;
5730 }
5731 bool operator==(AssociationIteratorTy Other) const { return E == Other.E; }
5732 }; // class AssociationIterator
5733
5734 /// Build a non-result-dependent generic selection expression.
5735 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
5736 Expr *ControllingExpr,
5737 ArrayRef<TypeSourceInfo *> AssocTypes,
5738 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5739 SourceLocation RParenLoc,
5740 bool ContainsUnexpandedParameterPack,
5741 unsigned ResultIndex);
5742
5743 /// Build a result-dependent generic selection expression.
5744 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
5745 Expr *ControllingExpr,
5746 ArrayRef<TypeSourceInfo *> AssocTypes,
5747 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5748 SourceLocation RParenLoc,
5749 bool ContainsUnexpandedParameterPack);
5750
5751 /// Build an empty generic selection expression for deserialization.
5752 explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs);
5753
5754public:
5755 /// Create a non-result-dependent generic selection expression.
5756 static GenericSelectionExpr *
5757 Create(const ASTContext &Context, SourceLocation GenericLoc,
5758 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
5759 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5760 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
5761 unsigned ResultIndex);
5762
5763 /// Create a result-dependent generic selection expression.
5764 static GenericSelectionExpr *
5765 Create(const ASTContext &Context, SourceLocation GenericLoc,
5766 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
5767 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5768 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack);
5769
5770 /// Create an empty generic selection expression for deserialization.
5771 static GenericSelectionExpr *CreateEmpty(const ASTContext &Context,
5772 unsigned NumAssocs);
5773
5774 using Association = AssociationTy<false>;
5775 using ConstAssociation = AssociationTy<true>;
5776 using AssociationIterator = AssociationIteratorTy<false>;
5777 using ConstAssociationIterator = AssociationIteratorTy<true>;
5778 using association_range = llvm::iterator_range<AssociationIterator>;
5779 using const_association_range =
5780 llvm::iterator_range<ConstAssociationIterator>;
5781
5782 /// The number of association expressions.
5783 unsigned getNumAssocs() const { return NumAssocs; }
5784
5785 /// The zero-based index of the result expression's generic association in
5786 /// the generic selection's association list. Defined only if the
5787 /// generic selection is not result-dependent.
5788 unsigned getResultIndex() const {
5789 assert(!isResultDependent() &&((void)0)
5790 "Generic selection is result-dependent but getResultIndex called!")((void)0);
5791 return ResultIndex;
5792 }
5793
5794 /// Whether this generic selection is result-dependent.
5795 bool isResultDependent() const { return ResultIndex == ResultDependentIndex; }
5796
5797 /// Return the controlling expression of this generic selection expression.
5798 Expr *getControllingExpr() {
5799 return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]);
5800 }
5801 const Expr *getControllingExpr() const {
5802 return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]);
5803 }
5804
5805 /// Return the result expression of this controlling expression. Defined if
5806 /// and only if the generic selection expression is not result-dependent.
5807 Expr *getResultExpr() {
5808 return cast<Expr>(
5809 getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]);
5810 }
5811 const Expr *getResultExpr() const {
5812 return cast<Expr>(
5813 getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]);
5814 }
5815
5816 ArrayRef<Expr *> getAssocExprs() const {
5817 return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() +
5818 AssocExprStartIndex),
5819 NumAssocs};
5820 }
5821 ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
5822 return {getTrailingObjects<TypeSourceInfo *>(), NumAssocs};
5823 }
5824
5825 /// Return the Ith association expression with its TypeSourceInfo,
5826 /// bundled together in GenericSelectionExpr::(Const)Association.
5827 Association getAssociation(unsigned I) {
5828 assert(I < getNumAssocs() &&((void)0)
5829 "Out-of-range index in GenericSelectionExpr::getAssociation!")((void)0);
5830 return Association(
5831 cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]),
5832 getTrailingObjects<TypeSourceInfo *>()[I],
5833 !isResultDependent() && (getResultIndex() == I));
5834 }
5835 ConstAssociation getAssociation(unsigned I) const {
5836 assert(I < getNumAssocs() &&((void)0)
5837 "Out-of-range index in GenericSelectionExpr::getAssociation!")((void)0);
5838 return ConstAssociation(
5839 cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]),
5840 getTrailingObjects<TypeSourceInfo *>()[I],
5841 !isResultDependent() && (getResultIndex() == I));
5842 }
5843
5844 association_range associations() {
5845 AssociationIterator Begin(getTrailingObjects<Stmt *>() +
5846 AssocExprStartIndex,
5847 getTrailingObjects<TypeSourceInfo *>(),
5848 /*Offset=*/0, ResultIndex);
5849 AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
5850 /*Offset=*/NumAssocs, ResultIndex);
5851 return llvm::make_range(Begin, End);
5852 }
5853
5854 const_association_range associations() const {
5855 ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() +
5856 AssocExprStartIndex,
5857 getTrailingObjects<TypeSourceInfo *>(),
5858 /*Offset=*/0, ResultIndex);
5859 ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
5860 /*Offset=*/NumAssocs, ResultIndex);
5861 return llvm::make_range(Begin, End);
5862 }
5863
5864 SourceLocation getGenericLoc() const {
5865 return GenericSelectionExprBits.GenericLoc;
5866 }
5867 SourceLocation getDefaultLoc() const { return DefaultLoc; }
5868 SourceLocation getRParenLoc() const { return RParenLoc; }
5869 SourceLocation getBeginLoc() const { return getGenericLoc(); }
5870 SourceLocation getEndLoc() const { return getRParenLoc(); }
5871
5872 static bool classof(const Stmt *T) {
5873 return T->getStmtClass() == GenericSelectionExprClass;
5874 }
5875
5876 child_range children() {
5877 return child_range(getTrailingObjects<Stmt *>(),
5878 getTrailingObjects<Stmt *>() +
5879 numTrailingObjects(OverloadToken<Stmt *>()));
5880 }
5881 const_child_range children() const {
5882 return const_child_range(getTrailingObjects<Stmt *>(),
5883 getTrailingObjects<Stmt *>() +
5884 numTrailingObjects(OverloadToken<Stmt *>()));
5885 }
5886};
5887
5888//===----------------------------------------------------------------------===//
5889// Clang Extensions
5890//===----------------------------------------------------------------------===//
5891
5892/// ExtVectorElementExpr - This represents access to specific elements of a
5893/// vector, and may occur on the left hand side or right hand side. For example
5894/// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
5895///
5896/// Note that the base may have either vector or pointer to vector type, just
5897/// like a struct field reference.
5898///
5899class ExtVectorElementExpr : public Expr {
5900 Stmt *Base;
5901 IdentifierInfo *Accessor;
5902 SourceLocation AccessorLoc;
5903public:
5904 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
5905 IdentifierInfo &accessor, SourceLocation loc)
5906 : Expr(ExtVectorElementExprClass, ty, VK,
5907 (VK == VK_PRValue ? OK_Ordinary : OK_VectorComponent)),
5908 Base(base), Accessor(&accessor), AccessorLoc(loc) {
5909 setDependence(computeDependence(this));
5910 }
5911
5912 /// Build an empty vector element expression.
5913 explicit ExtVectorElementExpr(EmptyShell Empty)
5914 : Expr(ExtVectorElementExprClass, Empty) { }
5915
5916 const Expr *getBase() const { return cast<Expr>(Base); }
5917 Expr *getBase() { return cast<Expr>(Base); }
5918 void setBase(Expr *E) { Base = E; }
5919
5920 IdentifierInfo &getAccessor() const { return *Accessor; }
5921 void setAccessor(IdentifierInfo *II) { Accessor = II; }
5922
5923 SourceLocation getAccessorLoc() const { return AccessorLoc; }
5924 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
5925
5926 /// getNumElements - Get the number of components being selected.
5927 unsigned getNumElements() const;
5928
5929 /// containsDuplicateElements - Return true if any element access is
5930 /// repeated.
5931 bool containsDuplicateElements() const;
5932
5933 /// getEncodedElementAccess - Encode the elements accessed into an llvm
5934 /// aggregate Constant of ConstantInt(s).
5935 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
5936
5937 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
5938 return getBase()->getBeginLoc();
5939 }
5940 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return AccessorLoc; }
5941
5942 /// isArrow - Return true if the base expression is a pointer to vector,
5943 /// return false if the base expression is a vector.
5944 bool isArrow() const;
5945
5946 static bool classof(const Stmt *T) {
5947 return T->getStmtClass() == ExtVectorElementExprClass;
5948 }
5949
5950 // Iterators
5951 child_range children() { return child_range(&Base, &Base+1); }
5952 const_child_range children() const {
5953 return const_child_range(&Base, &Base + 1);
5954 }
5955};
5956
5957/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
5958/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
5959class BlockExpr : public Expr {
5960protected:
5961 BlockDecl *TheBlock;
5962public:
5963 BlockExpr(BlockDecl *BD, QualType ty)
5964 : Expr(BlockExprClass, ty, VK_PRValue, OK_Ordinary), TheBlock(BD) {
5965 setDependence(computeDependence(this));
5966 }
5967
5968 /// Build an empty block expression.
5969 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
5970
5971 const BlockDecl *getBlockDecl() const { return TheBlock; }
5972 BlockDecl *getBlockDecl() { return TheBlock; }
5973 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
5974
5975 // Convenience functions for probing the underlying BlockDecl.
5976 SourceLocation getCaretLocation() const;
5977 const Stmt *getBody() const;
5978 Stmt *getBody();
5979
5980 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
5981 return getCaretLocation();
5982 }
5983 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
5984 return getBody()->getEndLoc();
5985 }
5986
5987 /// getFunctionType - Return the underlying function type for this block.
5988 const FunctionProtoType *getFunctionType() const;
5989
5990 static bool classof(const Stmt *T) {
5991 return T->getStmtClass() == BlockExprClass;
5992 }
5993
5994 // Iterators
5995 child_range children() {
5996 return child_range(child_iterator(), child_iterator());
5997 }
5998 const_child_range children() const {
5999 return const_child_range(const_child_iterator(), const_child_iterator());
6000 }
6001};
6002
6003/// Copy initialization expr of a __block variable and a boolean flag that
6004/// indicates whether the expression can throw.
6005struct BlockVarCopyInit {
6006 BlockVarCopyInit() = default;
6007 BlockVarCopyInit(Expr *CopyExpr, bool CanThrow)
6008 : ExprAndFlag(CopyExpr, CanThrow) {}
6009 void setExprAndFlag(Expr *CopyExpr, bool CanThrow) {
6010 ExprAndFlag.setPointerAndInt(CopyExpr, CanThrow);
6011 }
6012 Expr *getCopyExpr() const { return ExprAndFlag.getPointer(); }
6013 bool canThrow() const { return ExprAndFlag.getInt(); }
6014 llvm::PointerIntPair<Expr *, 1, bool> ExprAndFlag;
6015};
6016
6017/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
6018/// This AST node provides support for reinterpreting a type to another
6019/// type of the same size.
6020class AsTypeExpr : public Expr {
6021private:
6022 Stmt *SrcExpr;
6023 SourceLocation BuiltinLoc, RParenLoc;
6024
6025 friend class ASTReader;
6026 friend class ASTStmtReader;
6027 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
6028
6029public:
6030 AsTypeExpr(Expr *SrcExpr, QualType DstType, ExprValueKind VK,
6031 ExprObjectKind OK, SourceLocation BuiltinLoc,
6032 SourceLocation RParenLoc)
6033 : Expr(AsTypeExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
6034 BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
6035 setDependence(computeDependence(this));
6036 }
6037
6038 /// getSrcExpr - Return the Expr to be converted.
6039 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
6040
6041 /// getBuiltinLoc - Return the location of the __builtin_astype token.
6042 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
6043
6044 /// getRParenLoc - Return the location of final right parenthesis.
6045 SourceLocation getRParenLoc() const { return RParenLoc; }
6046
6047 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
6048 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
6049
6050 static bool classof(const Stmt *T) {
6051 return T->getStmtClass() == AsTypeExprClass;
6052 }
6053
6054 // Iterators
6055 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
6056 const_child_range children() const {
6057 return const_child_range(&SrcExpr, &SrcExpr + 1);
6058 }
6059};
6060
6061/// PseudoObjectExpr - An expression which accesses a pseudo-object
6062/// l-value. A pseudo-object is an abstract object, accesses to which
6063/// are translated to calls. The pseudo-object expression has a
6064/// syntactic form, which shows how the expression was actually
6065/// written in the source code, and a semantic form, which is a series
6066/// of expressions to be executed in order which detail how the
6067/// operation is actually evaluated. Optionally, one of the semantic
6068/// forms may also provide a result value for the expression.
6069///
6070/// If any of the semantic-form expressions is an OpaqueValueExpr,
6071/// that OVE is required to have a source expression, and it is bound
6072/// to the result of that source expression. Such OVEs may appear
6073/// only in subsequent semantic-form expressions and as
6074/// sub-expressions of the syntactic form.
6075///
6076/// PseudoObjectExpr should be used only when an operation can be
6077/// usefully described in terms of fairly simple rewrite rules on
6078/// objects and functions that are meant to be used by end-developers.
6079/// For example, under the Itanium ABI, dynamic casts are implemented
6080/// as a call to a runtime function called __dynamic_cast; using this
6081/// class to describe that would be inappropriate because that call is
6082/// not really part of the user-visible semantics, and instead the
6083/// cast is properly reflected in the AST and IR-generation has been
6084/// taught to generate the call as necessary. In contrast, an
6085/// Objective-C property access is semantically defined to be
6086/// equivalent to a particular message send, and this is very much
6087/// part of the user model. The name of this class encourages this
6088/// modelling design.
6089class PseudoObjectExpr final
6090 : public Expr,
6091 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
6092 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
6093 // Always at least two, because the first sub-expression is the
6094 // syntactic form.
6095
6096 // PseudoObjectExprBits.ResultIndex - The index of the
6097 // sub-expression holding the result. 0 means the result is void,
6098 // which is unambiguous because it's the index of the syntactic
6099 // form. Note that this is therefore 1 higher than the value passed
6100 // in to Create, which is an index within the semantic forms.
6101 // Note also that ASTStmtWriter assumes this encoding.
6102
6103 Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
6104 const Expr * const *getSubExprsBuffer() const {
6105 return getTrailingObjects<Expr *>();
6106 }
6107
6108 PseudoObjectExpr(QualType type, ExprValueKind VK,
6109 Expr *syntactic, ArrayRef<Expr*> semantic,
6110 unsigned resultIndex);
6111
6112 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
6113
6114 unsigned getNumSubExprs() const {
6115 return PseudoObjectExprBits.NumSubExprs;
6116 }
6117
6118public:
6119 /// NoResult - A value for the result index indicating that there is
6120 /// no semantic result.
6121 enum : unsigned { NoResult = ~0U };
6122
6123 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
6124 ArrayRef<Expr*> semantic,
6125 unsigned resultIndex);
6126
6127 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
6128 unsigned numSemanticExprs);
6129
6130 /// Return the syntactic form of this expression, i.e. the
6131 /// expression it actually looks like. Likely to be expressed in
6132 /// terms of OpaqueValueExprs bound in the semantic form.
6133 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
6134 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
6135
6136 /// Return the index of the result-bearing expression into the semantics
6137 /// expressions, or PseudoObjectExpr::NoResult if there is none.
6138 unsigned getResultExprIndex() const {
6139 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
6140 return PseudoObjectExprBits.ResultIndex - 1;
6141 }
6142
6143 /// Return the result-bearing expression, or null if there is none.
6144 Expr *getResultExpr() {
6145 if (PseudoObjectExprBits.ResultIndex == 0)
6146 return nullptr;
6147 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
6148 }
6149 const Expr *getResultExpr() const {
6150 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
6151 }
6152
6153 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
6154
6155 typedef Expr * const *semantics_iterator;
6156 typedef const Expr * const *const_semantics_iterator;
6157 semantics_iterator semantics_begin() {
6158 return getSubExprsBuffer() + 1;
6159 }
6160 const_semantics_iterator semantics_begin() const {
6161 return getSubExprsBuffer() + 1;
6162 }
6163 semantics_iterator semantics_end() {
6164 return getSubExprsBuffer() + getNumSubExprs();
6165 }
6166 const_semantics_iterator semantics_end() const {
6167 return getSubExprsBuffer() + getNumSubExprs();
6168 }
6169
6170 llvm::iterator_range<semantics_iterator> semantics() {
6171 return llvm::make_range(semantics_begin(), semantics_end());
6172 }
6173 llvm::iterator_range<const_semantics_iterator> semantics() const {
6174 return llvm::make_range(semantics_begin(), semantics_end());
6175 }
6176
6177 Expr *getSemanticExpr(unsigned index) {
6178 assert(index + 1 < getNumSubExprs())((void)0);
6179 return getSubExprsBuffer()[index + 1];
6180 }
6181 const Expr *getSemanticExpr(unsigned index) const {
6182 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
6183 }
6184
6185 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
6186 return getSyntacticForm()->getExprLoc();
6187 }
6188
6189 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
6190 return getSyntacticForm()->getBeginLoc();
6191 }
6192 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
6193 return getSyntacticForm()->getEndLoc();
6194 }
6195
6196 child_range children() {
6197 const_child_range CCR =
6198 const_cast<const PseudoObjectExpr *>(this)->children();
6199 return child_range(cast_away_const(CCR.begin()),
6200 cast_away_const(CCR.end()));
6201 }
6202 const_child_range children() const {
6203 Stmt *const *cs = const_cast<Stmt *const *>(
6204 reinterpret_cast<const Stmt *const *>(getSubExprsBuffer()));
6205 return const_child_range(cs, cs + getNumSubExprs());
6206 }
6207
6208 static bool classof(const Stmt *T) {
6209 return T->getStmtClass() == PseudoObjectExprClass;
6210 }
6211
6212 friend TrailingObjects;
6213 friend class ASTStmtReader;
6214};
6215
6216/// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
6217/// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
6218/// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>,
6219/// and corresponding __opencl_atomic_* for OpenCL 2.0.
6220/// All of these instructions take one primary pointer, at least one memory
6221/// order. The instructions for which getScopeModel returns non-null value
6222/// take one synch scope.
6223class AtomicExpr : public Expr {
6224public:
6225 enum AtomicOp {
6226#define BUILTIN(ID, TYPE, ATTRS)
6227#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
6228#include "clang/Basic/Builtins.def"
6229 // Avoid trailing comma
6230 BI_First = 0
6231 };
6232
6233private:
6234 /// Location of sub-expressions.
6235 /// The location of Scope sub-expression is NumSubExprs - 1, which is
6236 /// not fixed, therefore is not defined in enum.
6237 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
6238 Stmt *SubExprs[END_EXPR + 1];
6239 unsigned NumSubExprs;
6240 SourceLocation BuiltinLoc, RParenLoc;
6241 AtomicOp Op;
6242
6243 friend class ASTStmtReader;
6244public:
6245 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
6246 AtomicOp op, SourceLocation RP);
6247
6248 /// Determine the number of arguments the specified atomic builtin
6249 /// should have.
6250 static unsigned getNumSubExprs(AtomicOp Op);
6251
6252 /// Build an empty AtomicExpr.
6253 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
6254
6255 Expr *getPtr() const {
6256 return cast<Expr>(SubExprs[PTR]);
6257 }
6258 Expr *getOrder() const {
6259 return cast<Expr>(SubExprs[ORDER]);
6260 }
6261 Expr *getScope() const {
6262 assert(getScopeModel() && "No scope")((void)0);
6263 return cast<Expr>(SubExprs[NumSubExprs - 1]);
6264 }
6265 Expr *getVal1() const {
6266 if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init)
6267 return cast<Expr>(SubExprs[ORDER]);
6268 assert(NumSubExprs > VAL1)((void)0);
6269 return cast<Expr>(SubExprs[VAL1]);
6270 }
6271 Expr *getOrderFail() const {
6272 assert(NumSubExprs > ORDER_FAIL)((void)0);
6273 return cast<Expr>(SubExprs[ORDER_FAIL]);
6274 }
6275 Expr *getVal2() const {
6276 if (Op == AO__atomic_exchange)
6277 return cast<Expr>(SubExprs[ORDER_FAIL]);
6278 assert(NumSubExprs > VAL2)((void)0);
6279 return cast<Expr>(SubExprs[VAL2]);
6280 }
6281 Expr *getWeak() const {
6282 assert(NumSubExprs > WEAK)((void)0);
6283 return cast<Expr>(SubExprs[WEAK]);
6284 }
6285 QualType getValueType() const;
6286
6287 AtomicOp getOp() const { return Op; }
6288 unsigned getNumSubExprs() const { return NumSubExprs; }
6289
6290 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
6291 const Expr * const *getSubExprs() const {
6292 return reinterpret_cast<Expr * const *>(SubExprs);
6293 }
6294
6295 bool isVolatile() const {
6296 return getPtr()->getType()->getPointeeType().isVolatileQualified();
6297 }
6298
6299 bool isCmpXChg() const {
6300 return getOp() == AO__c11_atomic_compare_exchange_strong ||
6301 getOp() == AO__c11_atomic_compare_exchange_weak ||
6302 getOp() == AO__opencl_atomic_compare_exchange_strong ||
6303 getOp() == AO__opencl_atomic_compare_exchange_weak ||
6304 getOp() == AO__atomic_compare_exchange ||
6305 getOp() == AO__atomic_compare_exchange_n;
6306 }
6307
6308 bool isOpenCL() const {
6309 return getOp() >= AO__opencl_atomic_init &&
6310 getOp() <= AO__opencl_atomic_fetch_max;
6311 }
6312
6313 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
6314 SourceLocation getRParenLoc() const { return RParenLoc; }
6315
6316 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
6317 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
6318
6319 static bool classof(const Stmt *T) {
6320 return T->getStmtClass() == AtomicExprClass;
6321 }
6322
6323 // Iterators
6324 child_range children() {
6325 return child_range(SubExprs, SubExprs+NumSubExprs);
6326 }
6327 const_child_range children() const {
6328 return const_child_range(SubExprs, SubExprs + NumSubExprs);
6329 }
6330
6331 /// Get atomic scope model for the atomic op code.
6332 /// \return empty atomic scope model if the atomic op code does not have
6333 /// scope operand.
6334 static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) {
6335 auto Kind =
6336 (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max)
6337 ? AtomicScopeModelKind::OpenCL
6338 : AtomicScopeModelKind::None;
6339 return AtomicScopeModel::create(Kind);
6340 }
6341
6342 /// Get atomic scope model.
6343 /// \return empty atomic scope model if this atomic expression does not have
6344 /// scope operand.
6345 std::unique_ptr<AtomicScopeModel> getScopeModel() const {
6346 return getScopeModel(getOp());
6347 }
6348};
6349
6350/// TypoExpr - Internal placeholder for expressions where typo correction
6351/// still needs to be performed and/or an error diagnostic emitted.
6352class TypoExpr : public Expr {
6353 // The location for the typo name.
6354 SourceLocation TypoLoc;
6355
6356public:
6357 TypoExpr(QualType T, SourceLocation TypoLoc)
6358 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary), TypoLoc(TypoLoc) {
6359 assert(T->isDependentType() && "TypoExpr given a non-dependent type")((void)0);
6360 setDependence(ExprDependence::TypeValueInstantiation |
6361 ExprDependence::Error);
6362 }
6363
6364 child_range children() {
6365 return child_range(child_iterator(), child_iterator());
6366 }
6367 const_child_range children() const {
6368 return const_child_range(const_child_iterator(), const_child_iterator());
6369 }
6370
6371 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return TypoLoc; }
6372 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return TypoLoc; }
6373
6374 static bool classof(const Stmt *T) {
6375 return T->getStmtClass() == TypoExprClass;
6376 }
6377
6378};
6379
6380/// Frontend produces RecoveryExprs on semantic errors that prevent creating
6381/// other well-formed expressions. E.g. when type-checking of a binary operator
6382/// fails, we cannot produce a BinaryOperator expression. Instead, we can choose
6383/// to produce a recovery expression storing left and right operands.
6384///
6385/// RecoveryExpr does not have any semantic meaning in C++, it is only useful to
6386/// preserve expressions in AST that would otherwise be dropped. It captures
6387/// subexpressions of some expression that we could not construct and source
6388/// range covered by the expression.
6389///
6390/// By default, RecoveryExpr uses dependence-bits to take advantage of existing
6391/// machinery to deal with dependent code in C++, e.g. RecoveryExpr is preserved
6392/// in `decltype(<broken-expr>)` as part of the `DependentDecltypeType`. In
6393/// addition to that, clang does not report most errors on dependent
6394/// expressions, so we get rid of bogus errors for free. However, note that
6395/// unlike other dependent expressions, RecoveryExpr can be produced in
6396/// non-template contexts.
6397///
6398/// We will preserve the type in RecoveryExpr when the type is known, e.g.
6399/// preserving the return type for a broken non-overloaded function call, a
6400/// overloaded call where all candidates have the same return type. In this
6401/// case, the expression is not type-dependent (unless the known type is itself
6402/// dependent)
6403///
6404/// One can also reliably suppress all bogus errors on expressions containing
6405/// recovery expressions by examining results of Expr::containsErrors().
6406class RecoveryExpr final : public Expr,
6407 private llvm::TrailingObjects<RecoveryExpr, Expr *> {
6408public:
6409 static RecoveryExpr *Create(ASTContext &Ctx, QualType T,
6410 SourceLocation BeginLoc, SourceLocation EndLoc,
6411 ArrayRef<Expr *> SubExprs);
6412 static RecoveryExpr *CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs);
6413
6414 ArrayRef<Expr *> subExpressions() {
6415 auto *B = getTrailingObjects<Expr *>();
6416 return llvm::makeArrayRef(B, B + NumExprs);
6417 }
6418
6419 ArrayRef<const Expr *> subExpressions() const {
6420 return const_cast<RecoveryExpr *>(this)->subExpressions();
6421 }
6422
6423 child_range children() {
6424 Stmt **B = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
6425 return child_range(B, B + NumExprs);
6426 }
6427
6428 SourceLocation getBeginLoc() const { return BeginLoc; }
6429 SourceLocation getEndLoc() const { return EndLoc; }
6430
6431 static bool classof(const Stmt *T) {
6432 return T->getStmtClass() == RecoveryExprClass;
6433 }
6434
6435private:
6436 RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
6437 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs);
6438 RecoveryExpr(EmptyShell Empty, unsigned NumSubExprs)
6439 : Expr(RecoveryExprClass, Empty), NumExprs(NumSubExprs) {}
6440
6441 size_t numTrailingObjects(OverloadToken<Stmt *>) const { return NumExprs; }
6442
6443 SourceLocation BeginLoc, EndLoc;
6444 unsigned NumExprs;
6445 friend TrailingObjects;
6446 friend class ASTStmtReader;
6447 friend class ASTStmtWriter;
6448};
6449
6450} // end namespace clang
6451
6452#endif // LLVM_CLANG_AST_EXPR_H