Bug Summary

File:clang/lib/Sema/SemaExpr.cpp
Warning:line 9692, column 26
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaExpr.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-08-06-171148-17323-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/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/RecursiveASTVisitor.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/Basic/Builtins.h"
30#include "clang/Basic/FixedPoint.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/Support/ConvertUTF.h"
50#include "llvm/Support/SaveAndRestore.h"
51using namespace clang;
52using namespace sema;
53using llvm::RoundingMode;
54
55/// Determine whether the use of this declaration is valid, without
56/// emitting diagnostics.
57bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58 // See if this is an auto-typed variable whose initializer we are parsing.
59 if (ParsingInitForAutoVars.count(D))
60 return false;
61
62 // See if this is a deleted function.
63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64 if (FD->isDeleted())
65 return false;
66
67 // If the function has a deduced return type, and we can't deduce it,
68 // then we can't use it either.
69 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71 return false;
72
73 // See if this is an aligned allocation/deallocation function that is
74 // unavailable.
75 if (TreatUnavailableAsInvalid &&
76 isUnavailableAlignedAllocationFunction(*FD))
77 return false;
78 }
79
80 // See if this function is unavailable.
81 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83 return false;
84
85 return true;
86}
87
88static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89 // Warn if this is used but marked unused.
90 if (const auto *A = D->getAttr<UnusedAttr>()) {
91 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92 // should diagnose them.
93 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96 if (DC && !DC->hasAttr<UnusedAttr>())
97 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
98 }
99 }
100}
101
102/// Emit a note explaining that this function is deleted.
103void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104 assert(Decl && Decl->isDeleted())((Decl && Decl->isDeleted()) ? static_cast<void
> (0) : __assert_fail ("Decl && Decl->isDeleted()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 104, __PRETTY_FUNCTION__))
;
105
106 if (Decl->isDefaulted()) {
107 // If the method was explicitly defaulted, point at that declaration.
108 if (!Decl->isImplicit())
109 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110
111 // Try to diagnose why this special member function was implicitly
112 // deleted. This might fail, if that reason no longer applies.
113 DiagnoseDeletedDefaultedFunction(Decl);
114 return;
115 }
116
117 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118 if (Ctor && Ctor->isInheritingConstructor())
119 return NoteDeletedInheritingConstructor(Ctor);
120
121 Diag(Decl->getLocation(), diag::note_availability_specified_here)
122 << Decl << 1;
123}
124
125/// Determine whether a FunctionDecl was ever declared with an
126/// explicit storage class.
127static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128 for (auto I : D->redecls()) {
129 if (I->getStorageClass() != SC_None)
130 return true;
131 }
132 return false;
133}
134
135/// Check whether we're in an extern inline function and referring to a
136/// variable or function with internal linkage (C11 6.7.4p3).
137///
138/// This is only a warning because we used to silently accept this code, but
139/// in many cases it will not behave correctly. This is not enabled in C++ mode
140/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141/// and so while there may still be user mistakes, most of the time we can't
142/// prove that there are errors.
143static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144 const NamedDecl *D,
145 SourceLocation Loc) {
146 // This is disabled under C++; there are too many ways for this to fire in
147 // contexts where the warning is a false positive, or where it is technically
148 // correct but benign.
149 if (S.getLangOpts().CPlusPlus)
150 return;
151
152 // Check if this is an inlined function or method.
153 FunctionDecl *Current = S.getCurFunctionDecl();
154 if (!Current)
155 return;
156 if (!Current->isInlined())
157 return;
158 if (!Current->isExternallyVisible())
159 return;
160
161 // Check if the decl has internal linkage.
162 if (D->getFormalLinkage() != InternalLinkage)
163 return;
164
165 // Downgrade from ExtWarn to Extension if
166 // (1) the supposedly external inline function is in the main file,
167 // and probably won't be included anywhere else.
168 // (2) the thing we're referencing is a pure function.
169 // (3) the thing we're referencing is another inline function.
170 // This last can give us false negatives, but it's better than warning on
171 // wrappers for simple C library functions.
172 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174 if (!DowngradeWarning && UsedFn)
175 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
176
177 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178 : diag::ext_internal_in_extern_inline)
179 << /*IsVar=*/!UsedFn << D;
180
181 S.MaybeSuggestAddingStaticToDecl(Current);
182
183 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184 << D;
185}
186
187void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188 const FunctionDecl *First = Cur->getFirstDecl();
189
190 // Suggest "static" on the function, if possible.
191 if (!hasAnyExplicitStorageClass(First)) {
192 SourceLocation DeclBegin = First->getSourceRange().getBegin();
193 Diag(DeclBegin, diag::note_convert_inline_to_static)
194 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195 }
196}
197
198/// Determine whether the use of this declaration is valid, and
199/// emit any corresponding diagnostics.
200///
201/// This routine diagnoses various problems with referencing
202/// declarations that can occur when using a declaration. For example,
203/// it might warn if a deprecated or unavailable declaration is being
204/// used, or produce an error (and return true) if a C++0x deleted
205/// function is being used.
206///
207/// \returns true if there was an error (this declaration cannot be
208/// referenced), false otherwise.
209///
210bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211 const ObjCInterfaceDecl *UnknownObjCClass,
212 bool ObjCPropertyAccess,
213 bool AvoidPartialAvailabilityChecks,
214 ObjCInterfaceDecl *ClassReceiver) {
215 SourceLocation Loc = Locs.front();
216 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217 // If there were any diagnostics suppressed by template argument deduction,
218 // emit them now.
219 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220 if (Pos != SuppressedDiagnostics.end()) {
221 for (const PartialDiagnosticAt &Suppressed : Pos->second)
222 Diag(Suppressed.first, Suppressed.second);
223
224 // Clear out the list of suppressed diagnostics, so that we don't emit
225 // them again for this specialization. However, we don't obsolete this
226 // entry from the table, because we want to avoid ever emitting these
227 // diagnostics again.
228 Pos->second.clear();
229 }
230
231 // C++ [basic.start.main]p3:
232 // The function 'main' shall not be used within a program.
233 if (cast<FunctionDecl>(D)->isMain())
234 Diag(Loc, diag::ext_main_used);
235
236 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237 }
238
239 // See if this is an auto-typed variable whose initializer we are parsing.
240 if (ParsingInitForAutoVars.count(D)) {
241 if (isa<BindingDecl>(D)) {
242 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243 << D->getDeclName();
244 } else {
245 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246 << D->getDeclName() << cast<VarDecl>(D)->getType();
247 }
248 return true;
249 }
250
251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252 // See if this is a deleted function.
253 if (FD->isDeleted()) {
254 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255 if (Ctor && Ctor->isInheritingConstructor())
256 Diag(Loc, diag::err_deleted_inherited_ctor_use)
257 << Ctor->getParent()
258 << Ctor->getInheritedConstructor().getConstructor()->getParent();
259 else
260 Diag(Loc, diag::err_deleted_function_use);
261 NoteDeletedFunction(FD);
262 return true;
263 }
264
265 // [expr.prim.id]p4
266 // A program that refers explicitly or implicitly to a function with a
267 // trailing requires-clause whose constraint-expression is not satisfied,
268 // other than to declare it, is ill-formed. [...]
269 //
270 // See if this is a function with constraints that need to be satisfied.
271 // Check this before deducing the return type, as it might instantiate the
272 // definition.
273 if (FD->getTrailingRequiresClause()) {
274 ConstraintSatisfaction Satisfaction;
275 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276 // A diagnostic will have already been generated (non-constant
277 // constraint expression, for example)
278 return true;
279 if (!Satisfaction.IsSatisfied) {
280 Diag(Loc,
281 diag::err_reference_to_function_with_unsatisfied_constraints)
282 << D;
283 DiagnoseUnsatisfiedConstraint(Satisfaction);
284 return true;
285 }
286 }
287
288 // If the function has a deduced return type, and we can't deduce it,
289 // then we can't use it either.
290 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291 DeduceReturnType(FD, Loc))
292 return true;
293
294 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
295 return true;
296
297 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
298 return true;
299 }
300
301 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
302 // Lambdas are only default-constructible or assignable in C++2a onwards.
303 if (MD->getParent()->isLambda() &&
304 ((isa<CXXConstructorDecl>(MD) &&
305 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
306 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
307 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
308 << !isa<CXXConstructorDecl>(MD);
309 }
310 }
311
312 auto getReferencedObjCProp = [](const NamedDecl *D) ->
313 const ObjCPropertyDecl * {
314 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
315 return MD->findPropertyDecl();
316 return nullptr;
317 };
318 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
319 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
320 return true;
321 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
322 return true;
323 }
324
325 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
326 // Only the variables omp_in and omp_out are allowed in the combiner.
327 // Only the variables omp_priv and omp_orig are allowed in the
328 // initializer-clause.
329 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
330 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
331 isa<VarDecl>(D)) {
332 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
333 << getCurFunction()->HasOMPDeclareReductionCombiner;
334 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
335 return true;
336 }
337
338 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
339 // List-items in map clauses on this construct may only refer to the declared
340 // variable var and entities that could be referenced by a procedure defined
341 // at the same location
342 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
343 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
344 isa<VarDecl>(D)) {
345 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
346 << DMD->getVarName().getAsString();
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348 return true;
349 }
350
351 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
352 AvoidPartialAvailabilityChecks, ClassReceiver);
353
354 DiagnoseUnusedOfDecl(*this, D, Loc);
355
356 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
357
358 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
359 if (const auto *VD = dyn_cast<ValueDecl>(D))
360 checkDeviceDecl(VD, Loc);
361
362 if (!Context.getTargetInfo().isTLSSupported())
363 if (const auto *VD = dyn_cast<VarDecl>(D))
364 if (VD->getTLSKind() != VarDecl::TLS_None)
365 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
366 }
367
368 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
369 !isUnevaluatedContext()) {
370 // C++ [expr.prim.req.nested] p3
371 // A local parameter shall only appear as an unevaluated operand
372 // (Clause 8) within the constraint-expression.
373 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
374 << D;
375 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
376 return true;
377 }
378
379 return false;
380}
381
382/// DiagnoseSentinelCalls - This routine checks whether a call or
383/// message-send is to a declaration with the sentinel attribute, and
384/// if so, it checks that the requirements of the sentinel are
385/// satisfied.
386void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
387 ArrayRef<Expr *> Args) {
388 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
389 if (!attr)
390 return;
391
392 // The number of formal parameters of the declaration.
393 unsigned numFormalParams;
394
395 // The kind of declaration. This is also an index into a %select in
396 // the diagnostic.
397 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
398
399 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
400 numFormalParams = MD->param_size();
401 calleeType = CT_Method;
402 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
403 numFormalParams = FD->param_size();
404 calleeType = CT_Function;
405 } else if (isa<VarDecl>(D)) {
406 QualType type = cast<ValueDecl>(D)->getType();
407 const FunctionType *fn = nullptr;
408 if (const PointerType *ptr = type->getAs<PointerType>()) {
409 fn = ptr->getPointeeType()->getAs<FunctionType>();
410 if (!fn) return;
411 calleeType = CT_Function;
412 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
413 fn = ptr->getPointeeType()->castAs<FunctionType>();
414 calleeType = CT_Block;
415 } else {
416 return;
417 }
418
419 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
420 numFormalParams = proto->getNumParams();
421 } else {
422 numFormalParams = 0;
423 }
424 } else {
425 return;
426 }
427
428 // "nullPos" is the number of formal parameters at the end which
429 // effectively count as part of the variadic arguments. This is
430 // useful if you would prefer to not have *any* formal parameters,
431 // but the language forces you to have at least one.
432 unsigned nullPos = attr->getNullPos();
433 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"
) ? static_cast<void> (0) : __assert_fail ("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 433, __PRETTY_FUNCTION__))
;
434 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
435
436 // The number of arguments which should follow the sentinel.
437 unsigned numArgsAfterSentinel = attr->getSentinel();
438
439 // If there aren't enough arguments for all the formal parameters,
440 // the sentinel, and the args after the sentinel, complain.
441 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
442 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
443 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
444 return;
445 }
446
447 // Otherwise, find the sentinel expression.
448 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
449 if (!sentinelExpr) return;
450 if (sentinelExpr->isValueDependent()) return;
451 if (Context.isSentinelNullExpr(sentinelExpr)) return;
452
453 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
454 // or 'NULL' if those are actually defined in the context. Only use
455 // 'nil' for ObjC methods, where it's much more likely that the
456 // variadic arguments form a list of object pointers.
457 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
458 std::string NullValue;
459 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
460 NullValue = "nil";
461 else if (getLangOpts().CPlusPlus11)
462 NullValue = "nullptr";
463 else if (PP.isMacroDefined("NULL"))
464 NullValue = "NULL";
465 else
466 NullValue = "(void*) 0";
467
468 if (MissingNilLoc.isInvalid())
469 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
470 else
471 Diag(MissingNilLoc, diag::warn_missing_sentinel)
472 << int(calleeType)
473 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
474 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
475}
476
477SourceRange Sema::getExprRange(Expr *E) const {
478 return E ? E->getSourceRange() : SourceRange();
479}
480
481//===----------------------------------------------------------------------===//
482// Standard Promotions and Conversions
483//===----------------------------------------------------------------------===//
484
485/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
486ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
487 // Handle any placeholder expressions which made it here.
488 if (E->getType()->isPlaceholderType()) {
489 ExprResult result = CheckPlaceholderExpr(E);
490 if (result.isInvalid()) return ExprError();
491 E = result.get();
492 }
493
494 QualType Ty = E->getType();
495 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")((!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 495, __PRETTY_FUNCTION__))
;
496
497 if (Ty->isFunctionType()) {
498 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
499 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
500 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
501 return ExprError();
502
503 E = ImpCastExprToType(E, Context.getPointerType(Ty),
504 CK_FunctionToPointerDecay).get();
505 } else if (Ty->isArrayType()) {
506 // In C90 mode, arrays only promote to pointers if the array expression is
507 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
508 // type 'array of type' is converted to an expression that has type 'pointer
509 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
510 // that has type 'array of type' ...". The relevant change is "an lvalue"
511 // (C90) to "an expression" (C99).
512 //
513 // C++ 4.2p1:
514 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
515 // T" can be converted to an rvalue of type "pointer to T".
516 //
517 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
518 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
519 CK_ArrayToPointerDecay).get();
520 }
521 return E;
522}
523
524static void CheckForNullPointerDereference(Sema &S, Expr *E) {
525 // Check to see if we are dereferencing a null pointer. If so,
526 // and if not volatile-qualified, this is undefined behavior that the
527 // optimizer will delete, so warn about it. People sometimes try to use this
528 // to get a deterministic trap and are surprised by clang's behavior. This
529 // only handles the pattern "*null", which is a very syntactic check.
530 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
531 if (UO && UO->getOpcode() == UO_Deref &&
532 UO->getSubExpr()->getType()->isPointerType()) {
533 const LangAS AS =
534 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
535 if ((!isTargetAddressSpace(AS) ||
536 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
537 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
538 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
539 !UO->getType().isVolatileQualified()) {
540 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
541 S.PDiag(diag::warn_indirection_through_null)
542 << UO->getSubExpr()->getSourceRange());
543 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
544 S.PDiag(diag::note_indirection_through_null));
545 }
546 }
547}
548
549static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
550 SourceLocation AssignLoc,
551 const Expr* RHS) {
552 const ObjCIvarDecl *IV = OIRE->getDecl();
553 if (!IV)
554 return;
555
556 DeclarationName MemberName = IV->getDeclName();
557 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
558 if (!Member || !Member->isStr("isa"))
559 return;
560
561 const Expr *Base = OIRE->getBase();
562 QualType BaseType = Base->getType();
563 if (OIRE->isArrow())
564 BaseType = BaseType->getPointeeType();
565 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
566 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
567 ObjCInterfaceDecl *ClassDeclared = nullptr;
568 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
569 if (!ClassDeclared->getSuperClass()
570 && (*ClassDeclared->ivar_begin()) == IV) {
571 if (RHS) {
572 NamedDecl *ObjectSetClass =
573 S.LookupSingleName(S.TUScope,
574 &S.Context.Idents.get("object_setClass"),
575 SourceLocation(), S.LookupOrdinaryName);
576 if (ObjectSetClass) {
577 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
578 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
579 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
580 "object_setClass(")
581 << FixItHint::CreateReplacement(
582 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
583 << FixItHint::CreateInsertion(RHSLocEnd, ")");
584 }
585 else
586 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
587 } else {
588 NamedDecl *ObjectGetClass =
589 S.LookupSingleName(S.TUScope,
590 &S.Context.Idents.get("object_getClass"),
591 SourceLocation(), S.LookupOrdinaryName);
592 if (ObjectGetClass)
593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
595 "object_getClass(")
596 << FixItHint::CreateReplacement(
597 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
598 else
599 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
600 }
601 S.Diag(IV->getLocation(), diag::note_ivar_decl);
602 }
603 }
604}
605
606ExprResult Sema::DefaultLvalueConversion(Expr *E) {
607 // Handle any placeholder expressions which made it here.
608 if (E->getType()->isPlaceholderType()) {
609 ExprResult result = CheckPlaceholderExpr(E);
610 if (result.isInvalid()) return ExprError();
611 E = result.get();
612 }
613
614 // C++ [conv.lval]p1:
615 // A glvalue of a non-function, non-array type T can be
616 // converted to a prvalue.
617 if (!E->isGLValue()) return E;
618
619 QualType T = E->getType();
620 assert(!T.isNull() && "r-value conversion on typeless expression?")((!T.isNull() && "r-value conversion on typeless expression?"
) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 620, __PRETTY_FUNCTION__))
;
621
622 // lvalue-to-rvalue conversion cannot be applied to function or array types.
623 if (T->isFunctionType() || T->isArrayType())
624 return E;
625
626 // We don't want to throw lvalue-to-rvalue casts on top of
627 // expressions of certain types in C++.
628 if (getLangOpts().CPlusPlus &&
629 (E->getType() == Context.OverloadTy ||
630 T->isDependentType() ||
631 T->isRecordType()))
632 return E;
633
634 // The C standard is actually really unclear on this point, and
635 // DR106 tells us what the result should be but not why. It's
636 // generally best to say that void types just doesn't undergo
637 // lvalue-to-rvalue at all. Note that expressions of unqualified
638 // 'void' type are never l-values, but qualified void can be.
639 if (T->isVoidType())
640 return E;
641
642 // OpenCL usually rejects direct accesses to values of 'half' type.
643 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
644 T->isHalfType()) {
645 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
646 << 0 << T;
647 return ExprError();
648 }
649
650 CheckForNullPointerDereference(*this, E);
651 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
652 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
653 &Context.Idents.get("object_getClass"),
654 SourceLocation(), LookupOrdinaryName);
655 if (ObjectGetClass)
656 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
657 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
658 << FixItHint::CreateReplacement(
659 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
660 else
661 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
662 }
663 else if (const ObjCIvarRefExpr *OIRE =
664 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
665 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
666
667 // C++ [conv.lval]p1:
668 // [...] If T is a non-class type, the type of the prvalue is the
669 // cv-unqualified version of T. Otherwise, the type of the
670 // rvalue is T.
671 //
672 // C99 6.3.2.1p2:
673 // If the lvalue has qualified type, the value has the unqualified
674 // version of the type of the lvalue; otherwise, the value has the
675 // type of the lvalue.
676 if (T.hasQualifiers())
677 T = T.getUnqualifiedType();
678
679 // Under the MS ABI, lock down the inheritance model now.
680 if (T->isMemberPointerType() &&
681 Context.getTargetInfo().getCXXABI().isMicrosoft())
682 (void)isCompleteType(E->getExprLoc(), T);
683
684 ExprResult Res = CheckLValueToRValueConversionOperand(E);
685 if (Res.isInvalid())
686 return Res;
687 E = Res.get();
688
689 // Loading a __weak object implicitly retains the value, so we need a cleanup to
690 // balance that.
691 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
692 Cleanup.setExprNeedsCleanups(true);
693
694 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
695 Cleanup.setExprNeedsCleanups(true);
696
697 // C++ [conv.lval]p3:
698 // If T is cv std::nullptr_t, the result is a null pointer constant.
699 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
700 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
701
702 // C11 6.3.2.1p2:
703 // ... if the lvalue has atomic type, the value has the non-atomic version
704 // of the type of the lvalue ...
705 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
706 T = Atomic->getValueType().getUnqualifiedType();
707 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
708 nullptr, VK_RValue);
709 }
710
711 return Res;
712}
713
714ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
715 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
716 if (Res.isInvalid())
717 return ExprError();
718 Res = DefaultLvalueConversion(Res.get());
719 if (Res.isInvalid())
720 return ExprError();
721 return Res;
722}
723
724/// CallExprUnaryConversions - a special case of an unary conversion
725/// performed on a function designator of a call expression.
726ExprResult Sema::CallExprUnaryConversions(Expr *E) {
727 QualType Ty = E->getType();
728 ExprResult Res = E;
729 // Only do implicit cast for a function type, but not for a pointer
730 // to function type.
731 if (Ty->isFunctionType()) {
732 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
733 CK_FunctionToPointerDecay);
734 if (Res.isInvalid())
735 return ExprError();
736 }
737 Res = DefaultLvalueConversion(Res.get());
738 if (Res.isInvalid())
739 return ExprError();
740 return Res.get();
741}
742
743/// UsualUnaryConversions - Performs various conversions that are common to most
744/// operators (C99 6.3). The conversions of array and function types are
745/// sometimes suppressed. For example, the array->pointer conversion doesn't
746/// apply if the array is an argument to the sizeof or address (&) operators.
747/// In these instances, this routine should *not* be called.
748ExprResult Sema::UsualUnaryConversions(Expr *E) {
749 // First, convert to an r-value.
750 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
751 if (Res.isInvalid())
752 return ExprError();
753 E = Res.get();
754
755 QualType Ty = E->getType();
756 assert(!Ty.isNull() && "UsualUnaryConversions - missing type")((!Ty.isNull() && "UsualUnaryConversions - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 756, __PRETTY_FUNCTION__))
;
757
758 // Half FP have to be promoted to float unless it is natively supported
759 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
760 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
761
762 // Try to perform integral promotions if the object has a theoretically
763 // promotable type.
764 if (Ty->isIntegralOrUnscopedEnumerationType()) {
765 // C99 6.3.1.1p2:
766 //
767 // The following may be used in an expression wherever an int or
768 // unsigned int may be used:
769 // - an object or expression with an integer type whose integer
770 // conversion rank is less than or equal to the rank of int
771 // and unsigned int.
772 // - A bit-field of type _Bool, int, signed int, or unsigned int.
773 //
774 // If an int can represent all values of the original type, the
775 // value is converted to an int; otherwise, it is converted to an
776 // unsigned int. These are called the integer promotions. All
777 // other types are unchanged by the integer promotions.
778
779 QualType PTy = Context.isPromotableBitField(E);
780 if (!PTy.isNull()) {
781 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
782 return E;
783 }
784 if (Ty->isPromotableIntegerType()) {
785 QualType PT = Context.getPromotedIntegerType(Ty);
786 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
787 return E;
788 }
789 }
790 return E;
791}
792
793/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
794/// do not have a prototype. Arguments that have type float or __fp16
795/// are promoted to double. All other argument types are converted by
796/// UsualUnaryConversions().
797ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
798 QualType Ty = E->getType();
799 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")((!Ty.isNull() && "DefaultArgumentPromotion - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 799, __PRETTY_FUNCTION__))
;
800
801 ExprResult Res = UsualUnaryConversions(E);
802 if (Res.isInvalid())
803 return ExprError();
804 E = Res.get();
805
806 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
807 // promote to double.
808 // Note that default argument promotion applies only to float (and
809 // half/fp16); it does not apply to _Float16.
810 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
811 if (BTy && (BTy->getKind() == BuiltinType::Half ||
812 BTy->getKind() == BuiltinType::Float)) {
813 if (getLangOpts().OpenCL &&
814 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
815 if (BTy->getKind() == BuiltinType::Half) {
816 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
817 }
818 } else {
819 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
820 }
821 }
822
823 // C++ performs lvalue-to-rvalue conversion as a default argument
824 // promotion, even on class types, but note:
825 // C++11 [conv.lval]p2:
826 // When an lvalue-to-rvalue conversion occurs in an unevaluated
827 // operand or a subexpression thereof the value contained in the
828 // referenced object is not accessed. Otherwise, if the glvalue
829 // has a class type, the conversion copy-initializes a temporary
830 // of type T from the glvalue and the result of the conversion
831 // is a prvalue for the temporary.
832 // FIXME: add some way to gate this entire thing for correctness in
833 // potentially potentially evaluated contexts.
834 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
835 ExprResult Temp = PerformCopyInitialization(
836 InitializedEntity::InitializeTemporary(E->getType()),
837 E->getExprLoc(), E);
838 if (Temp.isInvalid())
839 return ExprError();
840 E = Temp.get();
841 }
842
843 return E;
844}
845
846/// Determine the degree of POD-ness for an expression.
847/// Incomplete types are considered POD, since this check can be performed
848/// when we're in an unevaluated context.
849Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
850 if (Ty->isIncompleteType()) {
851 // C++11 [expr.call]p7:
852 // After these conversions, if the argument does not have arithmetic,
853 // enumeration, pointer, pointer to member, or class type, the program
854 // is ill-formed.
855 //
856 // Since we've already performed array-to-pointer and function-to-pointer
857 // decay, the only such type in C++ is cv void. This also handles
858 // initializer lists as variadic arguments.
859 if (Ty->isVoidType())
860 return VAK_Invalid;
861
862 if (Ty->isObjCObjectType())
863 return VAK_Invalid;
864 return VAK_Valid;
865 }
866
867 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
868 return VAK_Invalid;
869
870 if (Ty.isCXX98PODType(Context))
871 return VAK_Valid;
872
873 // C++11 [expr.call]p7:
874 // Passing a potentially-evaluated argument of class type (Clause 9)
875 // having a non-trivial copy constructor, a non-trivial move constructor,
876 // or a non-trivial destructor, with no corresponding parameter,
877 // is conditionally-supported with implementation-defined semantics.
878 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
879 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
880 if (!Record->hasNonTrivialCopyConstructor() &&
881 !Record->hasNonTrivialMoveConstructor() &&
882 !Record->hasNonTrivialDestructor())
883 return VAK_ValidInCXX11;
884
885 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
886 return VAK_Valid;
887
888 if (Ty->isObjCObjectType())
889 return VAK_Invalid;
890
891 if (getLangOpts().MSVCCompat)
892 return VAK_MSVCUndefined;
893
894 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
895 // permitted to reject them. We should consider doing so.
896 return VAK_Undefined;
897}
898
899void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
900 // Don't allow one to pass an Objective-C interface to a vararg.
901 const QualType &Ty = E->getType();
902 VarArgKind VAK = isValidVarArgType(Ty);
903
904 // Complain about passing non-POD types through varargs.
905 switch (VAK) {
906 case VAK_ValidInCXX11:
907 DiagRuntimeBehavior(
908 E->getBeginLoc(), nullptr,
909 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
910 LLVM_FALLTHROUGH[[gnu::fallthrough]];
911 case VAK_Valid:
912 if (Ty->isRecordType()) {
913 // This is unlikely to be what the user intended. If the class has a
914 // 'c_str' member function, the user probably meant to call that.
915 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
916 PDiag(diag::warn_pass_class_arg_to_vararg)
917 << Ty << CT << hasCStrMethod(E) << ".c_str()");
918 }
919 break;
920
921 case VAK_Undefined:
922 case VAK_MSVCUndefined:
923 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
924 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
925 << getLangOpts().CPlusPlus11 << Ty << CT);
926 break;
927
928 case VAK_Invalid:
929 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
930 Diag(E->getBeginLoc(),
931 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
932 << Ty << CT;
933 else if (Ty->isObjCObjectType())
934 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
935 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
936 << Ty << CT);
937 else
938 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
939 << isa<InitListExpr>(E) << Ty << CT;
940 break;
941 }
942}
943
944/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
945/// will create a trap if the resulting type is not a POD type.
946ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
947 FunctionDecl *FDecl) {
948 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
949 // Strip the unbridged-cast placeholder expression off, if applicable.
950 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
951 (CT == VariadicMethod ||
952 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
953 E = stripARCUnbridgedCast(E);
954
955 // Otherwise, do normal placeholder checking.
956 } else {
957 ExprResult ExprRes = CheckPlaceholderExpr(E);
958 if (ExprRes.isInvalid())
959 return ExprError();
960 E = ExprRes.get();
961 }
962 }
963
964 ExprResult ExprRes = DefaultArgumentPromotion(E);
965 if (ExprRes.isInvalid())
966 return ExprError();
967
968 // Copy blocks to the heap.
969 if (ExprRes.get()->getType()->isBlockPointerType())
970 maybeExtendBlockObject(ExprRes);
971
972 E = ExprRes.get();
973
974 // Diagnostics regarding non-POD argument types are
975 // emitted along with format string checking in Sema::CheckFunctionCall().
976 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
977 // Turn this into a trap.
978 CXXScopeSpec SS;
979 SourceLocation TemplateKWLoc;
980 UnqualifiedId Name;
981 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
982 E->getBeginLoc());
983 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
984 /*HasTrailingLParen=*/true,
985 /*IsAddressOfOperand=*/false);
986 if (TrapFn.isInvalid())
987 return ExprError();
988
989 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
990 None, E->getEndLoc());
991 if (Call.isInvalid())
992 return ExprError();
993
994 ExprResult Comma =
995 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
996 if (Comma.isInvalid())
997 return ExprError();
998 return Comma.get();
999 }
1000
1001 if (!getLangOpts().CPlusPlus &&
1002 RequireCompleteType(E->getExprLoc(), E->getType(),
1003 diag::err_call_incomplete_argument))
1004 return ExprError();
1005
1006 return E;
1007}
1008
1009/// Converts an integer to complex float type. Helper function of
1010/// UsualArithmeticConversions()
1011///
1012/// \return false if the integer expression is an integer type and is
1013/// successfully converted to the complex type.
1014static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1015 ExprResult &ComplexExpr,
1016 QualType IntTy,
1017 QualType ComplexTy,
1018 bool SkipCast) {
1019 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1020 if (SkipCast) return false;
1021 if (IntTy->isIntegerType()) {
1022 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1024 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1025 CK_FloatingRealToComplex);
1026 } else {
1027 assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void>
(0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1027, __PRETTY_FUNCTION__))
;
1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1029 CK_IntegralComplexToFloatingComplex);
1030 }
1031 return false;
1032}
1033
1034/// Handle arithmetic conversion with complex types. Helper function of
1035/// UsualArithmeticConversions()
1036static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1037 ExprResult &RHS, QualType LHSType,
1038 QualType RHSType,
1039 bool IsCompAssign) {
1040 // if we have an integer operand, the result is the complex type.
1041 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1042 /*skipCast*/false))
1043 return LHSType;
1044 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1045 /*skipCast*/IsCompAssign))
1046 return RHSType;
1047
1048 // This handles complex/complex, complex/float, or float/complex.
1049 // When both operands are complex, the shorter operand is converted to the
1050 // type of the longer, and that is the type of the result. This corresponds
1051 // to what is done when combining two real floating-point operands.
1052 // The fun begins when size promotion occur across type domains.
1053 // From H&S 6.3.4: When one operand is complex and the other is a real
1054 // floating-point type, the less precise type is converted, within it's
1055 // real or complex domain, to the precision of the other type. For example,
1056 // when combining a "long double" with a "double _Complex", the
1057 // "double _Complex" is promoted to "long double _Complex".
1058
1059 // Compute the rank of the two types, regardless of whether they are complex.
1060 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1061
1062 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1063 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1064 QualType LHSElementType =
1065 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1066 QualType RHSElementType =
1067 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1068
1069 QualType ResultType = S.Context.getComplexType(LHSElementType);
1070 if (Order < 0) {
1071 // Promote the precision of the LHS if not an assignment.
1072 ResultType = S.Context.getComplexType(RHSElementType);
1073 if (!IsCompAssign) {
1074 if (LHSComplexType)
1075 LHS =
1076 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1077 else
1078 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1079 }
1080 } else if (Order > 0) {
1081 // Promote the precision of the RHS.
1082 if (RHSComplexType)
1083 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1084 else
1085 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1086 }
1087 return ResultType;
1088}
1089
1090/// Handle arithmetic conversion from integer to float. Helper function
1091/// of UsualArithmeticConversions()
1092static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1093 ExprResult &IntExpr,
1094 QualType FloatTy, QualType IntTy,
1095 bool ConvertFloat, bool ConvertInt) {
1096 if (IntTy->isIntegerType()) {
1097 if (ConvertInt)
1098 // Convert intExpr to the lhs floating point type.
1099 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1100 CK_IntegralToFloating);
1101 return FloatTy;
1102 }
1103
1104 // Convert both sides to the appropriate complex float.
1105 assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void>
(0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1105, __PRETTY_FUNCTION__))
;
1106 QualType result = S.Context.getComplexType(FloatTy);
1107
1108 // _Complex int -> _Complex float
1109 if (ConvertInt)
1110 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1111 CK_IntegralComplexToFloatingComplex);
1112
1113 // float -> _Complex float
1114 if (ConvertFloat)
1115 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1116 CK_FloatingRealToComplex);
1117
1118 return result;
1119}
1120
1121/// Handle arithmethic conversion with floating point types. Helper
1122/// function of UsualArithmeticConversions()
1123static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1124 ExprResult &RHS, QualType LHSType,
1125 QualType RHSType, bool IsCompAssign) {
1126 bool LHSFloat = LHSType->isRealFloatingType();
1127 bool RHSFloat = RHSType->isRealFloatingType();
1128
1129 // If we have two real floating types, convert the smaller operand
1130 // to the bigger result.
1131 if (LHSFloat && RHSFloat) {
1132 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1133 if (order > 0) {
1134 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1135 return LHSType;
1136 }
1137
1138 assert(order < 0 && "illegal float comparison")((order < 0 && "illegal float comparison") ? static_cast
<void> (0) : __assert_fail ("order < 0 && \"illegal float comparison\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1138, __PRETTY_FUNCTION__))
;
1139 if (!IsCompAssign)
1140 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1141 return RHSType;
1142 }
1143
1144 if (LHSFloat) {
1145 // Half FP has to be promoted to float unless it is natively supported
1146 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1147 LHSType = S.Context.FloatTy;
1148
1149 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1150 /*ConvertFloat=*/!IsCompAssign,
1151 /*ConvertInt=*/ true);
1152 }
1153 assert(RHSFloat)((RHSFloat) ? static_cast<void> (0) : __assert_fail ("RHSFloat"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1153, __PRETTY_FUNCTION__))
;
1154 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1155 /*convertInt=*/ true,
1156 /*convertFloat=*/!IsCompAssign);
1157}
1158
1159/// Diagnose attempts to convert between __float128 and long double if
1160/// there is no support for such conversion. Helper function of
1161/// UsualArithmeticConversions().
1162static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1163 QualType RHSType) {
1164 /* No issue converting if at least one of the types is not a floating point
1165 type or the two types have the same rank.
1166 */
1167 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1168 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1169 return false;
1170
1171 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&((LHSType->isFloatingType() && RHSType->isFloatingType
() && "The remaining types must be floating point types."
) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1172, __PRETTY_FUNCTION__))
1172 "The remaining types must be floating point types.")((LHSType->isFloatingType() && RHSType->isFloatingType
() && "The remaining types must be floating point types."
) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1172, __PRETTY_FUNCTION__))
;
1173
1174 auto *LHSComplex = LHSType->getAs<ComplexType>();
1175 auto *RHSComplex = RHSType->getAs<ComplexType>();
1176
1177 QualType LHSElemType = LHSComplex ?
1178 LHSComplex->getElementType() : LHSType;
1179 QualType RHSElemType = RHSComplex ?
1180 RHSComplex->getElementType() : RHSType;
1181
1182 // No issue if the two types have the same representation
1183 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1184 &S.Context.getFloatTypeSemantics(RHSElemType))
1185 return false;
1186
1187 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1188 RHSElemType == S.Context.LongDoubleTy);
1189 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1190 RHSElemType == S.Context.Float128Ty);
1191
1192 // We've handled the situation where __float128 and long double have the same
1193 // representation. We allow all conversions for all possible long double types
1194 // except PPC's double double.
1195 return Float128AndLongDouble &&
1196 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1197 &llvm::APFloat::PPCDoubleDouble());
1198}
1199
1200typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1201
1202namespace {
1203/// These helper callbacks are placed in an anonymous namespace to
1204/// permit their use as function template parameters.
1205ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1206 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1207}
1208
1209ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1210 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1211 CK_IntegralComplexCast);
1212}
1213}
1214
1215/// Handle integer arithmetic conversions. Helper function of
1216/// UsualArithmeticConversions()
1217template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1218static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1219 ExprResult &RHS, QualType LHSType,
1220 QualType RHSType, bool IsCompAssign) {
1221 // The rules for this case are in C99 6.3.1.8
1222 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1223 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1224 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1225 if (LHSSigned == RHSSigned) {
1226 // Same signedness; use the higher-ranked type
1227 if (order >= 0) {
1228 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1229 return LHSType;
1230 } else if (!IsCompAssign)
1231 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1232 return RHSType;
1233 } else if (order != (LHSSigned ? 1 : -1)) {
1234 // The unsigned type has greater than or equal rank to the
1235 // signed type, so use the unsigned type
1236 if (RHSSigned) {
1237 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1238 return LHSType;
1239 } else if (!IsCompAssign)
1240 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1241 return RHSType;
1242 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1243 // The two types are different widths; if we are here, that
1244 // means the signed type is larger than the unsigned type, so
1245 // use the signed type.
1246 if (LHSSigned) {
1247 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1248 return LHSType;
1249 } else if (!IsCompAssign)
1250 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1251 return RHSType;
1252 } else {
1253 // The signed type is higher-ranked than the unsigned type,
1254 // but isn't actually any bigger (like unsigned int and long
1255 // on most 32-bit systems). Use the unsigned type corresponding
1256 // to the signed type.
1257 QualType result =
1258 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1259 RHS = (*doRHSCast)(S, RHS.get(), result);
1260 if (!IsCompAssign)
1261 LHS = (*doLHSCast)(S, LHS.get(), result);
1262 return result;
1263 }
1264}
1265
1266/// Handle conversions with GCC complex int extension. Helper function
1267/// of UsualArithmeticConversions()
1268static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1269 ExprResult &RHS, QualType LHSType,
1270 QualType RHSType,
1271 bool IsCompAssign) {
1272 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1273 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1274
1275 if (LHSComplexInt && RHSComplexInt) {
1276 QualType LHSEltType = LHSComplexInt->getElementType();
1277 QualType RHSEltType = RHSComplexInt->getElementType();
1278 QualType ScalarType =
1279 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1280 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1281
1282 return S.Context.getComplexType(ScalarType);
1283 }
1284
1285 if (LHSComplexInt) {
1286 QualType LHSEltType = LHSComplexInt->getElementType();
1287 QualType ScalarType =
1288 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1289 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1290 QualType ComplexType = S.Context.getComplexType(ScalarType);
1291 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1292 CK_IntegralRealToComplex);
1293
1294 return ComplexType;
1295 }
1296
1297 assert(RHSComplexInt)((RHSComplexInt) ? static_cast<void> (0) : __assert_fail
("RHSComplexInt", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1297, __PRETTY_FUNCTION__))
;
1298
1299 QualType RHSEltType = RHSComplexInt->getElementType();
1300 QualType ScalarType =
1301 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1302 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1303 QualType ComplexType = S.Context.getComplexType(ScalarType);
1304
1305 if (!IsCompAssign)
1306 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1307 CK_IntegralRealToComplex);
1308 return ComplexType;
1309}
1310
1311/// Return the rank of a given fixed point or integer type. The value itself
1312/// doesn't matter, but the values must be increasing with proper increasing
1313/// rank as described in N1169 4.1.1.
1314static unsigned GetFixedPointRank(QualType Ty) {
1315 const auto *BTy = Ty->getAs<BuiltinType>();
1316 assert(BTy && "Expected a builtin type.")((BTy && "Expected a builtin type.") ? static_cast<
void> (0) : __assert_fail ("BTy && \"Expected a builtin type.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1316, __PRETTY_FUNCTION__))
;
1317
1318 switch (BTy->getKind()) {
1319 case BuiltinType::ShortFract:
1320 case BuiltinType::UShortFract:
1321 case BuiltinType::SatShortFract:
1322 case BuiltinType::SatUShortFract:
1323 return 1;
1324 case BuiltinType::Fract:
1325 case BuiltinType::UFract:
1326 case BuiltinType::SatFract:
1327 case BuiltinType::SatUFract:
1328 return 2;
1329 case BuiltinType::LongFract:
1330 case BuiltinType::ULongFract:
1331 case BuiltinType::SatLongFract:
1332 case BuiltinType::SatULongFract:
1333 return 3;
1334 case BuiltinType::ShortAccum:
1335 case BuiltinType::UShortAccum:
1336 case BuiltinType::SatShortAccum:
1337 case BuiltinType::SatUShortAccum:
1338 return 4;
1339 case BuiltinType::Accum:
1340 case BuiltinType::UAccum:
1341 case BuiltinType::SatAccum:
1342 case BuiltinType::SatUAccum:
1343 return 5;
1344 case BuiltinType::LongAccum:
1345 case BuiltinType::ULongAccum:
1346 case BuiltinType::SatLongAccum:
1347 case BuiltinType::SatULongAccum:
1348 return 6;
1349 default:
1350 if (BTy->isInteger())
1351 return 0;
1352 llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1352)
;
1353 }
1354}
1355
1356/// handleFixedPointConversion - Fixed point operations between fixed
1357/// point types and integers or other fixed point types do not fall under
1358/// usual arithmetic conversion since these conversions could result in loss
1359/// of precsision (N1169 4.1.4). These operations should be calculated with
1360/// the full precision of their result type (N1169 4.1.6.2.1).
1361static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1362 QualType RHSTy) {
1363 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType
()) && "Expected at least one of the operands to be a fixed point type"
) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1364, __PRETTY_FUNCTION__))
1364 "Expected at least one of the operands to be a fixed point type")(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType
()) && "Expected at least one of the operands to be a fixed point type"
) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1364, __PRETTY_FUNCTION__))
;
1365 assert((LHSTy->isFixedPointOrIntegerType() ||(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1368, __PRETTY_FUNCTION__))
1366 RHSTy->isFixedPointOrIntegerType()) &&(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1368, __PRETTY_FUNCTION__))
1367 "Special fixed point arithmetic operation conversions are only "(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1368, __PRETTY_FUNCTION__))
1368 "applied to ints or other fixed point types")(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1368, __PRETTY_FUNCTION__))
;
1369
1370 // If one operand has signed fixed-point type and the other operand has
1371 // unsigned fixed-point type, then the unsigned fixed-point operand is
1372 // converted to its corresponding signed fixed-point type and the resulting
1373 // type is the type of the converted operand.
1374 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1375 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1376 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1377 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1378
1379 // The result type is the type with the highest rank, whereby a fixed-point
1380 // conversion rank is always greater than an integer conversion rank; if the
1381 // type of either of the operands is a saturating fixedpoint type, the result
1382 // type shall be the saturating fixed-point type corresponding to the type
1383 // with the highest rank; the resulting value is converted (taking into
1384 // account rounding and overflow) to the precision of the resulting type.
1385 // Same ranks between signed and unsigned types are resolved earlier, so both
1386 // types are either signed or both unsigned at this point.
1387 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1388 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1389
1390 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1391
1392 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1393 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1394
1395 return ResultTy;
1396}
1397
1398/// Check that the usual arithmetic conversions can be performed on this pair of
1399/// expressions that might be of enumeration type.
1400static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1401 SourceLocation Loc,
1402 Sema::ArithConvKind ACK) {
1403 // C++2a [expr.arith.conv]p1:
1404 // If one operand is of enumeration type and the other operand is of a
1405 // different enumeration type or a floating-point type, this behavior is
1406 // deprecated ([depr.arith.conv.enum]).
1407 //
1408 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1409 // Eventually we will presumably reject these cases (in C++23 onwards?).
1410 QualType L = LHS->getType(), R = RHS->getType();
1411 bool LEnum = L->isUnscopedEnumerationType(),
1412 REnum = R->isUnscopedEnumerationType();
1413 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1414 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1415 (REnum && L->isFloatingType())) {
1416 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1417 ? diag::warn_arith_conv_enum_float_cxx20
1418 : diag::warn_arith_conv_enum_float)
1419 << LHS->getSourceRange() << RHS->getSourceRange()
1420 << (int)ACK << LEnum << L << R;
1421 } else if (!IsCompAssign && LEnum && REnum &&
1422 !S.Context.hasSameUnqualifiedType(L, R)) {
1423 unsigned DiagID;
1424 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1425 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1426 // If either enumeration type is unnamed, it's less likely that the
1427 // user cares about this, but this situation is still deprecated in
1428 // C++2a. Use a different warning group.
1429 DiagID = S.getLangOpts().CPlusPlus20
1430 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1431 : diag::warn_arith_conv_mixed_anon_enum_types;
1432 } else if (ACK == Sema::ACK_Conditional) {
1433 // Conditional expressions are separated out because they have
1434 // historically had a different warning flag.
1435 DiagID = S.getLangOpts().CPlusPlus20
1436 ? diag::warn_conditional_mixed_enum_types_cxx20
1437 : diag::warn_conditional_mixed_enum_types;
1438 } else if (ACK == Sema::ACK_Comparison) {
1439 // Comparison expressions are separated out because they have
1440 // historically had a different warning flag.
1441 DiagID = S.getLangOpts().CPlusPlus20
1442 ? diag::warn_comparison_mixed_enum_types_cxx20
1443 : diag::warn_comparison_mixed_enum_types;
1444 } else {
1445 DiagID = S.getLangOpts().CPlusPlus20
1446 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1447 : diag::warn_arith_conv_mixed_enum_types;
1448 }
1449 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1450 << (int)ACK << L << R;
1451 }
1452}
1453
1454/// UsualArithmeticConversions - Performs various conversions that are common to
1455/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1456/// routine returns the first non-arithmetic type found. The client is
1457/// responsible for emitting appropriate error diagnostics.
1458QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1459 SourceLocation Loc,
1460 ArithConvKind ACK) {
1461 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1462
1463 if (ACK != ACK_CompAssign) {
1464 LHS = UsualUnaryConversions(LHS.get());
1465 if (LHS.isInvalid())
1466 return QualType();
1467 }
1468
1469 RHS = UsualUnaryConversions(RHS.get());
1470 if (RHS.isInvalid())
1471 return QualType();
1472
1473 // For conversion purposes, we ignore any qualifiers.
1474 // For example, "const float" and "float" are equivalent.
1475 QualType LHSType =
1476 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1477 QualType RHSType =
1478 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1479
1480 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1481 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1482 LHSType = AtomicLHS->getValueType();
1483
1484 // If both types are identical, no conversion is needed.
1485 if (LHSType == RHSType)
1486 return LHSType;
1487
1488 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1489 // The caller can deal with this (e.g. pointer + int).
1490 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1491 return QualType();
1492
1493 // Apply unary and bitfield promotions to the LHS's type.
1494 QualType LHSUnpromotedType = LHSType;
1495 if (LHSType->isPromotableIntegerType())
1496 LHSType = Context.getPromotedIntegerType(LHSType);
1497 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1498 if (!LHSBitfieldPromoteTy.isNull())
1499 LHSType = LHSBitfieldPromoteTy;
1500 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1501 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1502
1503 // If both types are identical, no conversion is needed.
1504 if (LHSType == RHSType)
1505 return LHSType;
1506
1507 // ExtInt types aren't subject to conversions between them or normal integers,
1508 // so this fails.
1509 if(LHSType->isExtIntType() || RHSType->isExtIntType())
1510 return QualType();
1511
1512 // At this point, we have two different arithmetic types.
1513
1514 // Diagnose attempts to convert between __float128 and long double where
1515 // such conversions currently can't be handled.
1516 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1517 return QualType();
1518
1519 // Handle complex types first (C99 6.3.1.8p1).
1520 if (LHSType->isComplexType() || RHSType->isComplexType())
1521 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1522 ACK == ACK_CompAssign);
1523
1524 // Now handle "real" floating types (i.e. float, double, long double).
1525 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1526 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1527 ACK == ACK_CompAssign);
1528
1529 // Handle GCC complex int extension.
1530 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1531 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1532 ACK == ACK_CompAssign);
1533
1534 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1535 return handleFixedPointConversion(*this, LHSType, RHSType);
1536
1537 // Finally, we have two differing integer types.
1538 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1539 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1540}
1541
1542//===----------------------------------------------------------------------===//
1543// Semantic Analysis for various Expression Types
1544//===----------------------------------------------------------------------===//
1545
1546
1547ExprResult
1548Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1549 SourceLocation DefaultLoc,
1550 SourceLocation RParenLoc,
1551 Expr *ControllingExpr,
1552 ArrayRef<ParsedType> ArgTypes,
1553 ArrayRef<Expr *> ArgExprs) {
1554 unsigned NumAssocs = ArgTypes.size();
1555 assert(NumAssocs == ArgExprs.size())((NumAssocs == ArgExprs.size()) ? static_cast<void> (0)
: __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1555, __PRETTY_FUNCTION__))
;
1556
1557 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1558 for (unsigned i = 0; i < NumAssocs; ++i) {
1559 if (ArgTypes[i])
1560 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1561 else
1562 Types[i] = nullptr;
1563 }
1564
1565 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1566 ControllingExpr,
1567 llvm::makeArrayRef(Types, NumAssocs),
1568 ArgExprs);
1569 delete [] Types;
1570 return ER;
1571}
1572
1573ExprResult
1574Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1575 SourceLocation DefaultLoc,
1576 SourceLocation RParenLoc,
1577 Expr *ControllingExpr,
1578 ArrayRef<TypeSourceInfo *> Types,
1579 ArrayRef<Expr *> Exprs) {
1580 unsigned NumAssocs = Types.size();
1581 assert(NumAssocs == Exprs.size())((NumAssocs == Exprs.size()) ? static_cast<void> (0) : __assert_fail
("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1581, __PRETTY_FUNCTION__))
;
1582
1583 // Decay and strip qualifiers for the controlling expression type, and handle
1584 // placeholder type replacement. See committee discussion from WG14 DR423.
1585 {
1586 EnterExpressionEvaluationContext Unevaluated(
1587 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1588 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1589 if (R.isInvalid())
1590 return ExprError();
1591 ControllingExpr = R.get();
1592 }
1593
1594 // The controlling expression is an unevaluated operand, so side effects are
1595 // likely unintended.
1596 if (!inTemplateInstantiation() &&
1597 ControllingExpr->HasSideEffects(Context, false))
1598 Diag(ControllingExpr->getExprLoc(),
1599 diag::warn_side_effects_unevaluated_context);
1600
1601 bool TypeErrorFound = false,
1602 IsResultDependent = ControllingExpr->isTypeDependent(),
1603 ContainsUnexpandedParameterPack
1604 = ControllingExpr->containsUnexpandedParameterPack();
1605
1606 for (unsigned i = 0; i < NumAssocs; ++i) {
1607 if (Exprs[i]->containsUnexpandedParameterPack())
1608 ContainsUnexpandedParameterPack = true;
1609
1610 if (Types[i]) {
1611 if (Types[i]->getType()->containsUnexpandedParameterPack())
1612 ContainsUnexpandedParameterPack = true;
1613
1614 if (Types[i]->getType()->isDependentType()) {
1615 IsResultDependent = true;
1616 } else {
1617 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1618 // complete object type other than a variably modified type."
1619 unsigned D = 0;
1620 if (Types[i]->getType()->isIncompleteType())
1621 D = diag::err_assoc_type_incomplete;
1622 else if (!Types[i]->getType()->isObjectType())
1623 D = diag::err_assoc_type_nonobject;
1624 else if (Types[i]->getType()->isVariablyModifiedType())
1625 D = diag::err_assoc_type_variably_modified;
1626
1627 if (D != 0) {
1628 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1629 << Types[i]->getTypeLoc().getSourceRange()
1630 << Types[i]->getType();
1631 TypeErrorFound = true;
1632 }
1633
1634 // C11 6.5.1.1p2 "No two generic associations in the same generic
1635 // selection shall specify compatible types."
1636 for (unsigned j = i+1; j < NumAssocs; ++j)
1637 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1638 Context.typesAreCompatible(Types[i]->getType(),
1639 Types[j]->getType())) {
1640 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1641 diag::err_assoc_compatible_types)
1642 << Types[j]->getTypeLoc().getSourceRange()
1643 << Types[j]->getType()
1644 << Types[i]->getType();
1645 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1646 diag::note_compat_assoc)
1647 << Types[i]->getTypeLoc().getSourceRange()
1648 << Types[i]->getType();
1649 TypeErrorFound = true;
1650 }
1651 }
1652 }
1653 }
1654 if (TypeErrorFound)
1655 return ExprError();
1656
1657 // If we determined that the generic selection is result-dependent, don't
1658 // try to compute the result expression.
1659 if (IsResultDependent)
1660 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1661 Exprs, DefaultLoc, RParenLoc,
1662 ContainsUnexpandedParameterPack);
1663
1664 SmallVector<unsigned, 1> CompatIndices;
1665 unsigned DefaultIndex = -1U;
1666 for (unsigned i = 0; i < NumAssocs; ++i) {
1667 if (!Types[i])
1668 DefaultIndex = i;
1669 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1670 Types[i]->getType()))
1671 CompatIndices.push_back(i);
1672 }
1673
1674 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1675 // type compatible with at most one of the types named in its generic
1676 // association list."
1677 if (CompatIndices.size() > 1) {
1678 // We strip parens here because the controlling expression is typically
1679 // parenthesized in macro definitions.
1680 ControllingExpr = ControllingExpr->IgnoreParens();
1681 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1682 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1683 << (unsigned)CompatIndices.size();
1684 for (unsigned I : CompatIndices) {
1685 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1686 diag::note_compat_assoc)
1687 << Types[I]->getTypeLoc().getSourceRange()
1688 << Types[I]->getType();
1689 }
1690 return ExprError();
1691 }
1692
1693 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1694 // its controlling expression shall have type compatible with exactly one of
1695 // the types named in its generic association list."
1696 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1697 // We strip parens here because the controlling expression is typically
1698 // parenthesized in macro definitions.
1699 ControllingExpr = ControllingExpr->IgnoreParens();
1700 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1701 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1702 return ExprError();
1703 }
1704
1705 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1706 // type name that is compatible with the type of the controlling expression,
1707 // then the result expression of the generic selection is the expression
1708 // in that generic association. Otherwise, the result expression of the
1709 // generic selection is the expression in the default generic association."
1710 unsigned ResultIndex =
1711 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1712
1713 return GenericSelectionExpr::Create(
1714 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1715 ContainsUnexpandedParameterPack, ResultIndex);
1716}
1717
1718/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1719/// location of the token and the offset of the ud-suffix within it.
1720static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1721 unsigned Offset) {
1722 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1723 S.getLangOpts());
1724}
1725
1726/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1727/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1728static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1729 IdentifierInfo *UDSuffix,
1730 SourceLocation UDSuffixLoc,
1731 ArrayRef<Expr*> Args,
1732 SourceLocation LitEndLoc) {
1733 assert(Args.size() <= 2 && "too many arguments for literal operator")((Args.size() <= 2 && "too many arguments for literal operator"
) ? static_cast<void> (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1733, __PRETTY_FUNCTION__))
;
1734
1735 QualType ArgTy[2];
1736 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1737 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1738 if (ArgTy[ArgIdx]->isArrayType())
1739 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1740 }
1741
1742 DeclarationName OpName =
1743 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1744 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1745 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1746
1747 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1748 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1749 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1750 /*AllowStringTemplate*/ false,
1751 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1752 return ExprError();
1753
1754 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1755}
1756
1757/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1758/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1759/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1760/// multiple tokens. However, the common case is that StringToks points to one
1761/// string.
1762///
1763ExprResult
1764Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1765 assert(!StringToks.empty() && "Must have at least one string!")((!StringToks.empty() && "Must have at least one string!"
) ? static_cast<void> (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1765, __PRETTY_FUNCTION__))
;
1766
1767 StringLiteralParser Literal(StringToks, PP);
1768 if (Literal.hadError)
1769 return ExprError();
1770
1771 SmallVector<SourceLocation, 4> StringTokLocs;
1772 for (const Token &Tok : StringToks)
1773 StringTokLocs.push_back(Tok.getLocation());
1774
1775 QualType CharTy = Context.CharTy;
1776 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1777 if (Literal.isWide()) {
1778 CharTy = Context.getWideCharType();
1779 Kind = StringLiteral::Wide;
1780 } else if (Literal.isUTF8()) {
1781 if (getLangOpts().Char8)
1782 CharTy = Context.Char8Ty;
1783 Kind = StringLiteral::UTF8;
1784 } else if (Literal.isUTF16()) {
1785 CharTy = Context.Char16Ty;
1786 Kind = StringLiteral::UTF16;
1787 } else if (Literal.isUTF32()) {
1788 CharTy = Context.Char32Ty;
1789 Kind = StringLiteral::UTF32;
1790 } else if (Literal.isPascal()) {
1791 CharTy = Context.UnsignedCharTy;
1792 }
1793
1794 // Warn on initializing an array of char from a u8 string literal; this
1795 // becomes ill-formed in C++2a.
1796 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1797 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1798 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1799
1800 // Create removals for all 'u8' prefixes in the string literal(s). This
1801 // ensures C++2a compatibility (but may change the program behavior when
1802 // built by non-Clang compilers for which the execution character set is
1803 // not always UTF-8).
1804 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1805 SourceLocation RemovalDiagLoc;
1806 for (const Token &Tok : StringToks) {
1807 if (Tok.getKind() == tok::utf8_string_literal) {
1808 if (RemovalDiagLoc.isInvalid())
1809 RemovalDiagLoc = Tok.getLocation();
1810 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1811 Tok.getLocation(),
1812 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1813 getSourceManager(), getLangOpts())));
1814 }
1815 }
1816 Diag(RemovalDiagLoc, RemovalDiag);
1817 }
1818
1819 QualType StrTy =
1820 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1821
1822 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1823 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1824 Kind, Literal.Pascal, StrTy,
1825 &StringTokLocs[0],
1826 StringTokLocs.size());
1827 if (Literal.getUDSuffix().empty())
1828 return Lit;
1829
1830 // We're building a user-defined literal.
1831 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1832 SourceLocation UDSuffixLoc =
1833 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1834 Literal.getUDSuffixOffset());
1835
1836 // Make sure we're allowed user-defined literals here.
1837 if (!UDLScope)
1838 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1839
1840 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1841 // operator "" X (str, len)
1842 QualType SizeType = Context.getSizeType();
1843
1844 DeclarationName OpName =
1845 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1846 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1847 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1848
1849 QualType ArgTy[] = {
1850 Context.getArrayDecayedType(StrTy), SizeType
1851 };
1852
1853 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1854 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1855 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1856 /*AllowStringTemplate*/ true,
1857 /*DiagnoseMissing*/ true)) {
1858
1859 case LOLR_Cooked: {
1860 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1861 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1862 StringTokLocs[0]);
1863 Expr *Args[] = { Lit, LenArg };
1864
1865 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1866 }
1867
1868 case LOLR_StringTemplate: {
1869 TemplateArgumentListInfo ExplicitArgs;
1870
1871 unsigned CharBits = Context.getIntWidth(CharTy);
1872 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1873 llvm::APSInt Value(CharBits, CharIsUnsigned);
1874
1875 TemplateArgument TypeArg(CharTy);
1876 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1877 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1878
1879 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1880 Value = Lit->getCodeUnit(I);
1881 TemplateArgument Arg(Context, Value, CharTy);
1882 TemplateArgumentLocInfo ArgInfo;
1883 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1884 }
1885 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1886 &ExplicitArgs);
1887 }
1888 case LOLR_Raw:
1889 case LOLR_Template:
1890 case LOLR_ErrorNoDiagnostic:
1891 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1891)
;
1892 case LOLR_Error:
1893 return ExprError();
1894 }
1895 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1895)
;
1896}
1897
1898DeclRefExpr *
1899Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1900 SourceLocation Loc,
1901 const CXXScopeSpec *SS) {
1902 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1903 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1904}
1905
1906DeclRefExpr *
1907Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1908 const DeclarationNameInfo &NameInfo,
1909 const CXXScopeSpec *SS, NamedDecl *FoundD,
1910 SourceLocation TemplateKWLoc,
1911 const TemplateArgumentListInfo *TemplateArgs) {
1912 NestedNameSpecifierLoc NNS =
1913 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1914 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1915 TemplateArgs);
1916}
1917
1918NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1919 // A declaration named in an unevaluated operand never constitutes an odr-use.
1920 if (isUnevaluatedContext())
1921 return NOUR_Unevaluated;
1922
1923 // C++2a [basic.def.odr]p4:
1924 // A variable x whose name appears as a potentially-evaluated expression e
1925 // is odr-used by e unless [...] x is a reference that is usable in
1926 // constant expressions.
1927 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1928 if (VD->getType()->isReferenceType() &&
1929 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1930 VD->isUsableInConstantExpressions(Context))
1931 return NOUR_Constant;
1932 }
1933
1934 // All remaining non-variable cases constitute an odr-use. For variables, we
1935 // need to wait and see how the expression is used.
1936 return NOUR_None;
1937}
1938
1939/// BuildDeclRefExpr - Build an expression that references a
1940/// declaration that does not require a closure capture.
1941DeclRefExpr *
1942Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1943 const DeclarationNameInfo &NameInfo,
1944 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1945 SourceLocation TemplateKWLoc,
1946 const TemplateArgumentListInfo *TemplateArgs) {
1947 bool RefersToCapturedVariable =
1948 isa<VarDecl>(D) &&
1949 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1950
1951 DeclRefExpr *E = DeclRefExpr::Create(
1952 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1953 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1954 MarkDeclRefReferenced(E);
1955
1956 // C++ [except.spec]p17:
1957 // An exception-specification is considered to be needed when:
1958 // - in an expression, the function is the unique lookup result or
1959 // the selected member of a set of overloaded functions.
1960 //
1961 // We delay doing this until after we've built the function reference and
1962 // marked it as used so that:
1963 // a) if the function is defaulted, we get errors from defining it before /
1964 // instead of errors from computing its exception specification, and
1965 // b) if the function is a defaulted comparison, we can use the body we
1966 // build when defining it as input to the exception specification
1967 // computation rather than computing a new body.
1968 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1969 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1970 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1971 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1972 }
1973 }
1974
1975 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1976 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1977 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1978 getCurFunction()->recordUseOfWeak(E);
1979
1980 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1981 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1982 FD = IFD->getAnonField();
1983 if (FD) {
1984 UnusedPrivateFields.remove(FD);
1985 // Just in case we're building an illegal pointer-to-member.
1986 if (FD->isBitField())
1987 E->setObjectKind(OK_BitField);
1988 }
1989
1990 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1991 // designates a bit-field.
1992 if (auto *BD = dyn_cast<BindingDecl>(D))
1993 if (auto *BE = BD->getBinding())
1994 E->setObjectKind(BE->getObjectKind());
1995
1996 return E;
1997}
1998
1999/// Decomposes the given name into a DeclarationNameInfo, its location, and
2000/// possibly a list of template arguments.
2001///
2002/// If this produces template arguments, it is permitted to call
2003/// DecomposeTemplateName.
2004///
2005/// This actually loses a lot of source location information for
2006/// non-standard name kinds; we should consider preserving that in
2007/// some way.
2008void
2009Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2010 TemplateArgumentListInfo &Buffer,
2011 DeclarationNameInfo &NameInfo,
2012 const TemplateArgumentListInfo *&TemplateArgs) {
2013 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2014 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2015 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2016
2017 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2018 Id.TemplateId->NumArgs);
2019 translateTemplateArguments(TemplateArgsPtr, Buffer);
2020
2021 TemplateName TName = Id.TemplateId->Template.get();
2022 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2023 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2024 TemplateArgs = &Buffer;
2025 } else {
2026 NameInfo = GetNameFromUnqualifiedId(Id);
2027 TemplateArgs = nullptr;
2028 }
2029}
2030
2031static void emitEmptyLookupTypoDiagnostic(
2032 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2033 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2034 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2035 DeclContext *Ctx =
2036 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2037 if (!TC) {
2038 // Emit a special diagnostic for failed member lookups.
2039 // FIXME: computing the declaration context might fail here (?)
2040 if (Ctx)
2041 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2042 << SS.getRange();
2043 else
2044 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2045 return;
2046 }
2047
2048 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2049 bool DroppedSpecifier =
2050 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2051 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2052 ? diag::note_implicit_param_decl
2053 : diag::note_previous_decl;
2054 if (!Ctx)
2055 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2056 SemaRef.PDiag(NoteID));
2057 else
2058 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2059 << Typo << Ctx << DroppedSpecifier
2060 << SS.getRange(),
2061 SemaRef.PDiag(NoteID));
2062}
2063
2064/// Diagnose an empty lookup.
2065///
2066/// \return false if new lookup candidates were found
2067bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2068 CorrectionCandidateCallback &CCC,
2069 TemplateArgumentListInfo *ExplicitTemplateArgs,
2070 ArrayRef<Expr *> Args, TypoExpr **Out) {
2071 DeclarationName Name = R.getLookupName();
2072
2073 unsigned diagnostic = diag::err_undeclared_var_use;
2074 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2075 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2076 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2077 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2078 diagnostic = diag::err_undeclared_use;
2079 diagnostic_suggest = diag::err_undeclared_use_suggest;
2080 }
2081
2082 // If the original lookup was an unqualified lookup, fake an
2083 // unqualified lookup. This is useful when (for example) the
2084 // original lookup would not have found something because it was a
2085 // dependent name.
2086 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2087 while (DC) {
2088 if (isa<CXXRecordDecl>(DC)) {
2089 LookupQualifiedName(R, DC);
2090
2091 if (!R.empty()) {
2092 // Don't give errors about ambiguities in this lookup.
2093 R.suppressDiagnostics();
2094
2095 // During a default argument instantiation the CurContext points
2096 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2097 // function parameter list, hence add an explicit check.
2098 bool isDefaultArgument =
2099 !CodeSynthesisContexts.empty() &&
2100 CodeSynthesisContexts.back().Kind ==
2101 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2102 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2103 bool isInstance = CurMethod &&
2104 CurMethod->isInstance() &&
2105 DC == CurMethod->getParent() && !isDefaultArgument;
2106
2107 // Give a code modification hint to insert 'this->'.
2108 // TODO: fixit for inserting 'Base<T>::' in the other cases.
2109 // Actually quite difficult!
2110 if (getLangOpts().MSVCCompat)
2111 diagnostic = diag::ext_found_via_dependent_bases_lookup;
2112 if (isInstance) {
2113 Diag(R.getNameLoc(), diagnostic) << Name
2114 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2115 CheckCXXThisCapture(R.getNameLoc());
2116 } else {
2117 Diag(R.getNameLoc(), diagnostic) << Name;
2118 }
2119
2120 // Do we really want to note all of these?
2121 for (NamedDecl *D : R)
2122 Diag(D->getLocation(), diag::note_dependent_var_use);
2123
2124 // Return true if we are inside a default argument instantiation
2125 // and the found name refers to an instance member function, otherwise
2126 // the function calling DiagnoseEmptyLookup will try to create an
2127 // implicit member call and this is wrong for default argument.
2128 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2129 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2130 return true;
2131 }
2132
2133 // Tell the callee to try to recover.
2134 return false;
2135 }
2136
2137 R.clear();
2138 }
2139
2140 DC = DC->getLookupParent();
2141 }
2142
2143 // We didn't find anything, so try to correct for a typo.
2144 TypoCorrection Corrected;
2145 if (S && Out) {
2146 SourceLocation TypoLoc = R.getNameLoc();
2147 assert(!ExplicitTemplateArgs &&((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2148, __PRETTY_FUNCTION__))
2148 "Diagnosing an empty lookup with explicit template args!")((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2148, __PRETTY_FUNCTION__))
;
2149 *Out = CorrectTypoDelayed(
2150 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2151 [=](const TypoCorrection &TC) {
2152 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2153 diagnostic, diagnostic_suggest);
2154 },
2155 nullptr, CTK_ErrorRecovery);
2156 if (*Out)
2157 return true;
2158 } else if (S &&
2159 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2160 S, &SS, CCC, CTK_ErrorRecovery))) {
2161 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2162 bool DroppedSpecifier =
2163 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2164 R.setLookupName(Corrected.getCorrection());
2165
2166 bool AcceptableWithRecovery = false;
2167 bool AcceptableWithoutRecovery = false;
2168 NamedDecl *ND = Corrected.getFoundDecl();
2169 if (ND) {
2170 if (Corrected.isOverloaded()) {
2171 OverloadCandidateSet OCS(R.getNameLoc(),
2172 OverloadCandidateSet::CSK_Normal);
2173 OverloadCandidateSet::iterator Best;
2174 for (NamedDecl *CD : Corrected) {
2175 if (FunctionTemplateDecl *FTD =
2176 dyn_cast<FunctionTemplateDecl>(CD))
2177 AddTemplateOverloadCandidate(
2178 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2179 Args, OCS);
2180 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2181 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2182 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2183 Args, OCS);
2184 }
2185 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2186 case OR_Success:
2187 ND = Best->FoundDecl;
2188 Corrected.setCorrectionDecl(ND);
2189 break;
2190 default:
2191 // FIXME: Arbitrarily pick the first declaration for the note.
2192 Corrected.setCorrectionDecl(ND);
2193 break;
2194 }
2195 }
2196 R.addDecl(ND);
2197 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2198 CXXRecordDecl *Record = nullptr;
2199 if (Corrected.getCorrectionSpecifier()) {
2200 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2201 Record = Ty->getAsCXXRecordDecl();
2202 }
2203 if (!Record)
2204 Record = cast<CXXRecordDecl>(
2205 ND->getDeclContext()->getRedeclContext());
2206 R.setNamingClass(Record);
2207 }
2208
2209 auto *UnderlyingND = ND->getUnderlyingDecl();
2210 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2211 isa<FunctionTemplateDecl>(UnderlyingND);
2212 // FIXME: If we ended up with a typo for a type name or
2213 // Objective-C class name, we're in trouble because the parser
2214 // is in the wrong place to recover. Suggest the typo
2215 // correction, but don't make it a fix-it since we're not going
2216 // to recover well anyway.
2217 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2218 getAsTypeTemplateDecl(UnderlyingND) ||
2219 isa<ObjCInterfaceDecl>(UnderlyingND);
2220 } else {
2221 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2222 // because we aren't able to recover.
2223 AcceptableWithoutRecovery = true;
2224 }
2225
2226 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2227 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2228 ? diag::note_implicit_param_decl
2229 : diag::note_previous_decl;
2230 if (SS.isEmpty())
2231 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2232 PDiag(NoteID), AcceptableWithRecovery);
2233 else
2234 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2235 << Name << computeDeclContext(SS, false)
2236 << DroppedSpecifier << SS.getRange(),
2237 PDiag(NoteID), AcceptableWithRecovery);
2238
2239 // Tell the callee whether to try to recover.
2240 return !AcceptableWithRecovery;
2241 }
2242 }
2243 R.clear();
2244
2245 // Emit a special diagnostic for failed member lookups.
2246 // FIXME: computing the declaration context might fail here (?)
2247 if (!SS.isEmpty()) {
2248 Diag(R.getNameLoc(), diag::err_no_member)
2249 << Name << computeDeclContext(SS, false)
2250 << SS.getRange();
2251 return true;
2252 }
2253
2254 // Give up, we can't recover.
2255 Diag(R.getNameLoc(), diagnostic) << Name;
2256 return true;
2257}
2258
2259/// In Microsoft mode, if we are inside a template class whose parent class has
2260/// dependent base classes, and we can't resolve an unqualified identifier, then
2261/// assume the identifier is a member of a dependent base class. We can only
2262/// recover successfully in static methods, instance methods, and other contexts
2263/// where 'this' is available. This doesn't precisely match MSVC's
2264/// instantiation model, but it's close enough.
2265static Expr *
2266recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2267 DeclarationNameInfo &NameInfo,
2268 SourceLocation TemplateKWLoc,
2269 const TemplateArgumentListInfo *TemplateArgs) {
2270 // Only try to recover from lookup into dependent bases in static methods or
2271 // contexts where 'this' is available.
2272 QualType ThisType = S.getCurrentThisType();
2273 const CXXRecordDecl *RD = nullptr;
2274 if (!ThisType.isNull())
2275 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2276 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2277 RD = MD->getParent();
2278 if (!RD || !RD->hasAnyDependentBases())
2279 return nullptr;
2280
2281 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2282 // is available, suggest inserting 'this->' as a fixit.
2283 SourceLocation Loc = NameInfo.getLoc();
2284 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2285 DB << NameInfo.getName() << RD;
2286
2287 if (!ThisType.isNull()) {
2288 DB << FixItHint::CreateInsertion(Loc, "this->");
2289 return CXXDependentScopeMemberExpr::Create(
2290 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2291 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2292 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2293 }
2294
2295 // Synthesize a fake NNS that points to the derived class. This will
2296 // perform name lookup during template instantiation.
2297 CXXScopeSpec SS;
2298 auto *NNS =
2299 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2300 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2301 return DependentScopeDeclRefExpr::Create(
2302 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2303 TemplateArgs);
2304}
2305
2306ExprResult
2307Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2308 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2309 bool HasTrailingLParen, bool IsAddressOfOperand,
2310 CorrectionCandidateCallback *CCC,
2311 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2312 assert(!(IsAddressOfOperand && HasTrailingLParen) &&((!(IsAddressOfOperand && HasTrailingLParen) &&
"cannot be direct & operand and have a trailing lparen")
? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2313, __PRETTY_FUNCTION__))
2313 "cannot be direct & operand and have a trailing lparen")((!(IsAddressOfOperand && HasTrailingLParen) &&
"cannot be direct & operand and have a trailing lparen")
? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2313, __PRETTY_FUNCTION__))
;
2314 if (SS.isInvalid())
2315 return ExprError();
2316
2317 TemplateArgumentListInfo TemplateArgsBuffer;
2318
2319 // Decompose the UnqualifiedId into the following data.
2320 DeclarationNameInfo NameInfo;
2321 const TemplateArgumentListInfo *TemplateArgs;
2322 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2323
2324 DeclarationName Name = NameInfo.getName();
2325 IdentifierInfo *II = Name.getAsIdentifierInfo();
2326 SourceLocation NameLoc = NameInfo.getLoc();
2327
2328 if (II && II->isEditorPlaceholder()) {
2329 // FIXME: When typed placeholders are supported we can create a typed
2330 // placeholder expression node.
2331 return ExprError();
2332 }
2333
2334 // C++ [temp.dep.expr]p3:
2335 // An id-expression is type-dependent if it contains:
2336 // -- an identifier that was declared with a dependent type,
2337 // (note: handled after lookup)
2338 // -- a template-id that is dependent,
2339 // (note: handled in BuildTemplateIdExpr)
2340 // -- a conversion-function-id that specifies a dependent type,
2341 // -- a nested-name-specifier that contains a class-name that
2342 // names a dependent type.
2343 // Determine whether this is a member of an unknown specialization;
2344 // we need to handle these differently.
2345 bool DependentID = false;
2346 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2347 Name.getCXXNameType()->isDependentType()) {
2348 DependentID = true;
2349 } else if (SS.isSet()) {
2350 if (DeclContext *DC = computeDeclContext(SS, false)) {
2351 if (RequireCompleteDeclContext(SS, DC))
2352 return ExprError();
2353 } else {
2354 DependentID = true;
2355 }
2356 }
2357
2358 if (DependentID)
2359 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2360 IsAddressOfOperand, TemplateArgs);
2361
2362 // Perform the required lookup.
2363 LookupResult R(*this, NameInfo,
2364 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2365 ? LookupObjCImplicitSelfParam
2366 : LookupOrdinaryName);
2367 if (TemplateKWLoc.isValid() || TemplateArgs) {
2368 // Lookup the template name again to correctly establish the context in
2369 // which it was found. This is really unfortunate as we already did the
2370 // lookup to determine that it was a template name in the first place. If
2371 // this becomes a performance hit, we can work harder to preserve those
2372 // results until we get here but it's likely not worth it.
2373 bool MemberOfUnknownSpecialization;
2374 AssumedTemplateKind AssumedTemplate;
2375 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2376 MemberOfUnknownSpecialization, TemplateKWLoc,
2377 &AssumedTemplate))
2378 return ExprError();
2379
2380 if (MemberOfUnknownSpecialization ||
2381 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2382 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2383 IsAddressOfOperand, TemplateArgs);
2384 } else {
2385 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2386 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2387
2388 // If the result might be in a dependent base class, this is a dependent
2389 // id-expression.
2390 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2391 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2392 IsAddressOfOperand, TemplateArgs);
2393
2394 // If this reference is in an Objective-C method, then we need to do
2395 // some special Objective-C lookup, too.
2396 if (IvarLookupFollowUp) {
2397 ExprResult E(LookupInObjCMethod(R, S, II, true));
2398 if (E.isInvalid())
2399 return ExprError();
2400
2401 if (Expr *Ex = E.getAs<Expr>())
2402 return Ex;
2403 }
2404 }
2405
2406 if (R.isAmbiguous())
2407 return ExprError();
2408
2409 // This could be an implicitly declared function reference (legal in C90,
2410 // extension in C99, forbidden in C++).
2411 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2412 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2413 if (D) R.addDecl(D);
2414 }
2415
2416 // Determine whether this name might be a candidate for
2417 // argument-dependent lookup.
2418 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2419
2420 if (R.empty() && !ADL) {
2421 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2422 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2423 TemplateKWLoc, TemplateArgs))
2424 return E;
2425 }
2426
2427 // Don't diagnose an empty lookup for inline assembly.
2428 if (IsInlineAsmIdentifier)
2429 return ExprError();
2430
2431 // If this name wasn't predeclared and if this is not a function
2432 // call, diagnose the problem.
2433 TypoExpr *TE = nullptr;
2434 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2435 : nullptr);
2436 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2437 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
"Typo correction callback misconfigured") ? static_cast<void
> (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2438, __PRETTY_FUNCTION__))
2438 "Typo correction callback misconfigured")(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
"Typo correction callback misconfigured") ? static_cast<void
> (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2438, __PRETTY_FUNCTION__))
;
2439 if (CCC) {
2440 // Make sure the callback knows what the typo being diagnosed is.
2441 CCC->setTypoName(II);
2442 if (SS.isValid())
2443 CCC->setTypoNNS(SS.getScopeRep());
2444 }
2445 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2446 // a template name, but we happen to have always already looked up the name
2447 // before we get here if it must be a template name.
2448 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2449 None, &TE)) {
2450 if (TE && KeywordReplacement) {
2451 auto &State = getTypoExprState(TE);
2452 auto BestTC = State.Consumer->getNextCorrection();
2453 if (BestTC.isKeyword()) {
2454 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2455 if (State.DiagHandler)
2456 State.DiagHandler(BestTC);
2457 KeywordReplacement->startToken();
2458 KeywordReplacement->setKind(II->getTokenID());
2459 KeywordReplacement->setIdentifierInfo(II);
2460 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2461 // Clean up the state associated with the TypoExpr, since it has
2462 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2463 clearDelayedTypo(TE);
2464 // Signal that a correction to a keyword was performed by returning a
2465 // valid-but-null ExprResult.
2466 return (Expr*)nullptr;
2467 }
2468 State.Consumer->resetCorrectionStream();
2469 }
2470 return TE ? TE : ExprError();
2471 }
2472
2473 assert(!R.empty() &&((!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2474, __PRETTY_FUNCTION__))
2474 "DiagnoseEmptyLookup returned false but added no results")((!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2474, __PRETTY_FUNCTION__))
;
2475
2476 // If we found an Objective-C instance variable, let
2477 // LookupInObjCMethod build the appropriate expression to
2478 // reference the ivar.
2479 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2480 R.clear();
2481 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2482 // In a hopelessly buggy code, Objective-C instance variable
2483 // lookup fails and no expression will be built to reference it.
2484 if (!E.isInvalid() && !E.get())
2485 return ExprError();
2486 return E;
2487 }
2488 }
2489
2490 // This is guaranteed from this point on.
2491 assert(!R.empty() || ADL)((!R.empty() || ADL) ? static_cast<void> (0) : __assert_fail
("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2491, __PRETTY_FUNCTION__))
;
2492
2493 // Check whether this might be a C++ implicit instance member access.
2494 // C++ [class.mfct.non-static]p3:
2495 // When an id-expression that is not part of a class member access
2496 // syntax and not used to form a pointer to member is used in the
2497 // body of a non-static member function of class X, if name lookup
2498 // resolves the name in the id-expression to a non-static non-type
2499 // member of some class C, the id-expression is transformed into a
2500 // class member access expression using (*this) as the
2501 // postfix-expression to the left of the . operator.
2502 //
2503 // But we don't actually need to do this for '&' operands if R
2504 // resolved to a function or overloaded function set, because the
2505 // expression is ill-formed if it actually works out to be a
2506 // non-static member function:
2507 //
2508 // C++ [expr.ref]p4:
2509 // Otherwise, if E1.E2 refers to a non-static member function. . .
2510 // [t]he expression can be used only as the left-hand operand of a
2511 // member function call.
2512 //
2513 // There are other safeguards against such uses, but it's important
2514 // to get this right here so that we don't end up making a
2515 // spuriously dependent expression if we're inside a dependent
2516 // instance method.
2517 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2518 bool MightBeImplicitMember;
2519 if (!IsAddressOfOperand)
2520 MightBeImplicitMember = true;
2521 else if (!SS.isEmpty())
2522 MightBeImplicitMember = false;
2523 else if (R.isOverloadedResult())
2524 MightBeImplicitMember = false;
2525 else if (R.isUnresolvableResult())
2526 MightBeImplicitMember = true;
2527 else
2528 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2529 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2530 isa<MSPropertyDecl>(R.getFoundDecl());
2531
2532 if (MightBeImplicitMember)
2533 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2534 R, TemplateArgs, S);
2535 }
2536
2537 if (TemplateArgs || TemplateKWLoc.isValid()) {
2538
2539 // In C++1y, if this is a variable template id, then check it
2540 // in BuildTemplateIdExpr().
2541 // The single lookup result must be a variable template declaration.
2542 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2543 Id.TemplateId->Kind == TNK_Var_template) {
2544 assert(R.getAsSingle<VarTemplateDecl>() &&((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found."
) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2545, __PRETTY_FUNCTION__))
2545 "There should only be one declaration found.")((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found."
) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2545, __PRETTY_FUNCTION__))
;
2546 }
2547
2548 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2549 }
2550
2551 return BuildDeclarationNameExpr(SS, R, ADL);
2552}
2553
2554/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2555/// declaration name, generally during template instantiation.
2556/// There's a large number of things which don't need to be done along
2557/// this path.
2558ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2559 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2560 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2561 DeclContext *DC = computeDeclContext(SS, false);
2562 if (!DC)
2563 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2564 NameInfo, /*TemplateArgs=*/nullptr);
2565
2566 if (RequireCompleteDeclContext(SS, DC))
2567 return ExprError();
2568
2569 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2570 LookupQualifiedName(R, DC);
2571
2572 if (R.isAmbiguous())
2573 return ExprError();
2574
2575 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2576 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2577 NameInfo, /*TemplateArgs=*/nullptr);
2578
2579 if (R.empty()) {
2580 Diag(NameInfo.getLoc(), diag::err_no_member)
2581 << NameInfo.getName() << DC << SS.getRange();
2582 return ExprError();
2583 }
2584
2585 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2586 // Diagnose a missing typename if this resolved unambiguously to a type in
2587 // a dependent context. If we can recover with a type, downgrade this to
2588 // a warning in Microsoft compatibility mode.
2589 unsigned DiagID = diag::err_typename_missing;
2590 if (RecoveryTSI && getLangOpts().MSVCCompat)
2591 DiagID = diag::ext_typename_missing;
2592 SourceLocation Loc = SS.getBeginLoc();
2593 auto D = Diag(Loc, DiagID);
2594 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2595 << SourceRange(Loc, NameInfo.getEndLoc());
2596
2597 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2598 // context.
2599 if (!RecoveryTSI)
2600 return ExprError();
2601
2602 // Only issue the fixit if we're prepared to recover.
2603 D << FixItHint::CreateInsertion(Loc, "typename ");
2604
2605 // Recover by pretending this was an elaborated type.
2606 QualType Ty = Context.getTypeDeclType(TD);
2607 TypeLocBuilder TLB;
2608 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2609
2610 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2611 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2612 QTL.setElaboratedKeywordLoc(SourceLocation());
2613 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2614
2615 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2616
2617 return ExprEmpty();
2618 }
2619
2620 // Defend against this resolving to an implicit member access. We usually
2621 // won't get here if this might be a legitimate a class member (we end up in
2622 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2623 // a pointer-to-member or in an unevaluated context in C++11.
2624 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2625 return BuildPossibleImplicitMemberExpr(SS,
2626 /*TemplateKWLoc=*/SourceLocation(),
2627 R, /*TemplateArgs=*/nullptr, S);
2628
2629 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2630}
2631
2632/// The parser has read a name in, and Sema has detected that we're currently
2633/// inside an ObjC method. Perform some additional checks and determine if we
2634/// should form a reference to an ivar.
2635///
2636/// Ideally, most of this would be done by lookup, but there's
2637/// actually quite a lot of extra work involved.
2638DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2639 IdentifierInfo *II) {
2640 SourceLocation Loc = Lookup.getNameLoc();
2641 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2642
2643 // Check for error condition which is already reported.
2644 if (!CurMethod)
2645 return DeclResult(true);
2646
2647 // There are two cases to handle here. 1) scoped lookup could have failed,
2648 // in which case we should look for an ivar. 2) scoped lookup could have
2649 // found a decl, but that decl is outside the current instance method (i.e.
2650 // a global variable). In these two cases, we do a lookup for an ivar with
2651 // this name, if the lookup sucedes, we replace it our current decl.
2652
2653 // If we're in a class method, we don't normally want to look for
2654 // ivars. But if we don't find anything else, and there's an
2655 // ivar, that's an error.
2656 bool IsClassMethod = CurMethod->isClassMethod();
2657
2658 bool LookForIvars;
2659 if (Lookup.empty())
2660 LookForIvars = true;
2661 else if (IsClassMethod)
2662 LookForIvars = false;
2663 else
2664 LookForIvars = (Lookup.isSingleResult() &&
2665 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2666 ObjCInterfaceDecl *IFace = nullptr;
2667 if (LookForIvars) {
2668 IFace = CurMethod->getClassInterface();
2669 ObjCInterfaceDecl *ClassDeclared;
2670 ObjCIvarDecl *IV = nullptr;
2671 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2672 // Diagnose using an ivar in a class method.
2673 if (IsClassMethod) {
2674 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2675 return DeclResult(true);
2676 }
2677
2678 // Diagnose the use of an ivar outside of the declaring class.
2679 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2680 !declaresSameEntity(ClassDeclared, IFace) &&
2681 !getLangOpts().DebuggerSupport)
2682 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2683
2684 // Success.
2685 return IV;
2686 }
2687 } else if (CurMethod->isInstanceMethod()) {
2688 // We should warn if a local variable hides an ivar.
2689 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2690 ObjCInterfaceDecl *ClassDeclared;
2691 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2692 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2693 declaresSameEntity(IFace, ClassDeclared))
2694 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2695 }
2696 }
2697 } else if (Lookup.isSingleResult() &&
2698 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2699 // If accessing a stand-alone ivar in a class method, this is an error.
2700 if (const ObjCIvarDecl *IV =
2701 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2702 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2703 return DeclResult(true);
2704 }
2705 }
2706
2707 // Didn't encounter an error, didn't find an ivar.
2708 return DeclResult(false);
2709}
2710
2711ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2712 ObjCIvarDecl *IV) {
2713 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2714 assert(CurMethod && CurMethod->isInstanceMethod() &&((CurMethod && CurMethod->isInstanceMethod() &&
"should not reference ivar from this context") ? static_cast
<void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2715, __PRETTY_FUNCTION__))
2715 "should not reference ivar from this context")((CurMethod && CurMethod->isInstanceMethod() &&
"should not reference ivar from this context") ? static_cast
<void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2715, __PRETTY_FUNCTION__))
;
2716
2717 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2718 assert(IFace && "should not reference ivar from this context")((IFace && "should not reference ivar from this context"
) ? static_cast<void> (0) : __assert_fail ("IFace && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2718, __PRETTY_FUNCTION__))
;
2719
2720 // If we're referencing an invalid decl, just return this as a silent
2721 // error node. The error diagnostic was already emitted on the decl.
2722 if (IV->isInvalidDecl())
2723 return ExprError();
2724
2725 // Check if referencing a field with __attribute__((deprecated)).
2726 if (DiagnoseUseOfDecl(IV, Loc))
2727 return ExprError();
2728
2729 // FIXME: This should use a new expr for a direct reference, don't
2730 // turn this into Self->ivar, just return a BareIVarExpr or something.
2731 IdentifierInfo &II = Context.Idents.get("self");
2732 UnqualifiedId SelfName;
2733 SelfName.setIdentifier(&II, SourceLocation());
2734 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2735 CXXScopeSpec SelfScopeSpec;
2736 SourceLocation TemplateKWLoc;
2737 ExprResult SelfExpr =
2738 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2739 /*HasTrailingLParen=*/false,
2740 /*IsAddressOfOperand=*/false);
2741 if (SelfExpr.isInvalid())
2742 return ExprError();
2743
2744 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2745 if (SelfExpr.isInvalid())
2746 return ExprError();
2747
2748 MarkAnyDeclReferenced(Loc, IV, true);
2749
2750 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2751 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2752 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2753 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2754
2755 ObjCIvarRefExpr *Result = new (Context)
2756 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2757 IV->getLocation(), SelfExpr.get(), true, true);
2758
2759 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2760 if (!isUnevaluatedContext() &&
2761 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2762 getCurFunction()->recordUseOfWeak(Result);
2763 }
2764 if (getLangOpts().ObjCAutoRefCount)
2765 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2766 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2767
2768 return Result;
2769}
2770
2771/// The parser has read a name in, and Sema has detected that we're currently
2772/// inside an ObjC method. Perform some additional checks and determine if we
2773/// should form a reference to an ivar. If so, build an expression referencing
2774/// that ivar.
2775ExprResult
2776Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2777 IdentifierInfo *II, bool AllowBuiltinCreation) {
2778 // FIXME: Integrate this lookup step into LookupParsedName.
2779 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2780 if (Ivar.isInvalid())
2781 return ExprError();
2782 if (Ivar.isUsable())
2783 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2784 cast<ObjCIvarDecl>(Ivar.get()));
2785
2786 if (Lookup.empty() && II && AllowBuiltinCreation)
2787 LookupBuiltin(Lookup);
2788
2789 // Sentinel value saying that we didn't do anything special.
2790 return ExprResult(false);
2791}
2792
2793/// Cast a base object to a member's actual type.
2794///
2795/// Logically this happens in three phases:
2796///
2797/// * First we cast from the base type to the naming class.
2798/// The naming class is the class into which we were looking
2799/// when we found the member; it's the qualifier type if a
2800/// qualifier was provided, and otherwise it's the base type.
2801///
2802/// * Next we cast from the naming class to the declaring class.
2803/// If the member we found was brought into a class's scope by
2804/// a using declaration, this is that class; otherwise it's
2805/// the class declaring the member.
2806///
2807/// * Finally we cast from the declaring class to the "true"
2808/// declaring class of the member. This conversion does not
2809/// obey access control.
2810ExprResult
2811Sema::PerformObjectMemberConversion(Expr *From,
2812 NestedNameSpecifier *Qualifier,
2813 NamedDecl *FoundDecl,
2814 NamedDecl *Member) {
2815 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2816 if (!RD)
2817 return From;
2818
2819 QualType DestRecordType;
2820 QualType DestType;
2821 QualType FromRecordType;
2822 QualType FromType = From->getType();
2823 bool PointerConversions = false;
2824 if (isa<FieldDecl>(Member)) {
2825 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2826 auto FromPtrType = FromType->getAs<PointerType>();
2827 DestRecordType = Context.getAddrSpaceQualType(
2828 DestRecordType, FromPtrType
2829 ? FromType->getPointeeType().getAddressSpace()
2830 : FromType.getAddressSpace());
2831
2832 if (FromPtrType) {
2833 DestType = Context.getPointerType(DestRecordType);
2834 FromRecordType = FromPtrType->getPointeeType();
2835 PointerConversions = true;
2836 } else {
2837 DestType = DestRecordType;
2838 FromRecordType = FromType;
2839 }
2840 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2841 if (Method->isStatic())
2842 return From;
2843
2844 DestType = Method->getThisType();
2845 DestRecordType = DestType->getPointeeType();
2846
2847 if (FromType->getAs<PointerType>()) {
2848 FromRecordType = FromType->getPointeeType();
2849 PointerConversions = true;
2850 } else {
2851 FromRecordType = FromType;
2852 DestType = DestRecordType;
2853 }
2854
2855 LangAS FromAS = FromRecordType.getAddressSpace();
2856 LangAS DestAS = DestRecordType.getAddressSpace();
2857 if (FromAS != DestAS) {
2858 QualType FromRecordTypeWithoutAS =
2859 Context.removeAddrSpaceQualType(FromRecordType);
2860 QualType FromTypeWithDestAS =
2861 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2862 if (PointerConversions)
2863 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2864 From = ImpCastExprToType(From, FromTypeWithDestAS,
2865 CK_AddressSpaceConversion, From->getValueKind())
2866 .get();
2867 }
2868 } else {
2869 // No conversion necessary.
2870 return From;
2871 }
2872
2873 if (DestType->isDependentType() || FromType->isDependentType())
2874 return From;
2875
2876 // If the unqualified types are the same, no conversion is necessary.
2877 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2878 return From;
2879
2880 SourceRange FromRange = From->getSourceRange();
2881 SourceLocation FromLoc = FromRange.getBegin();
2882
2883 ExprValueKind VK = From->getValueKind();
2884
2885 // C++ [class.member.lookup]p8:
2886 // [...] Ambiguities can often be resolved by qualifying a name with its
2887 // class name.
2888 //
2889 // If the member was a qualified name and the qualified referred to a
2890 // specific base subobject type, we'll cast to that intermediate type
2891 // first and then to the object in which the member is declared. That allows
2892 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2893 //
2894 // class Base { public: int x; };
2895 // class Derived1 : public Base { };
2896 // class Derived2 : public Base { };
2897 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2898 //
2899 // void VeryDerived::f() {
2900 // x = 17; // error: ambiguous base subobjects
2901 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2902 // }
2903 if (Qualifier && Qualifier->getAsType()) {
2904 QualType QType = QualType(Qualifier->getAsType(), 0);
2905 assert(QType->isRecordType() && "lookup done with non-record type")((QType->isRecordType() && "lookup done with non-record type"
) ? static_cast<void> (0) : __assert_fail ("QType->isRecordType() && \"lookup done with non-record type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2905, __PRETTY_FUNCTION__))
;
2906
2907 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2908
2909 // In C++98, the qualifier type doesn't actually have to be a base
2910 // type of the object type, in which case we just ignore it.
2911 // Otherwise build the appropriate casts.
2912 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2913 CXXCastPath BasePath;
2914 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2915 FromLoc, FromRange, &BasePath))
2916 return ExprError();
2917
2918 if (PointerConversions)
2919 QType = Context.getPointerType(QType);
2920 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2921 VK, &BasePath).get();
2922
2923 FromType = QType;
2924 FromRecordType = QRecordType;
2925
2926 // If the qualifier type was the same as the destination type,
2927 // we're done.
2928 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2929 return From;
2930 }
2931 }
2932
2933 bool IgnoreAccess = false;
2934
2935 // If we actually found the member through a using declaration, cast
2936 // down to the using declaration's type.
2937 //
2938 // Pointer equality is fine here because only one declaration of a
2939 // class ever has member declarations.
2940 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2941 assert(isa<UsingShadowDecl>(FoundDecl))((isa<UsingShadowDecl>(FoundDecl)) ? static_cast<void
> (0) : __assert_fail ("isa<UsingShadowDecl>(FoundDecl)"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2941, __PRETTY_FUNCTION__))
;
2942 QualType URecordType = Context.getTypeDeclType(
2943 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2944
2945 // We only need to do this if the naming-class to declaring-class
2946 // conversion is non-trivial.
2947 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2948 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType))((IsDerivedFrom(FromLoc, FromRecordType, URecordType)) ? static_cast
<void> (0) : __assert_fail ("IsDerivedFrom(FromLoc, FromRecordType, URecordType)"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2948, __PRETTY_FUNCTION__))
;
2949 CXXCastPath BasePath;
2950 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2951 FromLoc, FromRange, &BasePath))
2952 return ExprError();
2953
2954 QualType UType = URecordType;
2955 if (PointerConversions)
2956 UType = Context.getPointerType(UType);
2957 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2958 VK, &BasePath).get();
2959 FromType = UType;
2960 FromRecordType = URecordType;
2961 }
2962
2963 // We don't do access control for the conversion from the
2964 // declaring class to the true declaring class.
2965 IgnoreAccess = true;
2966 }
2967
2968 CXXCastPath BasePath;
2969 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2970 FromLoc, FromRange, &BasePath,
2971 IgnoreAccess))
2972 return ExprError();
2973
2974 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2975 VK, &BasePath);
2976}
2977
2978bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2979 const LookupResult &R,
2980 bool HasTrailingLParen) {
2981 // Only when used directly as the postfix-expression of a call.
2982 if (!HasTrailingLParen)
2983 return false;
2984
2985 // Never if a scope specifier was provided.
2986 if (SS.isSet())
2987 return false;
2988
2989 // Only in C++ or ObjC++.
2990 if (!getLangOpts().CPlusPlus)
2991 return false;
2992
2993 // Turn off ADL when we find certain kinds of declarations during
2994 // normal lookup:
2995 for (NamedDecl *D : R) {
2996 // C++0x [basic.lookup.argdep]p3:
2997 // -- a declaration of a class member
2998 // Since using decls preserve this property, we check this on the
2999 // original decl.
3000 if (D->isCXXClassMember())
3001 return false;
3002
3003 // C++0x [basic.lookup.argdep]p3:
3004 // -- a block-scope function declaration that is not a
3005 // using-declaration
3006 // NOTE: we also trigger this for function templates (in fact, we
3007 // don't check the decl type at all, since all other decl types
3008 // turn off ADL anyway).
3009 if (isa<UsingShadowDecl>(D))
3010 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3011 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3012 return false;
3013
3014 // C++0x [basic.lookup.argdep]p3:
3015 // -- a declaration that is neither a function or a function
3016 // template
3017 // And also for builtin functions.
3018 if (isa<FunctionDecl>(D)) {
3019 FunctionDecl *FDecl = cast<FunctionDecl>(D);
3020
3021 // But also builtin functions.
3022 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3023 return false;
3024 } else if (!isa<FunctionTemplateDecl>(D))
3025 return false;
3026 }
3027
3028 return true;
3029}
3030
3031
3032/// Diagnoses obvious problems with the use of the given declaration
3033/// as an expression. This is only actually called for lookups that
3034/// were not overloaded, and it doesn't promise that the declaration
3035/// will in fact be used.
3036static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3037 if (D->isInvalidDecl())
3038 return true;
3039
3040 if (isa<TypedefNameDecl>(D)) {
3041 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3042 return true;
3043 }
3044
3045 if (isa<ObjCInterfaceDecl>(D)) {
3046 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3047 return true;
3048 }
3049
3050 if (isa<NamespaceDecl>(D)) {
3051 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3052 return true;
3053 }
3054
3055 return false;
3056}
3057
3058// Certain multiversion types should be treated as overloaded even when there is
3059// only one result.
3060static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3061 assert(R.isSingleResult() && "Expected only a single result")((R.isSingleResult() && "Expected only a single result"
) ? static_cast<void> (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3061, __PRETTY_FUNCTION__))
;
3062 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3063 return FD &&
3064 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3065}
3066
3067ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3068 LookupResult &R, bool NeedsADL,
3069 bool AcceptInvalidDecl) {
3070 // If this is a single, fully-resolved result and we don't need ADL,
3071 // just build an ordinary singleton decl ref.
3072 if (!NeedsADL && R.isSingleResult() &&
3073 !R.getAsSingle<FunctionTemplateDecl>() &&
3074 !ShouldLookupResultBeMultiVersionOverload(R))
3075 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3076 R.getRepresentativeDecl(), nullptr,
3077 AcceptInvalidDecl);
3078
3079 // We only need to check the declaration if there's exactly one
3080 // result, because in the overloaded case the results can only be
3081 // functions and function templates.
3082 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3083 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3084 return ExprError();
3085
3086 // Otherwise, just build an unresolved lookup expression. Suppress
3087 // any lookup-related diagnostics; we'll hash these out later, when
3088 // we've picked a target.
3089 R.suppressDiagnostics();
3090
3091 UnresolvedLookupExpr *ULE
3092 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3093 SS.getWithLocInContext(Context),
3094 R.getLookupNameInfo(),
3095 NeedsADL, R.isOverloadedResult(),
3096 R.begin(), R.end());
3097
3098 return ULE;
3099}
3100
3101static void
3102diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3103 ValueDecl *var, DeclContext *DC);
3104
3105/// Complete semantic analysis for a reference to the given declaration.
3106ExprResult Sema::BuildDeclarationNameExpr(
3107 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3108 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3109 bool AcceptInvalidDecl) {
3110 assert(D && "Cannot refer to a NULL declaration")((D && "Cannot refer to a NULL declaration") ? static_cast
<void> (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3110, __PRETTY_FUNCTION__))
;
3111 assert(!isa<FunctionTemplateDecl>(D) &&((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template"
) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3112, __PRETTY_FUNCTION__))
3112 "Cannot refer unambiguously to a function template")((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template"
) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3112, __PRETTY_FUNCTION__))
;
3113
3114 SourceLocation Loc = NameInfo.getLoc();
3115 if (CheckDeclInExpr(*this, Loc, D))
3116 return ExprError();
3117
3118 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3119 // Specifically diagnose references to class templates that are missing
3120 // a template argument list.
3121 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3122 return ExprError();
3123 }
3124
3125 // Make sure that we're referring to a value.
3126 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3127 if (!VD) {
3128 Diag(Loc, diag::err_ref_non_value)
3129 << D << SS.getRange();
3130 Diag(D->getLocation(), diag::note_declared_at);
3131 return ExprError();
3132 }
3133
3134 // Check whether this declaration can be used. Note that we suppress
3135 // this check when we're going to perform argument-dependent lookup
3136 // on this function name, because this might not be the function
3137 // that overload resolution actually selects.
3138 if (DiagnoseUseOfDecl(VD, Loc))
3139 return ExprError();
3140
3141 // Only create DeclRefExpr's for valid Decl's.
3142 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3143 return ExprError();
3144
3145 // Handle members of anonymous structs and unions. If we got here,
3146 // and the reference is to a class member indirect field, then this
3147 // must be the subject of a pointer-to-member expression.
3148 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3149 if (!indirectField->isCXXClassMember())
3150 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3151 indirectField);
3152
3153 {
3154 QualType type = VD->getType();
3155 if (type.isNull())
3156 return ExprError();
3157 ExprValueKind valueKind = VK_RValue;
3158
3159 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3160 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3161 // is expanded by some outer '...' in the context of the use.
3162 type = type.getNonPackExpansionType();
3163
3164 switch (D->getKind()) {
3165 // Ignore all the non-ValueDecl kinds.
3166#define ABSTRACT_DECL(kind)
3167#define VALUE(type, base)
3168#define DECL(type, base) \
3169 case Decl::type:
3170#include "clang/AST/DeclNodes.inc"
3171 llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3171)
;
3172
3173 // These shouldn't make it here.
3174 case Decl::ObjCAtDefsField:
3175 llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3175)
;
3176
3177 // Enum constants are always r-values and never references.
3178 // Unresolved using declarations are dependent.
3179 case Decl::EnumConstant:
3180 case Decl::UnresolvedUsingValue:
3181 case Decl::OMPDeclareReduction:
3182 case Decl::OMPDeclareMapper:
3183 valueKind = VK_RValue;
3184 break;
3185
3186 // Fields and indirect fields that got here must be for
3187 // pointer-to-member expressions; we just call them l-values for
3188 // internal consistency, because this subexpression doesn't really
3189 // exist in the high-level semantics.
3190 case Decl::Field:
3191 case Decl::IndirectField:
3192 case Decl::ObjCIvar:
3193 assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "building reference to field in C?"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3194, __PRETTY_FUNCTION__))
3194 "building reference to field in C?")((getLangOpts().CPlusPlus && "building reference to field in C?"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3194, __PRETTY_FUNCTION__))
;
3195
3196 // These can't have reference type in well-formed programs, but
3197 // for internal consistency we do this anyway.
3198 type = type.getNonReferenceType();
3199 valueKind = VK_LValue;
3200 break;
3201
3202 // Non-type template parameters are either l-values or r-values
3203 // depending on the type.
3204 case Decl::NonTypeTemplateParm: {
3205 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3206 type = reftype->getPointeeType();
3207 valueKind = VK_LValue; // even if the parameter is an r-value reference
3208 break;
3209 }
3210
3211 // For non-references, we need to strip qualifiers just in case
3212 // the template parameter was declared as 'const int' or whatever.
3213 valueKind = VK_RValue;
3214 type = type.getUnqualifiedType();
3215 break;
3216 }
3217
3218 case Decl::Var:
3219 case Decl::VarTemplateSpecialization:
3220 case Decl::VarTemplatePartialSpecialization:
3221 case Decl::Decomposition:
3222 case Decl::OMPCapturedExpr:
3223 // In C, "extern void blah;" is valid and is an r-value.
3224 if (!getLangOpts().CPlusPlus &&
3225 !type.hasQualifiers() &&
3226 type->isVoidType()) {
3227 valueKind = VK_RValue;
3228 break;
3229 }
3230 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3231
3232 case Decl::ImplicitParam:
3233 case Decl::ParmVar: {
3234 // These are always l-values.
3235 valueKind = VK_LValue;
3236 type = type.getNonReferenceType();
3237
3238 // FIXME: Does the addition of const really only apply in
3239 // potentially-evaluated contexts? Since the variable isn't actually
3240 // captured in an unevaluated context, it seems that the answer is no.
3241 if (!isUnevaluatedContext()) {
3242 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3243 if (!CapturedType.isNull())
3244 type = CapturedType;
3245 }
3246
3247 break;
3248 }
3249
3250 case Decl::Binding: {
3251 // These are always lvalues.
3252 valueKind = VK_LValue;
3253 type = type.getNonReferenceType();
3254 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3255 // decides how that's supposed to work.
3256 auto *BD = cast<BindingDecl>(VD);
3257 if (BD->getDeclContext() != CurContext) {
3258 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3259 if (DD && DD->hasLocalStorage())
3260 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3261 }
3262 break;
3263 }
3264
3265 case Decl::Function: {
3266 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3267 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3268 type = Context.BuiltinFnTy;
3269 valueKind = VK_RValue;
3270 break;
3271 }
3272 }
3273
3274 const FunctionType *fty = type->castAs<FunctionType>();
3275
3276 // If we're referring to a function with an __unknown_anytype
3277 // result type, make the entire expression __unknown_anytype.
3278 if (fty->getReturnType() == Context.UnknownAnyTy) {
3279 type = Context.UnknownAnyTy;
3280 valueKind = VK_RValue;
3281 break;
3282 }
3283
3284 // Functions are l-values in C++.
3285 if (getLangOpts().CPlusPlus) {
3286 valueKind = VK_LValue;
3287 break;
3288 }
3289
3290 // C99 DR 316 says that, if a function type comes from a
3291 // function definition (without a prototype), that type is only
3292 // used for checking compatibility. Therefore, when referencing
3293 // the function, we pretend that we don't have the full function
3294 // type.
3295 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3296 isa<FunctionProtoType>(fty))
3297 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3298 fty->getExtInfo());
3299
3300 // Functions are r-values in C.
3301 valueKind = VK_RValue;
3302 break;
3303 }
3304
3305 case Decl::CXXDeductionGuide:
3306 llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3306)
;
3307
3308 case Decl::MSProperty:
3309 case Decl::MSGuid:
3310 // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3311 // or duplicated between host and device?
3312 valueKind = VK_LValue;
3313 break;
3314
3315 case Decl::CXXMethod:
3316 // If we're referring to a method with an __unknown_anytype
3317 // result type, make the entire expression __unknown_anytype.
3318 // This should only be possible with a type written directly.
3319 if (const FunctionProtoType *proto
3320 = dyn_cast<FunctionProtoType>(VD->getType()))
3321 if (proto->getReturnType() == Context.UnknownAnyTy) {
3322 type = Context.UnknownAnyTy;
3323 valueKind = VK_RValue;
3324 break;
3325 }
3326
3327 // C++ methods are l-values if static, r-values if non-static.
3328 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3329 valueKind = VK_LValue;
3330 break;
3331 }
3332 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3333
3334 case Decl::CXXConversion:
3335 case Decl::CXXDestructor:
3336 case Decl::CXXConstructor:
3337 valueKind = VK_RValue;
3338 break;
3339 }
3340
3341 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3342 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3343 TemplateArgs);
3344 }
3345}
3346
3347static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3348 SmallString<32> &Target) {
3349 Target.resize(CharByteWidth * (Source.size() + 1));
3350 char *ResultPtr = &Target[0];
3351 const llvm::UTF8 *ErrorPtr;
3352 bool success =
3353 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3354 (void)success;
3355 assert(success)((success) ? static_cast<void> (0) : __assert_fail ("success"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3355, __PRETTY_FUNCTION__))
;
3356 Target.resize(ResultPtr - &Target[0]);
3357}
3358
3359ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3360 PredefinedExpr::IdentKind IK) {
3361 // Pick the current block, lambda, captured statement or function.
3362 Decl *currentDecl = nullptr;
3363 if (const BlockScopeInfo *BSI = getCurBlock())
3364 currentDecl = BSI->TheDecl;
3365 else if (const LambdaScopeInfo *LSI = getCurLambda())
3366 currentDecl = LSI->CallOperator;
3367 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3368 currentDecl = CSI->TheCapturedDecl;
3369 else
3370 currentDecl = getCurFunctionOrMethodDecl();
3371
3372 if (!currentDecl) {
3373 Diag(Loc, diag::ext_predef_outside_function);
3374 currentDecl = Context.getTranslationUnitDecl();
3375 }
3376
3377 QualType ResTy;
3378 StringLiteral *SL = nullptr;
3379 if (cast<DeclContext>(currentDecl)->isDependentContext())
3380 ResTy = Context.DependentTy;
3381 else {
3382 // Pre-defined identifiers are of type char[x], where x is the length of
3383 // the string.
3384 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3385 unsigned Length = Str.length();
3386
3387 llvm::APInt LengthI(32, Length + 1);
3388 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3389 ResTy =
3390 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3391 SmallString<32> RawChars;
3392 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3393 Str, RawChars);
3394 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3395 ArrayType::Normal,
3396 /*IndexTypeQuals*/ 0);
3397 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3398 /*Pascal*/ false, ResTy, Loc);
3399 } else {
3400 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3401 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3402 ArrayType::Normal,
3403 /*IndexTypeQuals*/ 0);
3404 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3405 /*Pascal*/ false, ResTy, Loc);
3406 }
3407 }
3408
3409 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3410}
3411
3412static std::pair<QualType, StringLiteral *>
3413GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3414 SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3415 std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3416
3417 if (OpType->isDependentType()) {
3418 Result.first = Context.DependentTy;
3419 return Result;
3420 }
3421
3422 std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3423 llvm::APInt Length(32, Str.length() + 1);
3424 Result.first =
3425 Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3426 Result.first = Context.getConstantArrayType(
3427 Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3428 Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3429 /*Pascal*/ false, Result.first, OpLoc);
3430 return Result;
3431}
3432
3433ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3434 TypeSourceInfo *Operand) {
3435 QualType ResultTy;
3436 StringLiteral *SL;
3437 std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3438 Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3439
3440 return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3441 PredefinedExpr::UniqueStableNameType, SL,
3442 Operand);
3443}
3444
3445ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3446 Expr *E) {
3447 QualType ResultTy;
3448 StringLiteral *SL;
3449 std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3450 Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3451
3452 return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3453 PredefinedExpr::UniqueStableNameExpr, SL, E);
3454}
3455
3456ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3457 SourceLocation L, SourceLocation R,
3458 ParsedType Ty) {
3459 TypeSourceInfo *TInfo = nullptr;
3460 QualType T = GetTypeFromParser(Ty, &TInfo);
3461
3462 if (T.isNull())
3463 return ExprError();
3464 if (!TInfo)
3465 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3466
3467 return BuildUniqueStableName(OpLoc, TInfo);
3468}
3469
3470ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3471 SourceLocation L, SourceLocation R,
3472 Expr *E) {
3473 return BuildUniqueStableName(OpLoc, E);
3474}
3475
3476ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3477 PredefinedExpr::IdentKind IK;
3478
3479 switch (Kind) {
3480 default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3480)
;
3481 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3482 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3483 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3484 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3485 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3486 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3487 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3488 }
3489
3490 return BuildPredefinedExpr(Loc, IK);
3491}
3492
3493ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3494 SmallString<16> CharBuffer;
3495 bool Invalid = false;
3496 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3497 if (Invalid)
3498 return ExprError();
3499
3500 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3501 PP, Tok.getKind());
3502 if (Literal.hadError())
3503 return ExprError();
3504
3505 QualType Ty;
3506 if (Literal.isWide())
3507 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3508 else if (Literal.isUTF8() && getLangOpts().Char8)
3509 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3510 else if (Literal.isUTF16())
3511 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3512 else if (Literal.isUTF32())
3513 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3514 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3515 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3516 else
3517 Ty = Context.CharTy; // 'x' -> char in C++
3518
3519 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3520 if (Literal.isWide())
3521 Kind = CharacterLiteral::Wide;
3522 else if (Literal.isUTF16())
3523 Kind = CharacterLiteral::UTF16;
3524 else if (Literal.isUTF32())
3525 Kind = CharacterLiteral::UTF32;
3526 else if (Literal.isUTF8())
3527 Kind = CharacterLiteral::UTF8;
3528
3529 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3530 Tok.getLocation());
3531
3532 if (Literal.getUDSuffix().empty())
3533 return Lit;
3534
3535 // We're building a user-defined literal.
3536 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3537 SourceLocation UDSuffixLoc =
3538 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3539
3540 // Make sure we're allowed user-defined literals here.
3541 if (!UDLScope)
3542 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3543
3544 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3545 // operator "" X (ch)
3546 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3547 Lit, Tok.getLocation());
3548}
3549
3550ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3551 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3552 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3553 Context.IntTy, Loc);
3554}
3555
3556static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3557 QualType Ty, SourceLocation Loc) {
3558 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3559
3560 using llvm::APFloat;
3561 APFloat Val(Format);
3562
3563 APFloat::opStatus result = Literal.GetFloatValue(Val);
3564
3565 // Overflow is always an error, but underflow is only an error if
3566 // we underflowed to zero (APFloat reports denormals as underflow).
3567 if ((result & APFloat::opOverflow) ||
3568 ((result & APFloat::opUnderflow) && Val.isZero())) {
3569 unsigned diagnostic;
3570 SmallString<20> buffer;
3571 if (result & APFloat::opOverflow) {
3572 diagnostic = diag::warn_float_overflow;
3573 APFloat::getLargest(Format).toString(buffer);
3574 } else {
3575 diagnostic = diag::warn_float_underflow;
3576 APFloat::getSmallest(Format).toString(buffer);
3577 }
3578
3579 S.Diag(Loc, diagnostic)
3580 << Ty
3581 << StringRef(buffer.data(), buffer.size());
3582 }
3583
3584 bool isExact = (result == APFloat::opOK);
3585 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3586}
3587
3588bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3589 assert(E && "Invalid expression")((E && "Invalid expression") ? static_cast<void>
(0) : __assert_fail ("E && \"Invalid expression\"", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3589, __PRETTY_FUNCTION__))
;
3590
3591 if (E->isValueDependent())
3592 return false;
3593
3594 QualType QT = E->getType();
3595 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3596 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3597 return true;
3598 }
3599
3600 llvm::APSInt ValueAPS;
3601 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3602
3603 if (R.isInvalid())
3604 return true;
3605
3606 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3607 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3608 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3609 << ValueAPS.toString(10) << ValueIsPositive;
3610 return true;
3611 }
3612
3613 return false;
3614}
3615
3616ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3617 // Fast path for a single digit (which is quite common). A single digit
3618 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3619 if (Tok.getLength() == 1) {
3620 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3621 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3622 }
3623
3624 SmallString<128> SpellingBuffer;
3625 // NumericLiteralParser wants to overread by one character. Add padding to
3626 // the buffer in case the token is copied to the buffer. If getSpelling()
3627 // returns a StringRef to the memory buffer, it should have a null char at
3628 // the EOF, so it is also safe.
3629 SpellingBuffer.resize(Tok.getLength() + 1);
3630
3631 // Get the spelling of the token, which eliminates trigraphs, etc.
3632 bool Invalid = false;
3633 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3634 if (Invalid)
3635 return ExprError();
3636
3637 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3638 PP.getSourceManager(), PP.getLangOpts(),
3639 PP.getTargetInfo(), PP.getDiagnostics());
3640 if (Literal.hadError)
3641 return ExprError();
3642
3643 if (Literal.hasUDSuffix()) {
3644 // We're building a user-defined literal.
3645 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3646 SourceLocation UDSuffixLoc =
3647 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3648
3649 // Make sure we're allowed user-defined literals here.
3650 if (!UDLScope)
3651 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3652
3653 QualType CookedTy;
3654 if (Literal.isFloatingLiteral()) {
3655 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3656 // long double, the literal is treated as a call of the form
3657 // operator "" X (f L)
3658 CookedTy = Context.LongDoubleTy;
3659 } else {
3660 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3661 // unsigned long long, the literal is treated as a call of the form
3662 // operator "" X (n ULL)
3663 CookedTy = Context.UnsignedLongLongTy;
3664 }
3665
3666 DeclarationName OpName =
3667 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3668 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3669 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3670
3671 SourceLocation TokLoc = Tok.getLocation();
3672
3673 // Perform literal operator lookup to determine if we're building a raw
3674 // literal or a cooked one.
3675 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3676 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3677 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3678 /*AllowStringTemplate*/ false,
3679 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3680 case LOLR_ErrorNoDiagnostic:
3681 // Lookup failure for imaginary constants isn't fatal, there's still the
3682 // GNU extension producing _Complex types.
3683 break;
3684 case LOLR_Error:
3685 return ExprError();
3686 case LOLR_Cooked: {
3687 Expr *Lit;
3688 if (Literal.isFloatingLiteral()) {
3689 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3690 } else {
3691 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3692 if (Literal.GetIntegerValue(ResultVal))
3693 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3694 << /* Unsigned */ 1;
3695 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3696 Tok.getLocation());
3697 }
3698 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3699 }
3700
3701 case LOLR_Raw: {
3702 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3703 // literal is treated as a call of the form
3704 // operator "" X ("n")
3705 unsigned Length = Literal.getUDSuffixOffset();
3706 QualType StrTy = Context.getConstantArrayType(
3707 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3708 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3709 Expr *Lit = StringLiteral::Create(
3710 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3711 /*Pascal*/false, StrTy, &TokLoc, 1);
3712 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3713 }
3714
3715 case LOLR_Template: {
3716 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3717 // template), L is treated as a call fo the form
3718 // operator "" X <'c1', 'c2', ... 'ck'>()
3719 // where n is the source character sequence c1 c2 ... ck.
3720 TemplateArgumentListInfo ExplicitArgs;
3721 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3722 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3723 llvm::APSInt Value(CharBits, CharIsUnsigned);
3724 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3725 Value = TokSpelling[I];
3726 TemplateArgument Arg(Context, Value, Context.CharTy);
3727 TemplateArgumentLocInfo ArgInfo;
3728 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3729 }
3730 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3731 &ExplicitArgs);
3732 }
3733 case LOLR_StringTemplate:
3734 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3734)
;
3735 }
3736 }
3737
3738 Expr *Res;
3739
3740 if (Literal.isFixedPointLiteral()) {
3741 QualType Ty;
3742
3743 if (Literal.isAccum) {
3744 if (Literal.isHalf) {
3745 Ty = Context.ShortAccumTy;
3746 } else if (Literal.isLong) {
3747 Ty = Context.LongAccumTy;
3748 } else {
3749 Ty = Context.AccumTy;
3750 }
3751 } else if (Literal.isFract) {
3752 if (Literal.isHalf) {
3753 Ty = Context.ShortFractTy;
3754 } else if (Literal.isLong) {
3755 Ty = Context.LongFractTy;
3756 } else {
3757 Ty = Context.FractTy;
3758 }
3759 }
3760
3761 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3762
3763 bool isSigned = !Literal.isUnsigned;
3764 unsigned scale = Context.getFixedPointScale(Ty);
3765 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3766
3767 llvm::APInt Val(bit_width, 0, isSigned);
3768 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3769 bool ValIsZero = Val.isNullValue() && !Overflowed;
3770
3771 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3772 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3773 // Clause 6.4.4 - The value of a constant shall be in the range of
3774 // representable values for its type, with exception for constants of a
3775 // fract type with a value of exactly 1; such a constant shall denote
3776 // the maximal value for the type.
3777 --Val;
3778 else if (Val.ugt(MaxVal) || Overflowed)
3779 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3780
3781 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3782 Tok.getLocation(), scale);
3783 } else if (Literal.isFloatingLiteral()) {
3784 QualType Ty;
3785 if (Literal.isHalf){
3786 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3787 Ty = Context.HalfTy;
3788 else {
3789 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3790 return ExprError();
3791 }
3792 } else if (Literal.isFloat)
3793 Ty = Context.FloatTy;
3794 else if (Literal.isLong)
3795 Ty = Context.LongDoubleTy;
3796 else if (Literal.isFloat16)
3797 Ty = Context.Float16Ty;
3798 else if (Literal.isFloat128)
3799 Ty = Context.Float128Ty;
3800 else
3801 Ty = Context.DoubleTy;
3802
3803 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3804
3805 if (Ty == Context.DoubleTy) {
3806 if (getLangOpts().SinglePrecisionConstants) {
3807 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3808 if (BTy->getKind() != BuiltinType::Float) {
3809 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3810 }
3811 } else if (getLangOpts().OpenCL &&
3812 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3813 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3814 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3815 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3816 }
3817 }
3818 } else if (!Literal.isIntegerLiteral()) {
3819 return ExprError();
3820 } else {
3821 QualType Ty;
3822
3823 // 'long long' is a C99 or C++11 feature.
3824 if (!getLangOpts().C99 && Literal.isLongLong) {
3825 if (getLangOpts().CPlusPlus)
3826 Diag(Tok.getLocation(),
3827 getLangOpts().CPlusPlus11 ?
3828 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3829 else
3830 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3831 }
3832
3833 // Get the value in the widest-possible width.
3834 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3835 llvm::APInt ResultVal(MaxWidth, 0);
3836
3837 if (Literal.GetIntegerValue(ResultVal)) {
3838 // If this value didn't fit into uintmax_t, error and force to ull.
3839 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3840 << /* Unsigned */ 1;
3841 Ty = Context.UnsignedLongLongTy;
3842 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&((Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
"long long is not intmax_t?") ? static_cast<void> (0) :
__assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3843, __PRETTY_FUNCTION__))
3843 "long long is not intmax_t?")((Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
"long long is not intmax_t?") ? static_cast<void> (0) :
__assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3843, __PRETTY_FUNCTION__))
;
3844 } else {
3845 // If this value fits into a ULL, try to figure out what else it fits into
3846 // according to the rules of C99 6.4.4.1p5.
3847
3848 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3849 // be an unsigned int.
3850 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3851
3852 // Check from smallest to largest, picking the smallest type we can.
3853 unsigned Width = 0;
3854
3855 // Microsoft specific integer suffixes are explicitly sized.
3856 if (Literal.MicrosoftInteger) {
3857 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3858 Width = 8;
3859 Ty = Context.CharTy;
3860 } else {
3861 Width = Literal.MicrosoftInteger;
3862 Ty = Context.getIntTypeForBitwidth(Width,
3863 /*Signed=*/!Literal.isUnsigned);
3864 }
3865 }
3866
3867 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3868 // Are int/unsigned possibilities?
3869 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3870
3871 // Does it fit in a unsigned int?
3872 if (ResultVal.isIntN(IntSize)) {
3873 // Does it fit in a signed int?
3874 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3875 Ty = Context.IntTy;
3876 else if (AllowUnsigned)
3877 Ty = Context.UnsignedIntTy;
3878 Width = IntSize;
3879 }
3880 }
3881
3882 // Are long/unsigned long possibilities?
3883 if (Ty.isNull() && !Literal.isLongLong) {
3884 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3885
3886 // Does it fit in a unsigned long?
3887 if (ResultVal.isIntN(LongSize)) {
3888 // Does it fit in a signed long?
3889 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3890 Ty = Context.LongTy;
3891 else if (AllowUnsigned)
3892 Ty = Context.UnsignedLongTy;
3893 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3894 // is compatible.
3895 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3896 const unsigned LongLongSize =
3897 Context.getTargetInfo().getLongLongWidth();
3898 Diag(Tok.getLocation(),
3899 getLangOpts().CPlusPlus
3900 ? Literal.isLong
3901 ? diag::warn_old_implicitly_unsigned_long_cxx
3902 : /*C++98 UB*/ diag::
3903 ext_old_implicitly_unsigned_long_cxx
3904 : diag::warn_old_implicitly_unsigned_long)
3905 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3906 : /*will be ill-formed*/ 1);
3907 Ty = Context.UnsignedLongTy;
3908 }
3909 Width = LongSize;
3910 }
3911 }
3912
3913 // Check long long if needed.
3914 if (Ty.isNull()) {
3915 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3916
3917 // Does it fit in a unsigned long long?
3918 if (ResultVal.isIntN(LongLongSize)) {
3919 // Does it fit in a signed long long?
3920 // To be compatible with MSVC, hex integer literals ending with the
3921 // LL or i64 suffix are always signed in Microsoft mode.
3922 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3923 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3924 Ty = Context.LongLongTy;
3925 else if (AllowUnsigned)
3926 Ty = Context.UnsignedLongLongTy;
3927 Width = LongLongSize;
3928 }
3929 }
3930
3931 // If we still couldn't decide a type, we probably have something that
3932 // does not fit in a signed long long, but has no U suffix.
3933 if (Ty.isNull()) {
3934 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3935 Ty = Context.UnsignedLongLongTy;
3936 Width = Context.getTargetInfo().getLongLongWidth();
3937 }
3938
3939 if (ResultVal.getBitWidth() != Width)
3940 ResultVal = ResultVal.trunc(Width);
3941 }
3942 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3943 }
3944
3945 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3946 if (Literal.isImaginary) {
3947 Res = new (Context) ImaginaryLiteral(Res,
3948 Context.getComplexType(Res->getType()));
3949
3950 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3951 }
3952 return Res;
3953}
3954
3955ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3956 assert(E && "ActOnParenExpr() missing expr")((E && "ActOnParenExpr() missing expr") ? static_cast
<void> (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3956, __PRETTY_FUNCTION__))
;
3957 return new (Context) ParenExpr(L, R, E);
3958}
3959
3960static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3961 SourceLocation Loc,
3962 SourceRange ArgRange) {
3963 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3964 // scalar or vector data type argument..."
3965 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3966 // type (C99 6.2.5p18) or void.
3967 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3968 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3969 << T << ArgRange;
3970 return true;
3971 }
3972
3973 assert((T->isVoidType() || !T->isIncompleteType()) &&(((T->isVoidType() || !T->isIncompleteType()) &&
"Scalar types should always be complete") ? static_cast<void
> (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3974, __PRETTY_FUNCTION__))
3974 "Scalar types should always be complete")(((T->isVoidType() || !T->isIncompleteType()) &&
"Scalar types should always be complete") ? static_cast<void
> (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3974, __PRETTY_FUNCTION__))
;
3975 return false;
3976}
3977
3978static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3979 SourceLocation Loc,
3980 SourceRange ArgRange,
3981 UnaryExprOrTypeTrait TraitKind) {
3982 // Invalid types must be hard errors for SFINAE in C++.
3983 if (S.LangOpts.CPlusPlus)
3984 return true;
3985
3986 // C99 6.5.3.4p1:
3987 if (T->isFunctionType() &&
3988 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3989 TraitKind == UETT_PreferredAlignOf)) {
3990 // sizeof(function)/alignof(function) is allowed as an extension.
3991 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3992 << getTraitSpelling(TraitKind) << ArgRange;
3993 return false;
3994 }
3995
3996 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3997 // this is an error (OpenCL v1.1 s6.3.k)
3998 if (T->isVoidType()) {
3999 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4000 : diag::ext_sizeof_alignof_void_type;
4001 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4002 return false;
4003 }
4004
4005 return true;
4006}
4007
4008static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4009 SourceLocation Loc,
4010 SourceRange ArgRange,
4011 UnaryExprOrTypeTrait TraitKind) {
4012 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4013 // runtime doesn't allow it.
4014 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4015 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4016 << T << (TraitKind == UETT_SizeOf)
4017 << ArgRange;
4018 return true;
4019 }
4020
4021 return false;
4022}
4023
4024/// Check whether E is a pointer from a decayed array type (the decayed
4025/// pointer type is equal to T) and emit a warning if it is.
4026static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4027 Expr *E) {
4028 // Don't warn if the operation changed the type.
4029 if (T != E->getType())
4030 return;
4031
4032 // Now look for array decays.
4033 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4034 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4035 return;
4036
4037 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4038 << ICE->getType()
4039 << ICE->getSubExpr()->getType();
4040}
4041
4042/// Check the constraints on expression operands to unary type expression
4043/// and type traits.
4044///
4045/// Completes any types necessary and validates the constraints on the operand
4046/// expression. The logic mostly mirrors the type-based overload, but may modify
4047/// the expression as it completes the type for that expression through template
4048/// instantiation, etc.
4049bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4050 UnaryExprOrTypeTrait ExprKind) {
4051 QualType ExprTy = E->getType();
4052 assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4052, __PRETTY_FUNCTION__))
;
4053
4054 bool IsUnevaluatedOperand =
4055 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4056 ExprKind == UETT_PreferredAlignOf);
4057 if (IsUnevaluatedOperand) {
4058 ExprResult Result = CheckUnevaluatedOperand(E);
4059 if (Result.isInvalid())
4060 return true;
4061 E = Result.get();
4062 }
4063
4064 if (ExprKind == UETT_VecStep)
4065 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4066 E->getSourceRange());
4067
4068 // Explicitly list some types as extensions.
4069 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4070 E->getSourceRange(), ExprKind))
4071 return false;
4072
4073 // 'alignof' applied to an expression only requires the base element type of
4074 // the expression to be complete. 'sizeof' requires the expression's type to
4075 // be complete (and will attempt to complete it if it's an array of unknown
4076 // bound).
4077 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4078 if (RequireCompleteSizedType(
4079 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4080 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4081 getTraitSpelling(ExprKind), E->getSourceRange()))
4082 return true;
4083 } else {
4084 if (RequireCompleteSizedExprType(
4085 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4086 getTraitSpelling(ExprKind), E->getSourceRange()))
4087 return true;
4088 }
4089
4090 // Completing the expression's type may have changed it.
4091 ExprTy = E->getType();
4092 assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4092, __PRETTY_FUNCTION__))
;
4093
4094 if (ExprTy->isFunctionType()) {
4095 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4096 << getTraitSpelling(ExprKind) << E->getSourceRange();
4097 return true;
4098 }
4099
4100 // The operand for sizeof and alignof is in an unevaluated expression context,
4101 // so side effects could result in unintended consequences.
4102 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4103 E->HasSideEffects(Context, false))
4104 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4105
4106 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4107 E->getSourceRange(), ExprKind))
4108 return true;
4109
4110 if (ExprKind == UETT_SizeOf) {
4111 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4112 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4113 QualType OType = PVD->getOriginalType();
4114 QualType Type = PVD->getType();
4115 if (Type->isPointerType() && OType->isArrayType()) {
4116 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4117 << Type << OType;
4118 Diag(PVD->getLocation(), diag::note_declared_at);
4119 }
4120 }
4121 }
4122
4123 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4124 // decays into a pointer and returns an unintended result. This is most
4125 // likely a typo for "sizeof(array) op x".
4126 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4127 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4128 BO->getLHS());
4129 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4130 BO->getRHS());
4131 }
4132 }
4133
4134 return false;
4135}
4136
4137/// Check the constraints on operands to unary expression and type
4138/// traits.
4139///
4140/// This will complete any types necessary, and validate the various constraints
4141/// on those operands.
4142///
4143/// The UsualUnaryConversions() function is *not* called by this routine.
4144/// C99 6.3.2.1p[2-4] all state:
4145/// Except when it is the operand of the sizeof operator ...
4146///
4147/// C++ [expr.sizeof]p4
4148/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4149/// standard conversions are not applied to the operand of sizeof.
4150///
4151/// This policy is followed for all of the unary trait expressions.
4152bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4153 SourceLocation OpLoc,
4154 SourceRange ExprRange,
4155 UnaryExprOrTypeTrait ExprKind) {
4156 if (ExprType->isDependentType())
4157 return false;
4158
4159 // C++ [expr.sizeof]p2:
4160 // When applied to a reference or a reference type, the result
4161 // is the size of the referenced type.
4162 // C++11 [expr.alignof]p3:
4163 // When alignof is applied to a reference type, the result
4164 // shall be the alignment of the referenced type.
4165 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4166 ExprType = Ref->getPointeeType();
4167
4168 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4169 // When alignof or _Alignof is applied to an array type, the result
4170 // is the alignment of the element type.
4171 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4172 ExprKind == UETT_OpenMPRequiredSimdAlign)
4173 ExprType = Context.getBaseElementType(ExprType);
4174
4175 if (ExprKind == UETT_VecStep)
4176 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4177
4178 // Explicitly list some types as extensions.
4179 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4180 ExprKind))
4181 return false;
4182
4183 if (RequireCompleteSizedType(
4184 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4185 getTraitSpelling(ExprKind), ExprRange))
4186 return true;
4187
4188 if (ExprType->isFunctionType()) {
4189 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4190 << getTraitSpelling(ExprKind) << ExprRange;
4191 return true;
4192 }
4193
4194 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4195 ExprKind))
4196 return true;
4197
4198 return false;
4199}
4200
4201static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4202 // Cannot know anything else if the expression is dependent.
4203 if (E->isTypeDependent())
4204 return false;
4205
4206 if (E->getObjectKind() == OK_BitField) {
4207 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4208 << 1 << E->getSourceRange();
4209 return true;
4210 }
4211
4212 ValueDecl *D = nullptr;
4213 Expr *Inner = E->IgnoreParens();
4214 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4215 D = DRE->getDecl();
4216 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4217 D = ME->getMemberDecl();
4218 }
4219
4220 // If it's a field, require the containing struct to have a
4221 // complete definition so that we can compute the layout.
4222 //
4223 // This can happen in C++11 onwards, either by naming the member
4224 // in a way that is not transformed into a member access expression
4225 // (in an unevaluated operand, for instance), or by naming the member
4226 // in a trailing-return-type.
4227 //
4228 // For the record, since __alignof__ on expressions is a GCC
4229 // extension, GCC seems to permit this but always gives the
4230 // nonsensical answer 0.
4231 //
4232 // We don't really need the layout here --- we could instead just
4233 // directly check for all the appropriate alignment-lowing
4234 // attributes --- but that would require duplicating a lot of
4235 // logic that just isn't worth duplicating for such a marginal
4236 // use-case.
4237 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4238 // Fast path this check, since we at least know the record has a
4239 // definition if we can find a member of it.
4240 if (!FD->getParent()->isCompleteDefinition()) {
4241 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4242 << E->getSourceRange();
4243 return true;
4244 }
4245
4246 // Otherwise, if it's a field, and the field doesn't have
4247 // reference type, then it must have a complete type (or be a
4248 // flexible array member, which we explicitly want to
4249 // white-list anyway), which makes the following checks trivial.
4250 if (!FD->getType()->isReferenceType())
4251 return false;
4252 }
4253
4254 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4255}
4256
4257bool Sema::CheckVecStepExpr(Expr *E) {
4258 E = E->IgnoreParens();
4259
4260 // Cannot know anything else if the expression is dependent.
4261 if (E->isTypeDependent())
4262 return false;
4263
4264 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4265}
4266
4267static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4268 CapturingScopeInfo *CSI) {
4269 assert(T->isVariablyModifiedType())((T->isVariablyModifiedType()) ? static_cast<void> (
0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4269, __PRETTY_FUNCTION__))
;
4270 assert(CSI != nullptr)((CSI != nullptr) ? static_cast<void> (0) : __assert_fail
("CSI != nullptr", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4270, __PRETTY_FUNCTION__))
;
4271
4272 // We're going to walk down into the type and look for VLA expressions.
4273 do {
4274 const Type *Ty = T.getTypePtr();
4275 switch (Ty->getTypeClass()) {
4276#define TYPE(Class, Base)
4277#define ABSTRACT_TYPE(Class, Base)
4278#define NON_CANONICAL_TYPE(Class, Base)
4279#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4280#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4281#include "clang/AST/TypeNodes.inc"
4282 T = QualType();
4283 break;
4284 // These types are never variably-modified.
4285 case Type::Builtin:
4286 case Type::Complex:
4287 case Type::Vector:
4288 case Type::ExtVector:
4289 case Type::ConstantMatrix:
4290 case Type::Record:
4291 case Type::Enum:
4292 case Type::Elaborated:
4293 case Type::TemplateSpecialization:
4294 case Type::ObjCObject:
4295 case Type::ObjCInterface:
4296 case Type::ObjCObjectPointer:
4297 case Type::ObjCTypeParam:
4298 case Type::Pipe:
4299 case Type::ExtInt:
4300 llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4300)
;
4301 case Type::Adjusted:
4302 T = cast<AdjustedType>(Ty)->getOriginalType();
4303 break;
4304 case Type::Decayed:
4305 T = cast<DecayedType>(Ty)->getPointeeType();
4306 break;
4307 case Type::Pointer:
4308 T = cast<PointerType>(Ty)->getPointeeType();
4309 break;
4310 case Type::BlockPointer:
4311 T = cast<BlockPointerType>(Ty)->getPointeeType();
4312 break;
4313 case Type::LValueReference:
4314 case Type::RValueReference:
4315 T = cast<ReferenceType>(Ty)->getPointeeType();
4316 break;
4317 case Type::MemberPointer:
4318 T = cast<MemberPointerType>(Ty)->getPointeeType();
4319 break;
4320 case Type::ConstantArray:
4321 case Type::IncompleteArray:
4322 // Losing element qualification here is fine.
4323 T = cast<ArrayType>(Ty)->getElementType();
4324 break;
4325 case Type::VariableArray: {
4326 // Losing element qualification here is fine.
4327 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4328
4329 // Unknown size indication requires no size computation.
4330 // Otherwise, evaluate and record it.
4331 auto Size = VAT->getSizeExpr();
4332 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4333 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4334 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4335
4336 T = VAT->getElementType();
4337 break;
4338 }
4339 case Type::FunctionProto:
4340 case Type::FunctionNoProto:
4341 T = cast<FunctionType>(Ty)->getReturnType();
4342 break;
4343 case Type::Paren:
4344 case Type::TypeOf:
4345 case Type::UnaryTransform:
4346 case Type::Attributed:
4347 case Type::SubstTemplateTypeParm:
4348 case Type::MacroQualified:
4349 // Keep walking after single level desugaring.
4350 T = T.getSingleStepDesugaredType(Context);
4351 break;
4352 case Type::Typedef:
4353 T = cast<TypedefType>(Ty)->desugar();
4354 break;
4355 case Type::Decltype:
4356 T = cast<DecltypeType>(Ty)->desugar();
4357 break;
4358 case Type::Auto:
4359 case Type::DeducedTemplateSpecialization:
4360 T = cast<DeducedType>(Ty)->getDeducedType();
4361 break;
4362 case Type::TypeOfExpr:
4363 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4364 break;
4365 case Type::Atomic:
4366 T = cast<AtomicType>(Ty)->getValueType();
4367 break;
4368 }
4369 } while (!T.isNull() && T->isVariablyModifiedType());
4370}
4371
4372/// Build a sizeof or alignof expression given a type operand.
4373ExprResult
4374Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4375 SourceLocation OpLoc,
4376 UnaryExprOrTypeTrait ExprKind,
4377 SourceRange R) {
4378 if (!TInfo)
4379 return ExprError();
4380
4381 QualType T = TInfo->getType();
4382
4383 if (!T->isDependentType() &&
4384 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4385 return ExprError();
4386
4387 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4388 if (auto *TT = T->getAs<TypedefType>()) {
4389 for (auto I = FunctionScopes.rbegin(),
4390 E = std::prev(FunctionScopes.rend());
4391 I != E; ++I) {
4392 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4393 if (CSI == nullptr)
4394 break;
4395 DeclContext *DC = nullptr;
4396 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4397 DC = LSI->CallOperator;
4398 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4399 DC = CRSI->TheCapturedDecl;
4400 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4401 DC = BSI->TheDecl;
4402 if (DC) {
4403 if (DC->containsDecl(TT->getDecl()))
4404 break;
4405 captureVariablyModifiedType(Context, T, CSI);
4406 }
4407 }
4408 }
4409 }
4410
4411 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4412 return new (Context) UnaryExprOrTypeTraitExpr(
4413 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4414}
4415
4416/// Build a sizeof or alignof expression given an expression
4417/// operand.
4418ExprResult
4419Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4420 UnaryExprOrTypeTrait ExprKind) {
4421 ExprResult PE = CheckPlaceholderExpr(E);
4422 if (PE.isInvalid())
4423 return ExprError();
4424
4425 E = PE.get();
4426
4427 // Verify that the operand is valid.
4428 bool isInvalid = false;
4429 if (E->isTypeDependent()) {
4430 // Delay type-checking for type-dependent expressions.
4431 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4432 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4433 } else if (ExprKind == UETT_VecStep) {
4434 isInvalid = CheckVecStepExpr(E);
4435 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4436 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4437 isInvalid = true;
4438 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4439 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4440 isInvalid = true;
4441 } else {
4442 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4443 }
4444
4445 if (isInvalid)
4446 return ExprError();
4447
4448 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4449 PE = TransformToPotentiallyEvaluated(E);
4450 if (PE.isInvalid()) return ExprError();
4451 E = PE.get();
4452 }
4453
4454 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4455 return new (Context) UnaryExprOrTypeTraitExpr(
4456 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4457}
4458
4459/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4460/// expr and the same for @c alignof and @c __alignof
4461/// Note that the ArgRange is invalid if isType is false.
4462ExprResult
4463Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4464 UnaryExprOrTypeTrait ExprKind, bool IsType,
4465 void *TyOrEx, SourceRange ArgRange) {
4466 // If error parsing type, ignore.
4467 if (!TyOrEx) return ExprError();
4468
4469 if (IsType) {
4470 TypeSourceInfo *TInfo;
4471 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4472 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4473 }
4474
4475 Expr *ArgEx = (Expr *)TyOrEx;
4476 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4477 return Result;
4478}
4479
4480static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4481 bool IsReal) {
4482 if (V.get()->isTypeDependent())
4483 return S.Context.DependentTy;
4484
4485 // _Real and _Imag are only l-values for normal l-values.
4486 if (V.get()->getObjectKind() != OK_Ordinary) {
4487 V = S.DefaultLvalueConversion(V.get());
4488 if (V.isInvalid())
4489 return QualType();
4490 }
4491
4492 // These operators return the element type of a complex type.
4493 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4494 return CT->getElementType();
4495
4496 // Otherwise they pass through real integer and floating point types here.
4497 if (V.get()->getType()->isArithmeticType())
4498 return V.get()->getType();
4499
4500 // Test for placeholders.
4501 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4502 if (PR.isInvalid()) return QualType();
4503 if (PR.get() != V.get()) {
4504 V = PR;
4505 return CheckRealImagOperand(S, V, Loc, IsReal);
4506 }
4507
4508 // Reject anything else.
4509 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4510 << (IsReal ? "__real" : "__imag");
4511 return QualType();
4512}
4513
4514
4515
4516ExprResult
4517Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4518 tok::TokenKind Kind, Expr *Input) {
4519 UnaryOperatorKind Opc;
4520 switch (Kind) {
4521 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4521)
;
4522 case tok::plusplus: Opc = UO_PostInc; break;
4523 case tok::minusminus: Opc = UO_PostDec; break;
4524 }
4525
4526 // Since this might is a postfix expression, get rid of ParenListExprs.
4527 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4528 if (Result.isInvalid()) return ExprError();
4529 Input = Result.get();
4530
4531 return BuildUnaryOp(S, OpLoc, Opc, Input);
4532}
4533
4534/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4535///
4536/// \return true on error
4537static bool checkArithmeticOnObjCPointer(Sema &S,
4538 SourceLocation opLoc,
4539 Expr *op) {
4540 assert(op->getType()->isObjCObjectPointerType())((op->getType()->isObjCObjectPointerType()) ? static_cast
<void> (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4540, __PRETTY_FUNCTION__))
;
4541 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4542 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4543 return false;
4544
4545 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4546 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4547 << op->getSourceRange();
4548 return true;
4549}
4550
4551static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4552 auto *BaseNoParens = Base->IgnoreParens();
4553 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4554 return MSProp->getPropertyDecl()->getType()->isArrayType();
4555 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4556}
4557
4558ExprResult
4559Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4560 Expr *idx, SourceLocation rbLoc) {
4561 if (base && !base->getType().isNull() &&
4562 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4563 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4564 SourceLocation(), /*Length*/ nullptr,
4565 /*Stride=*/nullptr, rbLoc);
4566
4567 // Since this might be a postfix expression, get rid of ParenListExprs.
4568 if (isa<ParenListExpr>(base)) {
4569 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4570 if (result.isInvalid()) return ExprError();
4571 base = result.get();
4572 }
4573
4574 // Check if base and idx form a MatrixSubscriptExpr.
4575 //
4576 // Helper to check for comma expressions, which are not allowed as indices for
4577 // matrix subscript expressions.
4578 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4579 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4580 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4581 << SourceRange(base->getBeginLoc(), rbLoc);
4582 return true;
4583 }
4584 return false;
4585 };
4586 // The matrix subscript operator ([][])is considered a single operator.
4587 // Separating the index expressions by parenthesis is not allowed.
4588 if (base->getType()->isSpecificPlaceholderType(
4589 BuiltinType::IncompleteMatrixIdx) &&
4590 !isa<MatrixSubscriptExpr>(base)) {
4591 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4592 << SourceRange(base->getBeginLoc(), rbLoc);
4593 return ExprError();
4594 }
4595 // If the base is either a MatrixSubscriptExpr or a matrix type, try to create
4596 // a new MatrixSubscriptExpr.
4597 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4598 if (matSubscriptE) {
4599 if (CheckAndReportCommaError(idx))
4600 return ExprError();
4601
4602 assert(matSubscriptE->isIncomplete() &&((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript"
) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4603, __PRETTY_FUNCTION__))
4603 "base has to be an incomplete matrix subscript")((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript"
) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4603, __PRETTY_FUNCTION__))
;
4604 return CreateBuiltinMatrixSubscriptExpr(
4605 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4606 }
4607 Expr *matrixBase = base;
4608 bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4609 if (!IsMSPropertySubscript) {
4610 ExprResult result = CheckPlaceholderExpr(base);
4611 if (!result.isInvalid())
4612 matrixBase = result.get();
4613 }
4614 if (matrixBase->getType()->isMatrixType()) {
4615 if (CheckAndReportCommaError(idx))
4616 return ExprError();
4617
4618 return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc);
4619 }
4620
4621 // A comma-expression as the index is deprecated in C++2a onwards.
4622 if (getLangOpts().CPlusPlus20 &&
4623 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4624 (isa<CXXOperatorCallExpr>(idx) &&
4625 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4626 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4627 << SourceRange(base->getBeginLoc(), rbLoc);
4628 }
4629
4630 // Handle any non-overload placeholder types in the base and index
4631 // expressions. We can't handle overloads here because the other
4632 // operand might be an overloadable type, in which case the overload
4633 // resolution for the operator overload should get the first crack
4634 // at the overload.
4635 if (base->getType()->isNonOverloadPlaceholderType()) {
4636 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4637 if (!IsMSPropertySubscript) {
4638 ExprResult result = CheckPlaceholderExpr(base);
4639 if (result.isInvalid())
4640 return ExprError();
4641 base = result.get();
4642 }
4643 }
4644 if (idx->getType()->isNonOverloadPlaceholderType()) {
4645 ExprResult result = CheckPlaceholderExpr(idx);
4646 if (result.isInvalid()) return ExprError();
4647 idx = result.get();
4648 }
4649
4650 // Build an unanalyzed expression if either operand is type-dependent.
4651 if (getLangOpts().CPlusPlus &&
4652 (base->isTypeDependent() || idx->isTypeDependent())) {
4653 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4654 VK_LValue, OK_Ordinary, rbLoc);
4655 }
4656
4657 // MSDN, property (C++)
4658 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4659 // This attribute can also be used in the declaration of an empty array in a
4660 // class or structure definition. For example:
4661 // __declspec(property(get=GetX, put=PutX)) int x[];
4662 // The above statement indicates that x[] can be used with one or more array
4663 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4664 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4665 if (IsMSPropertySubscript) {
4666 // Build MS property subscript expression if base is MS property reference
4667 // or MS property subscript.
4668 return new (Context) MSPropertySubscriptExpr(
4669 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4670 }
4671
4672 // Use C++ overloaded-operator rules if either operand has record
4673 // type. The spec says to do this if either type is *overloadable*,
4674 // but enum types can't declare subscript operators or conversion
4675 // operators, so there's nothing interesting for overload resolution
4676 // to do if there aren't any record types involved.
4677 //
4678 // ObjC pointers have their own subscripting logic that is not tied
4679 // to overload resolution and so should not take this path.
4680 if (getLangOpts().CPlusPlus &&
4681 (base->getType()->isRecordType() ||
4682 (!base->getType()->isObjCObjectPointerType() &&
4683 idx->getType()->isRecordType()))) {
4684 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4685 }
4686
4687 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4688
4689 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4690 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4691
4692 return Res;
4693}
4694
4695ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4696 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4697 InitializationKind Kind =
4698 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4699 InitializationSequence InitSeq(*this, Entity, Kind, E);
4700 return InitSeq.Perform(*this, Entity, Kind, E);
4701}
4702
4703ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4704 Expr *ColumnIdx,
4705 SourceLocation RBLoc) {
4706 ExprResult BaseR = CheckPlaceholderExpr(Base);
4707 if (BaseR.isInvalid())
4708 return BaseR;
4709 Base = BaseR.get();
4710
4711 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4712 if (RowR.isInvalid())
4713 return RowR;
4714 RowIdx = RowR.get();
4715
4716 if (!ColumnIdx)
4717 return new (Context) MatrixSubscriptExpr(
4718 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4719
4720 // Build an unanalyzed expression if any of the operands is type-dependent.
4721 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4722 ColumnIdx->isTypeDependent())
4723 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4724 Context.DependentTy, RBLoc);
4725
4726 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4727 if (ColumnR.isInvalid())
4728 return ColumnR;
4729 ColumnIdx = ColumnR.get();
4730
4731 // Check that IndexExpr is an integer expression. If it is a constant
4732 // expression, check that it is less than Dim (= the number of elements in the
4733 // corresponding dimension).
4734 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4735 bool IsColumnIdx) -> Expr * {
4736 if (!IndexExpr->getType()->isIntegerType() &&
4737 !IndexExpr->isTypeDependent()) {
4738 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4739 << IsColumnIdx;
4740 return nullptr;
4741 }
4742
4743 if (Optional<llvm::APSInt> Idx =
4744 IndexExpr->getIntegerConstantExpr(Context)) {
4745 if ((*Idx < 0 || *Idx >= Dim)) {
4746 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4747 << IsColumnIdx << Dim;
4748 return nullptr;
4749 }
4750 }
4751
4752 ExprResult ConvExpr =
4753 tryConvertExprToType(IndexExpr, Context.getSizeType());
4754 assert(!ConvExpr.isInvalid() &&((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type"
) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4755, __PRETTY_FUNCTION__))
4755 "should be able to convert any integer type to size type")((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type"
) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4755, __PRETTY_FUNCTION__))
;
4756 return ConvExpr.get();
4757 };
4758
4759 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4760 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4761 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4762 if (!RowIdx || !ColumnIdx)
4763 return ExprError();
4764
4765 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4766 MTy->getElementType(), RBLoc);
4767}
4768
4769void Sema::CheckAddressOfNoDeref(const Expr *E) {
4770 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4771 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4772
4773 // For expressions like `&(*s).b`, the base is recorded and what should be
4774 // checked.
4775 const MemberExpr *Member = nullptr;
4776 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4777 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4778
4779 LastRecord.PossibleDerefs.erase(StrippedExpr);
4780}
4781
4782void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4783 QualType ResultTy = E->getType();
4784 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4785
4786 // Bail if the element is an array since it is not memory access.
4787 if (isa<ArrayType>(ResultTy))
4788 return;
4789
4790 if (ResultTy->hasAttr(attr::NoDeref)) {
4791 LastRecord.PossibleDerefs.insert(E);
4792 return;
4793 }
4794
4795 // Check if the base type is a pointer to a member access of a struct
4796 // marked with noderef.
4797 const Expr *Base = E->getBase();
4798 QualType BaseTy = Base->getType();
4799 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4800 // Not a pointer access
4801 return;
4802
4803 const MemberExpr *Member = nullptr;
4804 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4805 Member->isArrow())
4806 Base = Member->getBase();
4807
4808 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4809 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4810 LastRecord.PossibleDerefs.insert(E);
4811 }
4812}
4813
4814ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4815 Expr *LowerBound,
4816 SourceLocation ColonLocFirst,
4817 SourceLocation ColonLocSecond,
4818 Expr *Length, Expr *Stride,
4819 SourceLocation RBLoc) {
4820 if (Base->getType()->isPlaceholderType() &&
4821 !Base->getType()->isSpecificPlaceholderType(
4822 BuiltinType::OMPArraySection)) {
4823 ExprResult Result = CheckPlaceholderExpr(Base);
4824 if (Result.isInvalid())
4825 return ExprError();
4826 Base = Result.get();
4827 }
4828 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4829 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4830 if (Result.isInvalid())
4831 return ExprError();
4832 Result = DefaultLvalueConversion(Result.get());
4833 if (Result.isInvalid())
4834 return ExprError();
4835 LowerBound = Result.get();
4836 }
4837 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4838 ExprResult Result = CheckPlaceholderExpr(Length);
4839 if (Result.isInvalid())
4840 return ExprError();
4841 Result = DefaultLvalueConversion(Result.get());
4842 if (Result.isInvalid())
4843 return ExprError();
4844 Length = Result.get();
4845 }
4846 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4847 ExprResult Result = CheckPlaceholderExpr(Stride);
4848 if (Result.isInvalid())
4849 return ExprError();
4850 Result = DefaultLvalueConversion(Result.get());
4851 if (Result.isInvalid())
4852 return ExprError();
4853 Stride = Result.get();
4854 }
4855
4856 // Build an unanalyzed expression if either operand is type-dependent.
4857 if (Base->isTypeDependent() ||
4858 (LowerBound &&
4859 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4860 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4861 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4862 return new (Context) OMPArraySectionExpr(
4863 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4864 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4865 }
4866
4867 // Perform default conversions.
4868 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4869 QualType ResultTy;
4870 if (OriginalTy->isAnyPointerType()) {
4871 ResultTy = OriginalTy->getPointeeType();
4872 } else if (OriginalTy->isArrayType()) {
4873 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4874 } else {
4875 return ExprError(
4876 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4877 << Base->getSourceRange());
4878 }
4879 // C99 6.5.2.1p1
4880 if (LowerBound) {
4881 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4882 LowerBound);
4883 if (Res.isInvalid())
4884 return ExprError(Diag(LowerBound->getExprLoc(),
4885 diag::err_omp_typecheck_section_not_integer)
4886 << 0 << LowerBound->getSourceRange());
4887 LowerBound = Res.get();
4888
4889 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4890 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4891 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4892 << 0 << LowerBound->getSourceRange();
4893 }
4894 if (Length) {
4895 auto Res =
4896 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4897 if (Res.isInvalid())
4898 return ExprError(Diag(Length->getExprLoc(),
4899 diag::err_omp_typecheck_section_not_integer)
4900 << 1 << Length->getSourceRange());
4901 Length = Res.get();
4902
4903 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4904 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4905 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4906 << 1 << Length->getSourceRange();
4907 }
4908 if (Stride) {
4909 ExprResult Res =
4910 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4911 if (Res.isInvalid())
4912 return ExprError(Diag(Stride->getExprLoc(),
4913 diag::err_omp_typecheck_section_not_integer)
4914 << 1 << Stride->getSourceRange());
4915 Stride = Res.get();
4916
4917 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4918 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4919 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4920 << 1 << Stride->getSourceRange();
4921 }
4922
4923 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4924 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4925 // type. Note that functions are not objects, and that (in C99 parlance)
4926 // incomplete types are not object types.
4927 if (ResultTy->isFunctionType()) {
4928 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4929 << ResultTy << Base->getSourceRange();
4930 return ExprError();
4931 }
4932
4933 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4934 diag::err_omp_section_incomplete_type, Base))
4935 return ExprError();
4936
4937 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4938 Expr::EvalResult Result;
4939 if (LowerBound->EvaluateAsInt(Result, Context)) {
4940 // OpenMP 5.0, [2.1.5 Array Sections]
4941 // The array section must be a subset of the original array.
4942 llvm::APSInt LowerBoundValue = Result.Val.getInt();
4943 if (LowerBoundValue.isNegative()) {
4944 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4945 << LowerBound->getSourceRange();
4946 return ExprError();
4947 }
4948 }
4949 }
4950
4951 if (Length) {
4952 Expr::EvalResult Result;
4953 if (Length->EvaluateAsInt(Result, Context)) {
4954 // OpenMP 5.0, [2.1.5 Array Sections]
4955 // The length must evaluate to non-negative integers.
4956 llvm::APSInt LengthValue = Result.Val.getInt();
4957 if (LengthValue.isNegative()) {
4958 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4959 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4960 << Length->getSourceRange();
4961 return ExprError();
4962 }
4963 }
4964 } else if (ColonLocFirst.isValid() &&
4965 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4966 !OriginalTy->isVariableArrayType()))) {
4967 // OpenMP 5.0, [2.1.5 Array Sections]
4968 // When the size of the array dimension is not known, the length must be
4969 // specified explicitly.
4970 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
4971 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4972 return ExprError();
4973 }
4974
4975 if (Stride) {
4976 Expr::EvalResult Result;
4977 if (Stride->EvaluateAsInt(Result, Context)) {
4978 // OpenMP 5.0, [2.1.5 Array Sections]
4979 // The stride must evaluate to a positive integer.
4980 llvm::APSInt StrideValue = Result.Val.getInt();
4981 if (!StrideValue.isStrictlyPositive()) {
4982 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
4983 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
4984 << Stride->getSourceRange();
4985 return ExprError();
4986 }
4987 }
4988 }
4989
4990 if (!Base->getType()->isSpecificPlaceholderType(
4991 BuiltinType::OMPArraySection)) {
4992 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4993 if (Result.isInvalid())
4994 return ExprError();
4995 Base = Result.get();
4996 }
4997 return new (Context) OMPArraySectionExpr(
4998 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
4999 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5000}
5001
5002ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5003 SourceLocation RParenLoc,
5004 ArrayRef<Expr *> Dims,
5005 ArrayRef<SourceRange> Brackets) {
5006 if (Base->getType()->isPlaceholderType()) {
5007 ExprResult Result = CheckPlaceholderExpr(Base);
5008 if (Result.isInvalid())
5009 return ExprError();
5010 Result = DefaultLvalueConversion(Result.get());
5011 if (Result.isInvalid())
5012 return ExprError();
5013 Base = Result.get();
5014 }
5015 QualType BaseTy = Base->getType();
5016 // Delay analysis of the types/expressions if instantiation/specialization is
5017 // required.
5018 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5019 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5020 LParenLoc, RParenLoc, Dims, Brackets);
5021 if (!BaseTy->isPointerType() ||
5022 (!Base->isTypeDependent() &&
5023 BaseTy->getPointeeType()->isIncompleteType()))
5024 return ExprError(Diag(Base->getExprLoc(),
5025 diag::err_omp_non_pointer_type_array_shaping_base)
5026 << Base->getSourceRange());
5027
5028 SmallVector<Expr *, 4> NewDims;
5029 bool ErrorFound = false;
5030 for (Expr *Dim : Dims) {
5031 if (Dim->getType()->isPlaceholderType()) {
5032 ExprResult Result = CheckPlaceholderExpr(Dim);
5033 if (Result.isInvalid()) {
5034 ErrorFound = true;
5035 continue;
5036 }
5037 Result = DefaultLvalueConversion(Result.get());
5038 if (Result.isInvalid()) {
5039 ErrorFound = true;
5040 continue;
5041 }
5042 Dim = Result.get();
5043 }
5044 if (!Dim->isTypeDependent()) {
5045 ExprResult Result =
5046 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5047 if (Result.isInvalid()) {
5048 ErrorFound = true;
5049 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5050 << Dim->getSourceRange();
5051 continue;
5052 }
5053 Dim = Result.get();
5054 Expr::EvalResult EvResult;
5055 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5056 // OpenMP 5.0, [2.1.4 Array Shaping]
5057 // Each si is an integral type expression that must evaluate to a
5058 // positive integer.
5059 llvm::APSInt Value = EvResult.Val.getInt();
5060 if (!Value.isStrictlyPositive()) {
5061 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5062 << Value.toString(/*Radix=*/10, /*Signed=*/true)
5063 << Dim->getSourceRange();
5064 ErrorFound = true;
5065 continue;
5066 }
5067 }
5068 }
5069 NewDims.push_back(Dim);
5070 }
5071 if (ErrorFound)
5072 return ExprError();
5073 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5074 LParenLoc, RParenLoc, NewDims, Brackets);
5075}
5076
5077ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5078 SourceLocation LLoc, SourceLocation RLoc,
5079 ArrayRef<OMPIteratorData> Data) {
5080 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5081 bool IsCorrect = true;
5082 for (const OMPIteratorData &D : Data) {
5083 TypeSourceInfo *TInfo = nullptr;
5084 SourceLocation StartLoc;
5085 QualType DeclTy;
5086 if (!D.Type.getAsOpaquePtr()) {
5087 // OpenMP 5.0, 2.1.6 Iterators
5088 // In an iterator-specifier, if the iterator-type is not specified then
5089 // the type of that iterator is of int type.
5090 DeclTy = Context.IntTy;
5091 StartLoc = D.DeclIdentLoc;
5092 } else {
5093 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5094 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5095 }
5096
5097 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5098 DeclTy->containsUnexpandedParameterPack() ||
5099 DeclTy->isInstantiationDependentType();
5100 if (!IsDeclTyDependent) {
5101 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5102 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5103 // The iterator-type must be an integral or pointer type.
5104 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5105 << DeclTy;
5106 IsCorrect = false;
5107 continue;
5108 }
5109 if (DeclTy.isConstant(Context)) {
5110 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5111 // The iterator-type must not be const qualified.
5112 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5113 << DeclTy;
5114 IsCorrect = false;
5115 continue;
5116 }
5117 }
5118
5119 // Iterator declaration.
5120 assert(D.DeclIdent && "Identifier expected.")((D.DeclIdent && "Identifier expected.") ? static_cast
<void> (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5120, __PRETTY_FUNCTION__))
;
5121 // Always try to create iterator declarator to avoid extra error messages
5122 // about unknown declarations use.
5123 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5124 D.DeclIdent, DeclTy, TInfo, SC_None);
5125 VD->setImplicit();
5126 if (S) {
5127 // Check for conflicting previous declaration.
5128 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5129 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5130 ForVisibleRedeclaration);
5131 Previous.suppressDiagnostics();
5132 LookupName(Previous, S);
5133
5134 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5135 /*AllowInlineNamespace=*/false);
5136 if (!Previous.empty()) {
5137 NamedDecl *Old = Previous.getRepresentativeDecl();
5138 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5139 Diag(Old->getLocation(), diag::note_previous_definition);
5140 } else {
5141 PushOnScopeChains(VD, S);
5142 }
5143 } else {
5144 CurContext->addDecl(VD);
5145 }
5146 Expr *Begin = D.Range.Begin;
5147 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5148 ExprResult BeginRes =
5149 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5150 Begin = BeginRes.get();
5151 }
5152 Expr *End = D.Range.End;
5153 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5154 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5155 End = EndRes.get();
5156 }
5157 Expr *Step = D.Range.Step;
5158 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5159 if (!Step->getType()->isIntegralType(Context)) {
5160 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5161 << Step << Step->getSourceRange();
5162 IsCorrect = false;
5163 continue;
5164 }
5165 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5166 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5167 // If the step expression of a range-specification equals zero, the
5168 // behavior is unspecified.
5169 if (Result && Result->isNullValue()) {
5170 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5171 << Step << Step->getSourceRange();
5172 IsCorrect = false;
5173 continue;
5174 }
5175 }
5176 if (!Begin || !End || !IsCorrect) {
5177 IsCorrect = false;
5178 continue;
5179 }
5180 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5181 IDElem.IteratorDecl = VD;
5182 IDElem.AssignmentLoc = D.AssignLoc;
5183 IDElem.Range.Begin = Begin;
5184 IDElem.Range.End = End;
5185 IDElem.Range.Step = Step;
5186 IDElem.ColonLoc = D.ColonLoc;
5187 IDElem.SecondColonLoc = D.SecColonLoc;
5188 }
5189 if (!IsCorrect) {
5190 // Invalidate all created iterator declarations if error is found.
5191 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5192 if (Decl *ID = D.IteratorDecl)
5193 ID->setInvalidDecl();
5194 }
5195 return ExprError();
5196 }
5197 SmallVector<OMPIteratorHelperData, 4> Helpers;
5198 if (!CurContext->isDependentContext()) {
5199 // Build number of ityeration for each iteration range.
5200 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5201 // ((Begini-Stepi-1-Endi) / -Stepi);
5202 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5203 // (Endi - Begini)
5204 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5205 D.Range.Begin);
5206 if(!Res.isUsable()) {
5207 IsCorrect = false;
5208 continue;
5209 }
5210 ExprResult St, St1;
5211 if (D.Range.Step) {
5212 St = D.Range.Step;
5213 // (Endi - Begini) + Stepi
5214 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5215 if (!Res.isUsable()) {
5216 IsCorrect = false;
5217 continue;
5218 }
5219 // (Endi - Begini) + Stepi - 1
5220 Res =
5221 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5222 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5223 if (!Res.isUsable()) {
5224 IsCorrect = false;
5225 continue;
5226 }
5227 // ((Endi - Begini) + Stepi - 1) / Stepi
5228 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5229 if (!Res.isUsable()) {
5230 IsCorrect = false;
5231 continue;
5232 }
5233 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5234 // (Begini - Endi)
5235 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5236 D.Range.Begin, D.Range.End);
5237 if (!Res1.isUsable()) {
5238 IsCorrect = false;
5239 continue;
5240 }
5241 // (Begini - Endi) - Stepi
5242 Res1 =
5243 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5244 if (!Res1.isUsable()) {
5245 IsCorrect = false;
5246 continue;
5247 }
5248 // (Begini - Endi) - Stepi - 1
5249 Res1 =
5250 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5251 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5252 if (!Res1.isUsable()) {
5253 IsCorrect = false;
5254 continue;
5255 }
5256 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5257 Res1 =
5258 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5259 if (!Res1.isUsable()) {
5260 IsCorrect = false;
5261 continue;
5262 }
5263 // Stepi > 0.
5264 ExprResult CmpRes =
5265 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5266 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5267 if (!CmpRes.isUsable()) {
5268 IsCorrect = false;
5269 continue;
5270 }
5271 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5272 Res.get(), Res1.get());
5273 if (!Res.isUsable()) {
5274 IsCorrect = false;
5275 continue;
5276 }
5277 }
5278 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5279 if (!Res.isUsable()) {
5280 IsCorrect = false;
5281 continue;
5282 }
5283
5284 // Build counter update.
5285 // Build counter.
5286 auto *CounterVD =
5287 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5288 D.IteratorDecl->getBeginLoc(), nullptr,
5289 Res.get()->getType(), nullptr, SC_None);
5290 CounterVD->setImplicit();
5291 ExprResult RefRes =
5292 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5293 D.IteratorDecl->getBeginLoc());
5294 // Build counter update.
5295 // I = Begini + counter * Stepi;
5296 ExprResult UpdateRes;
5297 if (D.Range.Step) {
5298 UpdateRes = CreateBuiltinBinOp(
5299 D.AssignmentLoc, BO_Mul,
5300 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5301 } else {
5302 UpdateRes = DefaultLvalueConversion(RefRes.get());
5303 }
5304 if (!UpdateRes.isUsable()) {
5305 IsCorrect = false;
5306 continue;
5307 }
5308 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5309 UpdateRes.get());
5310 if (!UpdateRes.isUsable()) {
5311 IsCorrect = false;
5312 continue;
5313 }
5314 ExprResult VDRes =
5315 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5316 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5317 D.IteratorDecl->getBeginLoc());
5318 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5319 UpdateRes.get());
5320 if (!UpdateRes.isUsable()) {
5321 IsCorrect = false;
5322 continue;
5323 }
5324 UpdateRes =
5325 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5326 if (!UpdateRes.isUsable()) {
5327 IsCorrect = false;
5328 continue;
5329 }
5330 ExprResult CounterUpdateRes =
5331 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5332 if (!CounterUpdateRes.isUsable()) {
5333 IsCorrect = false;
5334 continue;
5335 }
5336 CounterUpdateRes =
5337 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5338 if (!CounterUpdateRes.isUsable()) {
5339 IsCorrect = false;
5340 continue;
5341 }
5342 OMPIteratorHelperData &HD = Helpers.emplace_back();
5343 HD.CounterVD = CounterVD;
5344 HD.Upper = Res.get();
5345 HD.Update = UpdateRes.get();
5346 HD.CounterUpdate = CounterUpdateRes.get();
5347 }
5348 } else {
5349 Helpers.assign(ID.size(), {});
5350 }
5351 if (!IsCorrect) {
5352 // Invalidate all created iterator declarations if error is found.
5353 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5354 if (Decl *ID = D.IteratorDecl)
5355 ID->setInvalidDecl();
5356 }
5357 return ExprError();
5358 }
5359 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5360 LLoc, RLoc, ID, Helpers);
5361}
5362
5363ExprResult
5364Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5365 Expr *Idx, SourceLocation RLoc) {
5366 Expr *LHSExp = Base;
5367 Expr *RHSExp = Idx;
5368
5369 ExprValueKind VK = VK_LValue;
5370 ExprObjectKind OK = OK_Ordinary;
5371
5372 // Per C++ core issue 1213, the result is an xvalue if either operand is
5373 // a non-lvalue array, and an lvalue otherwise.
5374 if (getLangOpts().CPlusPlus11) {
5375 for (auto *Op : {LHSExp, RHSExp}) {
5376 Op = Op->IgnoreImplicit();
5377 if (Op->getType()->isArrayType() && !Op->isLValue())
5378 VK = VK_XValue;
5379 }
5380 }
5381
5382 // Perform default conversions.
5383 if (!LHSExp->getType()->getAs<VectorType>()) {
5384 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5385 if (Result.isInvalid())
5386 return ExprError();
5387 LHSExp = Result.get();
5388 }
5389 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5390 if (Result.isInvalid())
5391 return ExprError();
5392 RHSExp = Result.get();
5393
5394 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5395
5396 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5397 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5398 // in the subscript position. As a result, we need to derive the array base
5399 // and index from the expression types.
5400 Expr *BaseExpr, *IndexExpr;
5401 QualType ResultType;
5402 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5403 BaseExpr = LHSExp;
5404 IndexExpr = RHSExp;
5405 ResultType = Context.DependentTy;
5406 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5407 BaseExpr = LHSExp;
5408 IndexExpr = RHSExp;
5409 ResultType = PTy->getPointeeType();
5410 } else if (const ObjCObjectPointerType *PTy =
5411 LHSTy->getAs<ObjCObjectPointerType>()) {
5412 BaseExpr = LHSExp;
5413 IndexExpr = RHSExp;
5414
5415 // Use custom logic if this should be the pseudo-object subscript
5416 // expression.
5417 if (!LangOpts.isSubscriptPointerArithmetic())
5418 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5419 nullptr);
5420
5421 ResultType = PTy->getPointeeType();
5422 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5423 // Handle the uncommon case of "123[Ptr]".
5424 BaseExpr = RHSExp;
5425 IndexExpr = LHSExp;
5426 ResultType = PTy->getPointeeType();
5427 } else if (const ObjCObjectPointerType *PTy =
5428 RHSTy->getAs<ObjCObjectPointerType>()) {
5429 // Handle the uncommon case of "123[Ptr]".
5430 BaseExpr = RHSExp;
5431 IndexExpr = LHSExp;
5432 ResultType = PTy->getPointeeType();
5433 if (!LangOpts.isSubscriptPointerArithmetic()) {
5434 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5435 << ResultType << BaseExpr->getSourceRange();
5436 return ExprError();
5437 }
5438 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5439 BaseExpr = LHSExp; // vectors: V[123]
5440 IndexExpr = RHSExp;
5441 // We apply C++ DR1213 to vector subscripting too.
5442 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5443 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5444 if (Materialized.isInvalid())
5445 return ExprError();
5446 LHSExp = Materialized.get();
5447 }
5448 VK = LHSExp->getValueKind();
5449 if (VK != VK_RValue)
5450 OK = OK_VectorComponent;
5451
5452 ResultType = VTy->getElementType();
5453 QualType BaseType = BaseExpr->getType();
5454 Qualifiers BaseQuals = BaseType.getQualifiers();
5455 Qualifiers MemberQuals = ResultType.getQualifiers();
5456 Qualifiers Combined = BaseQuals + MemberQuals;
5457 if (Combined != MemberQuals)
5458 ResultType = Context.getQualifiedType(ResultType, Combined);
5459 } else if (LHSTy->isArrayType()) {
5460 // If we see an array that wasn't promoted by
5461 // DefaultFunctionArrayLvalueConversion, it must be an array that
5462 // wasn't promoted because of the C90 rule that doesn't
5463 // allow promoting non-lvalue arrays. Warn, then
5464 // force the promotion here.
5465 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5466 << LHSExp->getSourceRange();
5467 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5468 CK_ArrayToPointerDecay).get();
5469 LHSTy = LHSExp->getType();
5470
5471 BaseExpr = LHSExp;
5472 IndexExpr = RHSExp;
5473 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5474 } else if (RHSTy->isArrayType()) {
5475 // Same as previous, except for 123[f().a] case
5476 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5477 << RHSExp->getSourceRange();
5478 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5479 CK_ArrayToPointerDecay).get();
5480 RHSTy = RHSExp->getType();
5481
5482 BaseExpr = RHSExp;
5483 IndexExpr = LHSExp;
5484 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5485 } else {
5486 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5487 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5488 }
5489 // C99 6.5.2.1p1
5490 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5491 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5492 << IndexExpr->getSourceRange());
5493
5494 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5495 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5496 && !IndexExpr->isTypeDependent())
5497 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5498
5499 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5500 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5501 // type. Note that Functions are not objects, and that (in C99 parlance)
5502 // incomplete types are not object types.
5503 if (ResultType->isFunctionType()) {
5504 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5505 << ResultType << BaseExpr->getSourceRange();
5506 return ExprError();
5507 }
5508
5509 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5510 // GNU extension: subscripting on pointer to void
5511 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5512 << BaseExpr->getSourceRange();
5513
5514 // C forbids expressions of unqualified void type from being l-values.
5515 // See IsCForbiddenLValueType.
5516 if (!ResultType.hasQualifiers()) VK = VK_RValue;
5517 } else if (!ResultType->isDependentType() &&
5518 RequireCompleteSizedType(
5519 LLoc, ResultType,
5520 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5521 return ExprError();
5522
5523 assert(VK == VK_RValue || LangOpts.CPlusPlus ||((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType
()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5524, __PRETTY_FUNCTION__))
5524 !ResultType.isCForbiddenLValueType())((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType
()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5524, __PRETTY_FUNCTION__))
;
5525
5526 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5527 FunctionScopes.size() > 1) {
5528 if (auto *TT =
5529 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5530 for (auto I = FunctionScopes.rbegin(),
5531 E = std::prev(FunctionScopes.rend());
5532 I != E; ++I) {
5533 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5534 if (CSI == nullptr)
5535 break;
5536 DeclContext *DC = nullptr;
5537 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5538 DC = LSI->CallOperator;
5539 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5540 DC = CRSI->TheCapturedDecl;
5541 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5542 DC = BSI->TheDecl;
5543 if (DC) {
5544 if (DC->containsDecl(TT->getDecl()))
5545 break;
5546 captureVariablyModifiedType(
5547 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5548 }
5549 }
5550 }
5551 }
5552
5553 return new (Context)
5554 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5555}
5556
5557bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5558 ParmVarDecl *Param) {
5559 if (Param->hasUnparsedDefaultArg()) {
5560 // If we've already cleared out the location for the default argument,
5561 // that means we're parsing it right now.
5562 if (!UnparsedDefaultArgLocs.count(Param)) {
5563 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5564 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5565 Param->setInvalidDecl();
5566 return true;
5567 }
5568
5569 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5570 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5571 Diag(UnparsedDefaultArgLocs[Param],
5572 diag::note_default_argument_declared_here);
5573 return true;
5574 }
5575
5576 if (Param->hasUninstantiatedDefaultArg() &&
5577 InstantiateDefaultArgument(CallLoc, FD, Param))
5578 return true;
5579
5580 assert(Param->hasInit() && "default argument but no initializer?")((Param->hasInit() && "default argument but no initializer?"
) ? static_cast<void> (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5580, __PRETTY_FUNCTION__))
;
5581
5582 // If the default expression creates temporaries, we need to
5583 // push them to the current stack of expression temporaries so they'll
5584 // be properly destroyed.
5585 // FIXME: We should really be rebuilding the default argument with new
5586 // bound temporaries; see the comment in PR5810.
5587 // We don't need to do that with block decls, though, because
5588 // blocks in default argument expression can never capture anything.
5589 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5590 // Set the "needs cleanups" bit regardless of whether there are
5591 // any explicit objects.
5592 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5593
5594 // Append all the objects to the cleanup list. Right now, this
5595 // should always be a no-op, because blocks in default argument
5596 // expressions should never be able to capture anything.
5597 assert(!Init->getNumObjects() &&((!Init->getNumObjects() && "default argument expression has capturing blocks?"
) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5598, __PRETTY_FUNCTION__))
5598 "default argument expression has capturing blocks?")((!Init->getNumObjects() && "default argument expression has capturing blocks?"
) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5598, __PRETTY_FUNCTION__))
;
5599 }
5600
5601 // We already type-checked the argument, so we know it works.
5602 // Just mark all of the declarations in this potentially-evaluated expression
5603 // as being "referenced".
5604 EnterExpressionEvaluationContext EvalContext(
5605 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5606 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5607 /*SkipLocalVariables=*/true);
5608 return false;
5609}
5610
5611ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5612 FunctionDecl *FD, ParmVarDecl *Param) {
5613 assert(Param->hasDefaultArg() && "can't build nonexistent default arg")((Param->hasDefaultArg() && "can't build nonexistent default arg"
) ? static_cast<void> (0) : __assert_fail ("Param->hasDefaultArg() && \"can't build nonexistent default arg\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5613, __PRETTY_FUNCTION__))
;
5614 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5615 return ExprError();
5616 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5617}
5618
5619Sema::VariadicCallType
5620Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5621 Expr *Fn) {
5622 if (Proto && Proto->isVariadic()) {
5623 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5624 return VariadicConstructor;
5625 else if (Fn && Fn->getType()->isBlockPointerType())
5626 return VariadicBlock;
5627 else if (FDecl) {
5628 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5629 if (Method->isInstance())
5630 return VariadicMethod;
5631 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5632 return VariadicMethod;
5633 return VariadicFunction;
5634 }
5635 return VariadicDoesNotApply;
5636}
5637
5638namespace {
5639class FunctionCallCCC final : public FunctionCallFilterCCC {
5640public:
5641 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5642 unsigned NumArgs, MemberExpr *ME)
5643 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5644 FunctionName(FuncName) {}
5645
5646 bool ValidateCandidate(const TypoCorrection &candidate) override {
5647 if (!candidate.getCorrectionSpecifier() ||
5648 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5649 return false;
5650 }
5651
5652 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5653 }
5654
5655 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5656 return std::make_unique<FunctionCallCCC>(*this);
5657 }
5658
5659private:
5660 const IdentifierInfo *const FunctionName;
5661};
5662}
5663
5664static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5665 FunctionDecl *FDecl,
5666 ArrayRef<Expr *> Args) {
5667 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5668 DeclarationName FuncName = FDecl->getDeclName();
5669 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5670
5671 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5672 if (TypoCorrection Corrected = S.CorrectTypo(
5673 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5674 S.getScopeForContext(S.CurContext), nullptr, CCC,
5675 Sema::CTK_ErrorRecovery)) {
5676 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5677 if (Corrected.isOverloaded()) {
5678 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5679 OverloadCandidateSet::iterator Best;
5680 for (NamedDecl *CD : Corrected) {
5681 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5682 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5683 OCS);
5684 }
5685 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5686 case OR_Success:
5687 ND = Best->FoundDecl;
5688 Corrected.setCorrectionDecl(ND);
5689 break;
5690 default:
5691 break;
5692 }
5693 }
5694 ND = ND->getUnderlyingDecl();
5695 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5696 return Corrected;
5697 }
5698 }
5699 return TypoCorrection();
5700}
5701
5702/// ConvertArgumentsForCall - Converts the arguments specified in
5703/// Args/NumArgs to the parameter types of the function FDecl with
5704/// function prototype Proto. Call is the call expression itself, and
5705/// Fn is the function expression. For a C++ member function, this
5706/// routine does not attempt to convert the object argument. Returns
5707/// true if the call is ill-formed.
5708bool
5709Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5710 FunctionDecl *FDecl,
5711 const FunctionProtoType *Proto,
5712 ArrayRef<Expr *> Args,
5713 SourceLocation RParenLoc,
5714 bool IsExecConfig) {
5715 // Bail out early if calling a builtin with custom typechecking.
5716 if (FDecl)
5717 if (unsigned ID = FDecl->getBuiltinID())
5718 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5719 return false;
5720
5721 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5722 // assignment, to the types of the corresponding parameter, ...
5723 unsigned NumParams = Proto->getNumParams();
5724 bool Invalid = false;
5725 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5726 unsigned FnKind = Fn->getType()->isBlockPointerType()
5727 ? 1 /* block */
5728 : (IsExecConfig ? 3 /* kernel function (exec config) */
5729 : 0 /* function */);
5730
5731 // If too few arguments are available (and we don't have default
5732 // arguments for the remaining parameters), don't make the call.
5733 if (Args.size() < NumParams) {
5734 if (Args.size() < MinArgs) {
5735 TypoCorrection TC;
5736 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5737 unsigned diag_id =
5738 MinArgs == NumParams && !Proto->isVariadic()
5739 ? diag::err_typecheck_call_too_few_args_suggest
5740 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5741 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5742 << static_cast<unsigned>(Args.size())
5743 << TC.getCorrectionRange());
5744 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5745 Diag(RParenLoc,
5746 MinArgs == NumParams && !Proto->isVariadic()
5747 ? diag::err_typecheck_call_too_few_args_one
5748 : diag::err_typecheck_call_too_few_args_at_least_one)
5749 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5750 else
5751 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5752 ? diag::err_typecheck_call_too_few_args
5753 : diag::err_typecheck_call_too_few_args_at_least)
5754 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5755 << Fn->getSourceRange();
5756
5757 // Emit the location of the prototype.
5758 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5759 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5760
5761 return true;
5762 }
5763 // We reserve space for the default arguments when we create
5764 // the call expression, before calling ConvertArgumentsForCall.
5765 assert((Call->getNumArgs() == NumParams) &&(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!"
) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5766, __PRETTY_FUNCTION__))
5766 "We should have reserved space for the default arguments before!")(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!"
) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5766, __PRETTY_FUNCTION__))
;
5767 }
5768
5769 // If too many are passed and not variadic, error on the extras and drop
5770 // them.
5771 if (Args.size() > NumParams) {
5772 if (!Proto->isVariadic()) {
5773 TypoCorrection TC;
5774 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5775 unsigned diag_id =
5776 MinArgs == NumParams && !Proto->isVariadic()
5777 ? diag::err_typecheck_call_too_many_args_suggest
5778 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5779 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5780 << static_cast<unsigned>(Args.size())
5781 << TC.getCorrectionRange());
5782 } else if (NumParams == 1 && FDecl &&
5783 FDecl->getParamDecl(0)->getDeclName())
5784 Diag(Args[NumParams]->getBeginLoc(),
5785 MinArgs == NumParams
5786 ? diag::err_typecheck_call_too_many_args_one
5787 : diag::err_typecheck_call_too_many_args_at_most_one)
5788 << FnKind << FDecl->getParamDecl(0)
5789 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5790 << SourceRange(Args[NumParams]->getBeginLoc(),
5791 Args.back()->getEndLoc());
5792 else
5793 Diag(Args[NumParams]->getBeginLoc(),
5794 MinArgs == NumParams
5795 ? diag::err_typecheck_call_too_many_args
5796 : diag::err_typecheck_call_too_many_args_at_most)
5797 << FnKind << NumParams << static_cast<unsigned>(Args.size())
5798 << Fn->getSourceRange()
5799 << SourceRange(Args[NumParams]->getBeginLoc(),
5800 Args.back()->getEndLoc());
5801
5802 // Emit the location of the prototype.
5803 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5804 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5805
5806 // This deletes the extra arguments.
5807 Call->shrinkNumArgs(NumParams);
5808 return true;
5809 }
5810 }
5811 SmallVector<Expr *, 8> AllArgs;
5812 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5813
5814 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5815 AllArgs, CallType);
5816 if (Invalid)
5817 return true;
5818 unsigned TotalNumArgs = AllArgs.size();
5819 for (unsigned i = 0; i < TotalNumArgs; ++i)
5820 Call->setArg(i, AllArgs[i]);
5821
5822 return false;
5823}
5824
5825bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5826 const FunctionProtoType *Proto,
5827 unsigned FirstParam, ArrayRef<Expr *> Args,
5828 SmallVectorImpl<Expr *> &AllArgs,
5829 VariadicCallType CallType, bool AllowExplicit,
5830 bool IsListInitialization) {
5831 unsigned NumParams = Proto->getNumParams();
5832 bool Invalid = false;
5833 size_t ArgIx = 0;
5834 // Continue to check argument types (even if we have too few/many args).
5835 for (unsigned i = FirstParam; i < NumParams; i++) {
5836 QualType ProtoArgType = Proto->getParamType(i);
5837
5838 Expr *Arg;
5839 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5840 if (ArgIx < Args.size()) {
5841 Arg = Args[ArgIx++];
5842
5843 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5844 diag::err_call_incomplete_argument, Arg))
5845 return true;
5846
5847 // Strip the unbridged-cast placeholder expression off, if applicable.
5848 bool CFAudited = false;
5849 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5850 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5851 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5852 Arg = stripARCUnbridgedCast(Arg);
5853 else if (getLangOpts().ObjCAutoRefCount &&
5854 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5855 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5856 CFAudited = true;
5857
5858 if (Proto->getExtParameterInfo(i).isNoEscape())
5859 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5860 BE->getBlockDecl()->setDoesNotEscape();
5861
5862 InitializedEntity Entity =
5863 Param ? InitializedEntity::InitializeParameter(Context, Param,
5864 ProtoArgType)
5865 : InitializedEntity::InitializeParameter(
5866 Context, ProtoArgType, Proto->isParamConsumed(i));
5867
5868 // Remember that parameter belongs to a CF audited API.
5869 if (CFAudited)
5870 Entity.setParameterCFAudited();
5871
5872 ExprResult ArgE = PerformCopyInitialization(
5873 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5874 if (ArgE.isInvalid())
5875 return true;
5876
5877 Arg = ArgE.getAs<Expr>();
5878 } else {
5879 assert(Param && "can't use default arguments without a known callee")((Param && "can't use default arguments without a known callee"
) ? static_cast<void> (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5879, __PRETTY_FUNCTION__))
;
5880
5881 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5882 if (ArgExpr.isInvalid())
5883 return true;
5884
5885 Arg = ArgExpr.getAs<Expr>();
5886 }
5887
5888 // Check for array bounds violations for each argument to the call. This
5889 // check only triggers warnings when the argument isn't a more complex Expr
5890 // with its own checking, such as a BinaryOperator.
5891 CheckArrayAccess(Arg);
5892
5893 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5894 CheckStaticArrayArgument(CallLoc, Param, Arg);
5895
5896 AllArgs.push_back(Arg);
5897 }
5898
5899 // If this is a variadic call, handle args passed through "...".
5900 if (CallType != VariadicDoesNotApply) {
5901 // Assume that extern "C" functions with variadic arguments that
5902 // return __unknown_anytype aren't *really* variadic.
5903 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5904 FDecl->isExternC()) {
5905 for (Expr *A : Args.slice(ArgIx)) {
5906 QualType paramType; // ignored
5907 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5908 Invalid |= arg.isInvalid();
5909 AllArgs.push_back(arg.get());
5910 }
5911
5912 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5913 } else {
5914 for (Expr *A : Args.slice(ArgIx)) {
5915 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5916 Invalid |= Arg.isInvalid();
5917 AllArgs.push_back(Arg.get());
5918 }
5919 }
5920
5921 // Check for array bounds violations.
5922 for (Expr *A : Args.slice(ArgIx))
5923 CheckArrayAccess(A);
5924 }
5925 return Invalid;
5926}
5927
5928static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5929 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5930 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5931 TL = DTL.getOriginalLoc();
5932 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5933 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5934 << ATL.getLocalSourceRange();
5935}
5936
5937/// CheckStaticArrayArgument - If the given argument corresponds to a static
5938/// array parameter, check that it is non-null, and that if it is formed by
5939/// array-to-pointer decay, the underlying array is sufficiently large.
5940///
5941/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5942/// array type derivation, then for each call to the function, the value of the
5943/// corresponding actual argument shall provide access to the first element of
5944/// an array with at least as many elements as specified by the size expression.
5945void
5946Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5947 ParmVarDecl *Param,
5948 const Expr *ArgExpr) {
5949 // Static array parameters are not supported in C++.
5950 if (!Param || getLangOpts().CPlusPlus)
5951 return;
5952
5953 QualType OrigTy = Param->getOriginalType();
5954
5955 const ArrayType *AT = Context.getAsArrayType(OrigTy);
5956 if (!AT || AT->getSizeModifier() != ArrayType::Static)
5957 return;
5958
5959 if (ArgExpr->isNullPointerConstant(Context,
5960 Expr::NPC_NeverValueDependent)) {
5961 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5962 DiagnoseCalleeStaticArrayParam(*this, Param);
5963 return;
5964 }
5965
5966 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5967 if (!CAT)
5968 return;
5969
5970 const ConstantArrayType *ArgCAT =
5971 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5972 if (!ArgCAT)
5973 return;
5974
5975 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5976 ArgCAT->getElementType())) {
5977 if (ArgCAT->getSize().ult(CAT->getSize())) {
5978 Diag(CallLoc, diag::warn_static_array_too_small)
5979 << ArgExpr->getSourceRange()
5980 << (unsigned)ArgCAT->getSize().getZExtValue()
5981 << (unsigned)CAT->getSize().getZExtValue() << 0;
5982 DiagnoseCalleeStaticArrayParam(*this, Param);
5983 }
5984 return;
5985 }
5986
5987 Optional<CharUnits> ArgSize =
5988 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5989 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5990 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5991 Diag(CallLoc, diag::warn_static_array_too_small)
5992 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5993 << (unsigned)ParmSize->getQuantity() << 1;
5994 DiagnoseCalleeStaticArrayParam(*this, Param);
5995 }
5996}
5997
5998/// Given a function expression of unknown-any type, try to rebuild it
5999/// to have a function type.
6000static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6001
6002/// Is the given type a placeholder that we need to lower out
6003/// immediately during argument processing?
6004static bool isPlaceholderToRemoveAsArg(QualType type) {
6005 // Placeholders are never sugared.
6006 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6007 if (!placeholder) return false;
6008
6009 switch (placeholder->getKind()) {
6010 // Ignore all the non-placeholder types.
6011#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6012 case BuiltinType::Id:
6013#include "clang/Basic/OpenCLImageTypes.def"
6014#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6015 case BuiltinType::Id:
6016#include "clang/Basic/OpenCLExtensionTypes.def"