Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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